1
0

setting.go 9.4 KB

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