auth.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. package user
  2. import (
  3. "github.com/0xJacky/Nginx-UI/api"
  4. "github.com/0xJacky/Nginx-UI/internal/logger"
  5. "github.com/0xJacky/Nginx-UI/internal/user"
  6. "github.com/0xJacky/Nginx-UI/query"
  7. "github.com/0xJacky/Nginx-UI/settings"
  8. "github.com/gin-gonic/gin"
  9. "github.com/pkg/errors"
  10. "net/http"
  11. "sync"
  12. "time"
  13. )
  14. var mutex = &sync.Mutex{}
  15. type LoginUser struct {
  16. Name string `json:"name" binding:"required,max=255"`
  17. Password string `json:"password" binding:"required,max=255"`
  18. OTP string `json:"otp"`
  19. RecoveryCode string `json:"recovery_code"`
  20. }
  21. const (
  22. ErrPasswordIncorrect = 4031
  23. ErrMaxAttempts = 4291
  24. ErrUserBanned = 4033
  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. }
  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 := api.BindAndValid(c, &json)
  55. if !ok {
  56. return
  57. }
  58. u, err := user.Login(json.Name, json.Password)
  59. if err != nil {
  60. // time.Sleep(5 * time.Second)
  61. switch {
  62. case errors.Is(err, user.ErrPasswordIncorrect):
  63. c.JSON(http.StatusForbidden, LoginResponse{
  64. Message: "Password incorrect",
  65. Code: ErrPasswordIncorrect,
  66. })
  67. case errors.Is(err, user.ErrUserBanned):
  68. c.JSON(http.StatusForbidden, LoginResponse{
  69. Message: "The user is banned",
  70. Code: ErrUserBanned,
  71. })
  72. default:
  73. api.ErrHandler(c, err)
  74. }
  75. user.BanIP(clientIP)
  76. return
  77. }
  78. // Check if the user enables 2FA
  79. if u.EnabledOTP() {
  80. if json.OTP == "" && json.RecoveryCode == "" {
  81. c.JSON(http.StatusOK, LoginResponse{
  82. Message: "The user has enabled 2FA",
  83. Code: Enabled2FA,
  84. })
  85. user.BanIP(clientIP)
  86. return
  87. }
  88. if err = user.VerifyOTP(u, json.OTP, json.RecoveryCode); err != nil {
  89. c.JSON(http.StatusForbidden, LoginResponse{
  90. Message: "Invalid 2FA or recovery code",
  91. Code: Error2FACode,
  92. })
  93. user.BanIP(clientIP)
  94. return
  95. }
  96. }
  97. // login success, clear banned record
  98. _, _ = b.Where(b.IP.Eq(clientIP)).Delete()
  99. logger.Info("[User Login]", u.Name)
  100. token, err := user.GenerateJWT(u)
  101. if err != nil {
  102. c.JSON(http.StatusInternalServerError, LoginResponse{
  103. Message: err.Error(),
  104. })
  105. return
  106. }
  107. c.JSON(http.StatusOK, LoginResponse{
  108. Code: LoginSuccess,
  109. Message: "ok",
  110. Token: token,
  111. })
  112. }
  113. func Logout(c *gin.Context) {
  114. token := c.GetHeader("Authorization")
  115. if token != "" {
  116. user.DeleteToken(token)
  117. }
  118. c.JSON(http.StatusNoContent, nil)
  119. }