1
0

auth.go 3.0 KB

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