index.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package controller
  2. import (
  3. "net/http"
  4. "text/template"
  5. "time"
  6. "github.com/mhsanaei/3x-ui/v3/logger"
  7. "github.com/mhsanaei/3x-ui/v3/web/middleware"
  8. "github.com/mhsanaei/3x-ui/v3/web/service"
  9. "github.com/mhsanaei/3x-ui/v3/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("/csrf-token", a.csrfToken)
  35. g.POST("/login", middleware.CSRFMiddleware(), a.login)
  36. g.POST("/logout", middleware.CSRFMiddleware(), a.logout)
  37. g.POST("/getTwoFactorEnable", middleware.CSRFMiddleware(), a.getTwoFactorEnable)
  38. }
  39. // index handles the root route, redirecting logged-in users to the panel or showing the login page.
  40. func (a *IndexController) index(c *gin.Context) {
  41. if session.IsLogin(c) {
  42. c.Header("Cache-Control", "no-store")
  43. c.Redirect(http.StatusTemporaryRedirect, c.GetString("base_path")+"panel/")
  44. return
  45. }
  46. serveDistPage(c, "login.html")
  47. }
  48. // login handles user authentication and session creation.
  49. func (a *IndexController) login(c *gin.Context) {
  50. var form LoginForm
  51. if err := c.ShouldBind(&form); err != nil {
  52. pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.invalidFormData"))
  53. return
  54. }
  55. if form.Username == "" {
  56. pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.emptyUsername"))
  57. return
  58. }
  59. if form.Password == "" {
  60. pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.emptyPassword"))
  61. return
  62. }
  63. remoteIP := getRemoteIp(c)
  64. safeUser := template.HTMLEscapeString(form.Username)
  65. timeStr := time.Now().Format("2006-01-02 15:04:05")
  66. if blockedUntil, ok := defaultLoginLimiter.allow(remoteIP, form.Username); !ok {
  67. reason := "too many failed attempts"
  68. logger.Warningf("failed login: username=%q, IP=%q, reason=%q, blocked_until=%s", safeUser, remoteIP, reason, blockedUntil.Format(time.RFC3339))
  69. a.tgbot.UserLoginNotify(service.LoginAttempt{
  70. Username: safeUser,
  71. IP: remoteIP,
  72. Time: timeStr,
  73. Status: service.LoginFail,
  74. Reason: reason,
  75. })
  76. pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.wrongUsernameOrPassword"))
  77. return
  78. }
  79. user, checkErr := a.userService.CheckUser(form.Username, form.Password, form.TwoFactorCode)
  80. if user == nil {
  81. reason := loginFailureReason(checkErr)
  82. if blockedUntil, blocked := defaultLoginLimiter.registerFailure(remoteIP, form.Username); blocked {
  83. logger.Warningf("failed login: username=%q, IP=%q, reason=%q, blocked_until=%s", safeUser, remoteIP, reason, blockedUntil.Format(time.RFC3339))
  84. } else {
  85. logger.Warningf("failed login: username=%q, IP=%q, reason=%q", safeUser, remoteIP, reason)
  86. }
  87. a.tgbot.UserLoginNotify(service.LoginAttempt{
  88. Username: safeUser,
  89. IP: remoteIP,
  90. Time: timeStr,
  91. Status: service.LoginFail,
  92. Reason: reason,
  93. })
  94. pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.wrongUsernameOrPassword"))
  95. return
  96. }
  97. defaultLoginLimiter.registerSuccess(remoteIP, form.Username)
  98. logger.Infof("%s logged in successfully, Ip Address: %s\n", safeUser, remoteIP)
  99. a.tgbot.UserLoginNotify(service.LoginAttempt{
  100. Username: safeUser,
  101. IP: remoteIP,
  102. Time: timeStr,
  103. Status: service.LoginSuccess,
  104. })
  105. if err := session.SetLoginUser(c, user); err != nil {
  106. logger.Warning("Unable to save session:", err)
  107. return
  108. }
  109. logger.Infof("%s logged in successfully", safeUser)
  110. jsonMsg(c, I18nWeb(c, "pages.login.toasts.successLogin"), nil)
  111. }
  112. func loginFailureReason(err error) string {
  113. if err != nil && err.Error() == "invalid 2fa code" {
  114. return "invalid 2FA code"
  115. }
  116. return "invalid credentials"
  117. }
  118. func (a *IndexController) logout(c *gin.Context) {
  119. user := session.GetLoginUser(c)
  120. if user != nil {
  121. logger.Infof("%s logged out successfully", user.Username)
  122. }
  123. if err := session.ClearSession(c); err != nil {
  124. logger.Warning("Unable to clear session on logout:", err)
  125. }
  126. c.Header("Cache-Control", "no-store")
  127. c.JSON(http.StatusOK, gin.H{"success": true})
  128. }
  129. // csrfToken returns the session CSRF token. Public — the login page
  130. // needs a token before authenticating.
  131. func (a *IndexController) csrfToken(c *gin.Context) {
  132. token, err := session.EnsureCSRFToken(c)
  133. if err != nil {
  134. c.JSON(http.StatusInternalServerError, gin.H{"success": false, "msg": err.Error()})
  135. return
  136. }
  137. c.JSON(http.StatusOK, gin.H{"success": true, "obj": token})
  138. }
  139. // getTwoFactorEnable retrieves the current status of two-factor authentication.
  140. func (a *IndexController) getTwoFactorEnable(c *gin.Context) {
  141. status, err := a.settingService.GetTwoFactorEnable()
  142. if err == nil {
  143. jsonObj(c, status, nil)
  144. }
  145. }