auth.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. package user
  2. import (
  3. "github.com/0xJacky/Nginx-UI/api"
  4. "github.com/0xJacky/Nginx-UI/internal/user"
  5. "github.com/0xJacky/Nginx-UI/query"
  6. "github.com/0xJacky/Nginx-UI/settings"
  7. "github.com/gin-gonic/gin"
  8. "errors"
  9. "github.com/uozi-tech/cosy"
  10. "github.com/uozi-tech/cosy/logger"
  11. "math/rand/v2"
  12. "net/http"
  13. "sync"
  14. "time"
  15. )
  16. var mutex = &sync.Mutex{}
  17. type LoginUser struct {
  18. Name string `json:"name" binding:"required,max=255"`
  19. Password string `json:"password" binding:"required,max=255"`
  20. OTP string `json:"otp"`
  21. RecoveryCode string `json:"recovery_code"`
  22. }
  23. const (
  24. ErrMaxAttempts = 4291
  25. Enabled2FA = 199
  26. Error2FACode = 4034
  27. LoginSuccess = 200
  28. )
  29. type LoginResponse struct {
  30. Message string `json:"message"`
  31. Error string `json:"error,omitempty"`
  32. Code int `json:"code"`
  33. Token string `json:"token,omitempty"`
  34. SecureSessionID string `json:"secure_session_id,omitempty"`
  35. }
  36. func Login(c *gin.Context) {
  37. // make sure that only one request is processed at a time
  38. mutex.Lock()
  39. defer mutex.Unlock()
  40. // check if the ip is banned
  41. clientIP := c.ClientIP()
  42. b := query.BanIP
  43. banIP, _ := b.Where(b.IP.Eq(clientIP),
  44. b.ExpiredAt.Gte(time.Now().Unix()),
  45. b.Attempts.Gte(settings.AuthSettings.MaxAttempts),
  46. ).Count()
  47. if banIP > 0 {
  48. c.JSON(http.StatusTooManyRequests, LoginResponse{
  49. Message: "Max attempts",
  50. Code: ErrMaxAttempts,
  51. })
  52. return
  53. }
  54. var json LoginUser
  55. ok := cosy.BindAndValid(c, &json)
  56. if !ok {
  57. return
  58. }
  59. u, err := user.Login(json.Name, json.Password)
  60. if err != nil {
  61. random := time.Duration(rand.Int() % 10)
  62. time.Sleep(random * time.Second)
  63. switch {
  64. case errors.Is(err, user.ErrPasswordIncorrect):
  65. c.JSON(http.StatusForbidden, user.ErrPasswordIncorrect)
  66. case errors.Is(err, user.ErrUserBanned):
  67. c.JSON(http.StatusForbidden, user.ErrUserBanned)
  68. default:
  69. api.ErrHandler(c, err)
  70. }
  71. user.BanIP(clientIP)
  72. return
  73. }
  74. // Check if the user enables 2FA
  75. var secureSessionID string
  76. if u.EnabledOTP() {
  77. if json.OTP == "" && json.RecoveryCode == "" {
  78. c.JSON(http.StatusOK, LoginResponse{
  79. Message: "The user has enabled 2FA",
  80. Code: Enabled2FA,
  81. })
  82. user.BanIP(clientIP)
  83. return
  84. }
  85. if err = user.VerifyOTP(u, json.OTP, json.RecoveryCode); err != nil {
  86. c.JSON(http.StatusForbidden, LoginResponse{
  87. Message: "Invalid 2FA or recovery code",
  88. Code: Error2FACode,
  89. })
  90. user.BanIP(clientIP)
  91. return
  92. }
  93. secureSessionID = user.SetSecureSessionID(u.ID)
  94. }
  95. // login success, clear banned record
  96. _, _ = b.Where(b.IP.Eq(clientIP)).Delete()
  97. logger.Info("[User Login]", u.Name)
  98. token, err := user.GenerateJWT(u)
  99. if err != nil {
  100. c.JSON(http.StatusInternalServerError, LoginResponse{
  101. Message: err.Error(),
  102. })
  103. return
  104. }
  105. c.JSON(http.StatusOK, LoginResponse{
  106. Code: LoginSuccess,
  107. Message: "ok",
  108. Token: token,
  109. SecureSessionID: secureSessionID,
  110. })
  111. }
  112. func Logout(c *gin.Context) {
  113. token := c.GetHeader("Authorization")
  114. if token != "" {
  115. user.DeleteToken(token)
  116. }
  117. c.JSON(http.StatusNoContent, nil)
  118. }