setting.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. package controller
  2. import (
  3. "errors"
  4. "strconv"
  5. "time"
  6. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  7. "github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
  8. "github.com/mhsanaei/3x-ui/v3/internal/web/entity"
  9. "github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
  10. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  11. "github.com/mhsanaei/3x-ui/v3/internal/web/service/email"
  12. "github.com/mhsanaei/3x-ui/v3/internal/web/service/panel"
  13. "github.com/mhsanaei/3x-ui/v3/internal/web/session"
  14. "github.com/gin-gonic/gin"
  15. )
  16. // updateUserForm represents the form for updating user credentials.
  17. type updateUserForm struct {
  18. OldUsername string `json:"oldUsername" form:"oldUsername"`
  19. OldPassword string `json:"oldPassword" form:"oldPassword"`
  20. NewUsername string `json:"newUsername" form:"newUsername"`
  21. NewPassword string `json:"newPassword" form:"newPassword"`
  22. TwoFactorCode string `json:"twoFactorCode" form:"twoFactorCode"`
  23. }
  24. type updateSettingForm struct {
  25. entity.AllSetting
  26. TwoFactorCode string `json:"twoFactorCode" form:"twoFactorCode"`
  27. }
  28. // SettingController handles settings and user management operations.
  29. type SettingController struct {
  30. settingService service.SettingService
  31. userService panel.UserService
  32. panelService panel.PanelService
  33. apiTokenService panel.ApiTokenService
  34. xrayService service.XrayService
  35. }
  36. // NewSettingController creates a new SettingController and initializes its routes.
  37. func NewSettingController(g *gin.RouterGroup) *SettingController {
  38. a := &SettingController{}
  39. a.initRouter(g)
  40. return a
  41. }
  42. // initRouter sets up the routes for settings management.
  43. func (a *SettingController) initRouter(g *gin.RouterGroup) {
  44. g = g.Group("/setting")
  45. g.POST("/all", a.getAllSetting)
  46. g.POST("/defaultSettings", a.getDefaultSettings)
  47. g.POST("/update", a.updateSetting)
  48. g.POST("/updateUser", a.updateUser)
  49. g.POST("/restartPanel", a.restartPanel)
  50. g.GET("/getDefaultJsonConfig", a.getDefaultXrayConfig)
  51. g.GET("/apiTokens", a.listApiTokens)
  52. g.POST("/apiTokens/create", a.createApiToken)
  53. g.POST("/apiTokens/delete/:id", a.deleteApiToken)
  54. g.POST("/apiTokens/setEnabled/:id", a.setApiTokenEnabled)
  55. g.POST("/testSmtp", a.testSmtp)
  56. g.POST("/testTgBot", a.testTgBot)
  57. }
  58. // getAllSetting retrieves all current settings as the browser-safe view:
  59. // secret values are redacted and surfaced as has* presence flags instead.
  60. func (a *SettingController) getAllSetting(c *gin.Context) {
  61. allSetting, err := a.settingService.GetAllSettingView()
  62. if err != nil {
  63. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.getSettings"), err)
  64. return
  65. }
  66. jsonObj(c, allSetting, nil)
  67. }
  68. // getDefaultSettings retrieves the default settings based on the host.
  69. func (a *SettingController) getDefaultSettings(c *gin.Context) {
  70. result, err := a.settingService.GetDefaultSettings(c.Request.Host)
  71. if err != nil {
  72. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.getSettings"), err)
  73. return
  74. }
  75. jsonObj(c, result, nil)
  76. }
  77. // updateSetting updates all settings with the provided data.
  78. func (a *SettingController) updateSetting(c *gin.Context) {
  79. form, ok := middleware.BindAndValidate[updateSettingForm](c)
  80. if !ok {
  81. return
  82. }
  83. allSetting := &form.AllSetting
  84. oldTwoFactor, twoFactorErr := a.settingService.GetTwoFactorEnable()
  85. oldPanelOutbound, _ := a.settingService.GetPanelOutbound()
  86. oldTgEnable, _ := a.settingService.GetTgbotEnabled()
  87. oldTgToken, _ := a.settingService.GetTgBotToken()
  88. oldTgChatId, _ := a.settingService.GetTgBotChatId()
  89. oldTgAPIServer, _ := a.settingService.GetTgBotAPIServer()
  90. if twoFactorErr == nil && oldTwoFactor && !allSetting.TwoFactorEnable {
  91. if err := a.settingService.VerifyTwoFactorCode(form.TwoFactorCode); err != nil {
  92. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
  93. return
  94. }
  95. }
  96. err := a.settingService.UpdateAllSetting(allSetting)
  97. if err == nil && twoFactorErr == nil && !oldTwoFactor && allSetting.TwoFactorEnable {
  98. if bumpErr := a.userService.BumpLoginEpoch(); bumpErr != nil {
  99. err = bumpErr
  100. }
  101. }
  102. if err == nil && form.PanelOutbound != oldPanelOutbound {
  103. // The egress bridge lives in the generated config; reconcile the
  104. // running core. One SOCKS inbound plus one routing rule — both
  105. // hot-appliable, so this normally does not restart Xray.
  106. if applyErr := a.xrayService.RestartXray(false); applyErr != nil {
  107. logger.Warning("apply panel outbound change failed:", applyErr)
  108. }
  109. }
  110. // UpdateAllSetting already restored a redacted-blank token, so allSetting.TgBotToken is the effective value to compare.
  111. if err == nil && reloadTgbotFunc != nil {
  112. tgChanged := oldTgEnable != allSetting.TgBotEnable ||
  113. (allSetting.TgBotEnable && (oldTgToken != allSetting.TgBotToken ||
  114. oldTgChatId != allSetting.TgBotChatId ||
  115. oldTgAPIServer != allSetting.TgBotAPIServer))
  116. if tgChanged {
  117. reloadTgbotFunc()
  118. }
  119. }
  120. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
  121. }
  122. // updateUser updates the current user's username and password.
  123. func (a *SettingController) updateUser(c *gin.Context) {
  124. form := &updateUserForm{}
  125. err := c.ShouldBind(form)
  126. if err != nil {
  127. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
  128. return
  129. }
  130. user := session.GetLoginUser(c)
  131. if user.Username != form.OldUsername || !crypto.CheckPasswordHash(user.Password, form.OldPassword) {
  132. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifyUserError"), errors.New(I18nWeb(c, "pages.settings.toasts.originalUserPassIncorrect")))
  133. return
  134. }
  135. if form.NewUsername == "" || form.NewPassword == "" {
  136. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifyUserError"), errors.New(I18nWeb(c, "pages.settings.toasts.userPassMustBeNotEmpty")))
  137. return
  138. }
  139. if err := a.settingService.VerifyTwoFactorCode(form.TwoFactorCode); err != nil {
  140. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifyUserError"), err)
  141. return
  142. }
  143. err = a.userService.UpdateUser(user.Id, form.NewUsername, form.NewPassword)
  144. if err == nil {
  145. user.Username = form.NewUsername
  146. user.Password, _ = crypto.HashPasswordAsBcrypt(form.NewPassword)
  147. if saveErr := session.SetLoginUser(c, user); saveErr != nil {
  148. err = saveErr
  149. }
  150. }
  151. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifyUser"), err)
  152. }
  153. // restartPanel restarts the panel service after a delay.
  154. func (a *SettingController) restartPanel(c *gin.Context) {
  155. err := a.panelService.RestartPanel(time.Second * 3)
  156. jsonMsg(c, I18nWeb(c, "pages.settings.restartPanelSuccess"), err)
  157. }
  158. // getDefaultXrayConfig retrieves the default Xray configuration.
  159. func (a *SettingController) getDefaultXrayConfig(c *gin.Context) {
  160. defaultJsonConfig, err := a.settingService.GetDefaultXrayConfig()
  161. if err != nil {
  162. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.getSettings"), err)
  163. return
  164. }
  165. jsonObj(c, defaultJsonConfig, nil)
  166. }
  167. type apiTokenCreateForm struct {
  168. Name string `json:"name" form:"name"`
  169. }
  170. type apiTokenEnabledForm struct {
  171. Enabled bool `json:"enabled" form:"enabled"`
  172. }
  173. func (a *SettingController) listApiTokens(c *gin.Context) {
  174. rows, err := a.apiTokenService.List()
  175. if err != nil {
  176. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.getSettings"), err)
  177. return
  178. }
  179. jsonObj(c, rows, nil)
  180. }
  181. func (a *SettingController) createApiToken(c *gin.Context) {
  182. form := &apiTokenCreateForm{}
  183. if err := c.ShouldBind(form); err != nil {
  184. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
  185. return
  186. }
  187. row, err := a.apiTokenService.Create(form.Name)
  188. if err != nil {
  189. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
  190. return
  191. }
  192. jsonObj(c, row, nil)
  193. }
  194. func (a *SettingController) deleteApiToken(c *gin.Context) {
  195. id, err := strconv.Atoi(c.Param("id"))
  196. if err != nil {
  197. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
  198. return
  199. }
  200. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), a.apiTokenService.Delete(id))
  201. }
  202. func (a *SettingController) setApiTokenEnabled(c *gin.Context) {
  203. id, err := strconv.Atoi(c.Param("id"))
  204. if err != nil {
  205. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
  206. return
  207. }
  208. form := &apiTokenEnabledForm{}
  209. if bindErr := c.ShouldBind(form); bindErr != nil {
  210. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), bindErr)
  211. return
  212. }
  213. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), a.apiTokenService.SetEnabled(id, form.Enabled))
  214. }
  215. func (a *SettingController) testSmtp(c *gin.Context) {
  216. if emailService == nil {
  217. jsonMsg(c, I18nWeb(c, "pages.settings.smtpNotInitialized"), errors.New("email service not available"))
  218. return
  219. }
  220. logger.Info("SMTP test: starting...")
  221. result := emailService.TestConnection()
  222. if !result.Success {
  223. logger.Warning("SMTP test failed at", result.Stage+":", result.Message)
  224. c.JSON(200, gin.H{
  225. "success": false,
  226. "stage": result.Stage,
  227. "msg": result.Message,
  228. })
  229. return
  230. }
  231. logger.Info("SMTP test: success")
  232. c.JSON(200, gin.H{
  233. "success": true,
  234. "stage": result.Stage,
  235. "msg": result.Message,
  236. })
  237. }
  238. func (a *SettingController) testTgBot(c *gin.Context) {
  239. enabled, err := a.settingService.GetTgbotEnabled()
  240. if err != nil || !enabled {
  241. jsonMsg(c, I18nWeb(c, "pages.settings.tgBotNotEnabled"), errors.New("telegram bot disabled"))
  242. return
  243. }
  244. // Import tgbot package would create a circular dependency, so we call
  245. // the test through the global function registered at startup.
  246. if testTgFunc != nil {
  247. if err := testTgFunc(); err != nil {
  248. jsonMsg(c, I18nWeb(c, "pages.settings.tgTestFailed")+": "+err.Error(), err)
  249. return
  250. }
  251. jsonMsg(c, I18nWeb(c, "pages.settings.tgTestSuccess"), nil)
  252. return
  253. }
  254. jsonMsg(c, I18nWeb(c, "pages.settings.tgBotNotRunning"), errors.New("bot not started"))
  255. }
  256. // testTgFunc is set from web layer to test Telegram sending without circular imports.
  257. var testTgFunc func() error
  258. // SetTestTgFunc registers the function used to test Telegram sending.
  259. func SetTestTgFunc(fn func() error) { testTgFunc = fn }
  260. // reloadTgbotFunc is wired from the web layer; importing tgbot here would be a circular dependency.
  261. var reloadTgbotFunc func()
  262. func SetReloadTgbotFunc(fn func()) { reloadTgbotFunc = fn }
  263. // emailService is set from web layer.
  264. var emailService *email.EmailService
  265. // SetEmailService registers the email service for test endpoints.
  266. func SetEmailService(s *email.EmailService) { emailService = s }