auth.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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/gin-gonic/gin"
  7. "github.com/pkg/errors"
  8. "net/http"
  9. "time"
  10. )
  11. type LoginUser struct {
  12. Name string `json:"name" binding:"required,max=255"`
  13. Password string `json:"password" binding:"required,max=255"`
  14. }
  15. const (
  16. ErrPasswordIncorrect = 4031
  17. ErrMaxAttempts = 4291
  18. ErrUserBanned = 4033
  19. )
  20. type LoginResponse struct {
  21. Message string `json:"message"`
  22. Error string `json:"error,omitempty"`
  23. Code int `json:"code"`
  24. Token string `json:"token,omitempty"`
  25. }
  26. func Login(c *gin.Context) {
  27. var json LoginUser
  28. ok := api.BindAndValid(c, &json)
  29. if !ok {
  30. return
  31. }
  32. u, err := user.Login(json.Name, json.Password)
  33. if err != nil {
  34. time.Sleep(5 * time.Second)
  35. switch {
  36. case errors.Is(err, user.ErrPasswordIncorrect):
  37. c.JSON(http.StatusForbidden, LoginResponse{
  38. Message: "Password incorrect",
  39. Code: ErrPasswordIncorrect,
  40. })
  41. case errors.Is(err, user.ErrUserBanned):
  42. c.JSON(http.StatusForbidden, LoginResponse{
  43. Message: "The user is banned",
  44. Code: ErrUserBanned,
  45. })
  46. default:
  47. api.ErrHandler(c, err)
  48. }
  49. return
  50. }
  51. logger.Info("[User Login]", u.Name)
  52. token, err := user.GenerateJWT(u.Name)
  53. if err != nil {
  54. c.JSON(http.StatusInternalServerError, LoginResponse{
  55. Message: err.Error(),
  56. })
  57. return
  58. }
  59. c.JSON(http.StatusOK, LoginResponse{
  60. Message: "ok",
  61. Token: token,
  62. })
  63. }
  64. func Logout(c *gin.Context) {
  65. token := c.GetHeader("Authorization")
  66. if token != "" {
  67. err := user.DeleteToken(token)
  68. if err != nil {
  69. c.JSON(http.StatusInternalServerError, gin.H{
  70. "message": err.Error(),
  71. })
  72. return
  73. }
  74. }
  75. c.JSON(http.StatusNoContent, nil)
  76. }