index.go 4.9 KB

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