1
0

setting.go 11 KB

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