setting.go 12 KB

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