index.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. package controller
  2. import (
  3. "net/http"
  4. "text/template"
  5. "time"
  6. "github.com/mhsanaei/3x-ui/v2/logger"
  7. "github.com/mhsanaei/3x-ui/v2/web/middleware"
  8. "github.com/mhsanaei/3x-ui/v2/web/service"
  9. "github.com/mhsanaei/3x-ui/v2/web/session"
  10. "github.com/gin-gonic/gin"
  11. )
  12. // LoginForm represents the login request structure.
  13. type LoginForm struct {
  14. Username string `json:"username" form:"username"`
  15. Password string `json:"password" form:"password"`
  16. TwoFactorCode string `json:"twoFactorCode" form:"twoFactorCode"`
  17. }
  18. // IndexController handles the main index and login-related routes.
  19. type IndexController struct {
  20. BaseController
  21. settingService service.SettingService
  22. userService service.UserService
  23. tgbot service.Tgbot
  24. }
  25. // NewIndexController creates a new IndexController and initializes its routes.
  26. func NewIndexController(g *gin.RouterGroup) *IndexController {
  27. a := &IndexController{}
  28. a.initRouter(g)
  29. return a
  30. }
  31. // initRouter sets up the routes for index, login, logout, and two-factor authentication.
  32. func (a *IndexController) initRouter(g *gin.RouterGroup) {
  33. g.GET("/", a.index)
  34. g.GET("/logout", a.logout)
  35. // Public CSRF endpoint — the SPA login page (served by Vite in
  36. // dev or by serveDistPage in prod) needs a token to POST /login,
  37. // but the panel-side /panel/csrf-token sits behind checkLogin.
  38. // EnsureCSRFToken creates a session token even for anonymous
  39. // callers, so any pre-login flow can bootstrap from here.
  40. g.GET("/csrf-token", a.csrfToken)
  41. g.POST("/login", middleware.CSRFMiddleware(), a.login)
  42. g.POST("/getTwoFactorEnable", middleware.CSRFMiddleware(), a.getTwoFactorEnable)
  43. }
  44. // index handles the root route, redirecting logged-in users to the panel or showing the login page.
  45. func (a *IndexController) index(c *gin.Context) {
  46. if session.IsLogin(c) {
  47. c.Redirect(http.StatusTemporaryRedirect, "panel/")
  48. return
  49. }
  50. serveDistPage(c, "login.html")
  51. }
  52. // login handles user authentication and session creation.
  53. func (a *IndexController) login(c *gin.Context) {
  54. var form LoginForm
  55. if err := c.ShouldBind(&form); err != nil {
  56. pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.invalidFormData"))
  57. return
  58. }
  59. if form.Username == "" {
  60. pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.emptyUsername"))
  61. return
  62. }
  63. if form.Password == "" {
  64. pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.emptyPassword"))
  65. return
  66. }
  67. remoteIP := getRemoteIp(c)
  68. safeUser := template.HTMLEscapeString(form.Username)
  69. timeStr := time.Now().Format("2006-01-02 15:04:05")
  70. if blockedUntil, ok := defaultLoginLimiter.allow(remoteIP, form.Username); !ok {
  71. reason := "too many failed attempts"
  72. logger.Warningf("failed login: username=%q, IP=%q, reason=%q, blocked_until=%s", safeUser, remoteIP, reason, blockedUntil.Format(time.RFC3339))
  73. a.tgbot.UserLoginNotify(service.LoginAttempt{
  74. Username: safeUser,
  75. IP: remoteIP,
  76. Time: timeStr,
  77. Status: service.LoginFail,
  78. Reason: reason,
  79. })
  80. pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.wrongUsernameOrPassword"))
  81. return
  82. }
  83. user, checkErr := a.userService.CheckUser(form.Username, form.Password, form.TwoFactorCode)
  84. if user == nil {
  85. reason := loginFailureReason(checkErr)
  86. if blockedUntil, blocked := defaultLoginLimiter.registerFailure(remoteIP, form.Username); blocked {
  87. logger.Warningf("failed login: username=%q, IP=%q, reason=%q, blocked_until=%s", safeUser, remoteIP, reason, blockedUntil.Format(time.RFC3339))
  88. } else {
  89. logger.Warningf("failed login: username=%q, IP=%q, reason=%q", safeUser, remoteIP, reason)
  90. }
  91. a.tgbot.UserLoginNotify(service.LoginAttempt{
  92. Username: safeUser,
  93. IP: remoteIP,
  94. Time: timeStr,
  95. Status: service.LoginFail,
  96. Reason: reason,
  97. })
  98. pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.wrongUsernameOrPassword"))
  99. return
  100. }
  101. defaultLoginLimiter.registerSuccess(remoteIP, form.Username)
  102. logger.Infof("%s logged in successfully, Ip Address: %s\n", safeUser, remoteIP)
  103. a.tgbot.UserLoginNotify(service.LoginAttempt{
  104. Username: safeUser,
  105. IP: remoteIP,
  106. Time: timeStr,
  107. Status: service.LoginSuccess,
  108. })
  109. if err := session.SetLoginUser(c, user); err != nil {
  110. logger.Warning("Unable to save session:", err)
  111. return
  112. }
  113. logger.Infof("%s logged in successfully", safeUser)
  114. jsonMsg(c, I18nWeb(c, "pages.login.toasts.successLogin"), nil)
  115. }
  116. func loginFailureReason(err error) string {
  117. if err != nil && err.Error() == "invalid 2fa code" {
  118. return "invalid 2FA code"
  119. }
  120. return "invalid credentials"
  121. }
  122. // logout handles user logout by clearing the session and redirecting to the login page.
  123. func (a *IndexController) logout(c *gin.Context) {
  124. user := session.GetLoginUser(c)
  125. if user != nil {
  126. logger.Infof("%s logged out successfully", user.Username)
  127. }
  128. if err := session.ClearSession(c); err != nil {
  129. logger.Warning("Unable to clear session on logout:", err)
  130. }
  131. c.Redirect(http.StatusTemporaryRedirect, c.GetString("base_path"))
  132. }
  133. // csrfToken returns the session CSRF token. Public — the login page
  134. // needs a token before authenticating.
  135. func (a *IndexController) csrfToken(c *gin.Context) {
  136. token, err := session.EnsureCSRFToken(c)
  137. if err != nil {
  138. c.JSON(http.StatusInternalServerError, gin.H{"success": false, "msg": err.Error()})
  139. return
  140. }
  141. c.JSON(http.StatusOK, gin.H{"success": true, "obj": token})
  142. }
  143. // getTwoFactorEnable retrieves the current status of two-factor authentication.
  144. func (a *IndexController) getTwoFactorEnable(c *gin.Context) {
  145. status, err := a.settingService.GetTwoFactorEnable()
  146. if err == nil {
  147. jsonObj(c, status, nil)
  148. }
  149. }