auth.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. package handlers
  2. import (
  3. // Added for context.Context
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "git.linuxforward.com/byop/byop-engine/auth"
  8. "git.linuxforward.com/byop/byop-engine/dbstore" // Keep for NewAuthHandler, but userStore is not directly used in handlers
  9. "git.linuxforward.com/byop/byop-engine/models"
  10. "github.com/gin-gonic/gin"
  11. "github.com/go-playground/validator/v10" // Added for validation
  12. )
  13. // AuthHandler handles authentication-related operations
  14. type AuthHandler struct {
  15. authService auth.Service
  16. validate *validator.Validate // Added for validation
  17. }
  18. // NewAuthHandler creates a new AuthHandler
  19. func NewAuthHandler(authService auth.Service, userStore *dbstore.SQLiteStore) *AuthHandler {
  20. return &AuthHandler{
  21. authService: authService,
  22. validate: validator.New(), // Initialize validator
  23. }
  24. }
  25. // LoginRequest defines the structure for login requests.
  26. type LoginRequest struct {
  27. Email string `json:"email" validate:"required,email"`
  28. Password string `json:"password" validate:"required"`
  29. }
  30. // Login handles user authentication
  31. func (h *AuthHandler) Login(c *gin.Context) {
  32. ctx := c.Request.Context() // Propagate context
  33. var req LoginRequest
  34. if err := c.ShouldBindJSON(&req); err != nil {
  35. models.RespondWithError(c, models.NewErrValidation("invalid_request_body", map[string]string{"body": "Invalid request body"}, err))
  36. return
  37. }
  38. fmt.Println("Login request received:", req.Email) // Debugging line to check input
  39. // Validate input
  40. if err := h.validate.Struct(req); err != nil {
  41. validationErrors := models.ExtractValidationErrors(err)
  42. models.RespondWithError(c, models.NewErrValidation("input_validation_failed", validationErrors, err))
  43. return
  44. }
  45. tokenResp, err := h.authService.Login(ctx, req.Email, req.Password)
  46. if err != nil {
  47. if errors.Is(err, auth.ErrInvalidCredentials) || errors.Is(err, auth.ErrUserNotFound) {
  48. models.RespondWithError(c, models.NewErrUnauthorized("login_failed", err))
  49. } else {
  50. models.RespondWithError(c, models.NewErrInternalServer("login_token_generation_failed", err))
  51. }
  52. return
  53. }
  54. c.JSON(http.StatusOK, tokenResp) // auth.TokenResponse is now the direct response
  55. }
  56. // RefreshTokenRequest defines the structure for refresh token requests.
  57. type RefreshTokenRequest struct {
  58. RefreshToken string `json:"refresh_token" validate:"required"`
  59. }
  60. // RefreshToken handles token refresh
  61. func (h *AuthHandler) RefreshToken(c *gin.Context) {
  62. ctx := c.Request.Context() // Propagate context
  63. var req RefreshTokenRequest
  64. if err := c.ShouldBindJSON(&req); err != nil {
  65. models.RespondWithError(c, models.NewErrValidation("invalid_request_body_refresh", map[string]string{"body": "Invalid request body"}, err))
  66. return
  67. }
  68. if err := h.validate.Struct(req); err != nil {
  69. validationErrors := models.ExtractValidationErrors(err)
  70. models.RespondWithError(c, models.NewErrValidation("input_validation_failed_refresh", validationErrors, err))
  71. return
  72. }
  73. resp, err := h.authService.RefreshToken(ctx, req.RefreshToken)
  74. if err != nil {
  75. if errors.Is(err, auth.ErrInvalidToken) || errors.Is(err, auth.ErrRefreshTokenNotFound) || errors.Is(err, auth.ErrTokenExpired) {
  76. models.RespondWithError(c, models.NewErrUnauthorized("invalid_refresh_token", err))
  77. } else {
  78. models.RespondWithError(c, models.NewErrInternalServer("refresh_token_failed", err))
  79. }
  80. return
  81. }
  82. c.JSON(http.StatusOK, resp)
  83. }
  84. // LogoutRequest defines the structure for logout requests.
  85. type LogoutRequest struct {
  86. Token string `json:"token" validate:"required"` // Assuming the client sends the token to be invalidated
  87. }
  88. // Logout handles user logout
  89. func (h *AuthHandler) Logout(c *gin.Context) {
  90. ctx := c.Request.Context() // Propagate context
  91. var req LogoutRequest
  92. if err := c.ShouldBindJSON(&req); err != nil {
  93. models.RespondWithError(c, models.NewErrValidation("invalid_request_body_logout", map[string]string{"body": "Invalid request body"}, err))
  94. return
  95. }
  96. if err := h.validate.Struct(req); err != nil {
  97. validationErrors := models.ExtractValidationErrors(err)
  98. models.RespondWithError(c, models.NewErrValidation("input_validation_failed_logout", validationErrors, err))
  99. return
  100. }
  101. err := h.authService.Logout(ctx, req.Token)
  102. if err != nil {
  103. if errors.Is(err, auth.ErrInvalidToken) {
  104. models.RespondWithError(c, models.NewErrBadRequest("logout_failed_invalid_token", err))
  105. } else {
  106. models.RespondWithError(c, models.NewErrInternalServer("logout_failed", err))
  107. }
  108. return
  109. }
  110. c.Status(http.StatusNoContent)
  111. }