setting.go 11 KB

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