1
0

setting.go 14 KB

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