package auth import ( "net/http" "strconv" "online-back/internal/appresult" "online-back/internal/handlers" "online-back/pkg/logging" "online-back/pkg/utils" "github.com/gin-gonic/gin" "golang.org/x/crypto/bcrypt" ) const ( loginURL = "/login" tokenURL = "/token" profileURL = "/profile" ) type handler struct { logger *logging.Logger repository Repository } func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { return &handler{logger: logger, repository: repository} } func (h *handler) Register(router *gin.RouterGroup) { router.POST(loginURL, h.login) router.POST(tokenURL, h.refreshToken) protected := router.Group("", appresult.JwtTokenCheck()) protected.GET(profileURL, h.getProfile) } // login godoc // @Summary Login // @Description Authenticates a user by email and password // @Tags auth // @Accept json // @Produce json // @Param body body LoginDTO true "Login payload" // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 401 {object} appresult.AppError // @Router /login [post] func (h *handler) login(c *gin.Context) { var dto LoginDTO if err := c.ShouldBindJSON(&dto); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } user, err := h.repository.Login(c.Request.Context(), dto) if err != nil { h.logger.Errorf("login lookup failed: %v", err) c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) return } if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil { c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) return } tokenPair, err := utils.GenerateTokenPair(user.Id) if err != nil { c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable) return } c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair)) } // refreshToken godoc // @Summary Refresh tokens // @Description Issues a new access and refresh token pair // @Tags auth // @Accept json // @Produce json // @Param body body RefreshTokenDTO true "Refresh token payload" // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 401 {object} appresult.AppError // @Router /token [post] func (h *handler) refreshToken(c *gin.Context) { var dto RefreshTokenDTO if err := c.ShouldBindJSON(&dto); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } claims, err := utils.ParseRefreshToken(dto.RefreshToken) if err != nil { c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) return } id, ok := utils.ClaimID(claims) if !ok { c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) return } user, err := h.repository.GetUserByID(c.Request.Context(), id) if err != nil || user.Id != id { c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) return } tokenPair, err := utils.GenerateTokenPair(id) if err != nil { c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable) return } c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair)) } // getProfile godoc // @Summary Get profile // @Description Returns the authenticated user's profile // @Tags auth // @Produce json // @Security BearerAuth // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 401 {object} appresult.AppError // @Failure 404 {object} appresult.AppError // @Router /profile [get] func (h *handler) getProfile(c *gin.Context) { userID, ok := currentUserID(c) if !ok { c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized) return } profile, err := h.repository.GetProfile(c.Request.Context(), userID) if err != nil { h.logger.Errorf("get profile failed: %v", err) c.JSON(http.StatusNotFound, appresult.ErrNotFound) return } c.JSON(http.StatusOK, appresult.SuccessWithData(profile)) } func currentUserID(c *gin.Context) (int, bool) { rawID, exists := c.Get("id") if !exists { return 0, false } switch id := rawID.(type) { case int: return id, id > 0 case string: parsed, err := strconv.Atoi(id) return parsed, err == nil && parsed > 0 default: return 0, false } }