187 lines
5.0 KiB
Go
Executable File
187 lines
5.0 KiB
Go
Executable File
package auth
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"online-back/internal/appresult"
|
|
"online-back/internal/handlers"
|
|
"online-back/pkg/logging"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/jackc/pgx/v4"
|
|
)
|
|
|
|
const (
|
|
loginURL = "/login"
|
|
tokenURL = "/token"
|
|
profileURL = "/profile"
|
|
)
|
|
|
|
type handler struct {
|
|
logger *logging.Logger
|
|
repository Repository
|
|
service *Service
|
|
}
|
|
|
|
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
|
return &handler{logger: logger, repository: repository, service: NewService(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)
|
|
protected.PUT(profileURL, h.updateProfile)
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
tokenPair, err := h.service.Login(c.Request.Context(), dto)
|
|
if errors.Is(err, ErrInvalidCredentials) {
|
|
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
|
return
|
|
}
|
|
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
|
|
}
|
|
|
|
tokenPair, err := h.service.RefreshToken(c.Request.Context(), dto.RefreshToken)
|
|
if errors.Is(err, ErrInvalidCredentials) {
|
|
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
|
return
|
|
}
|
|
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))
|
|
}
|
|
|
|
// updateProfile godoc
|
|
// @Summary Update profile
|
|
// @Description Updates the authenticated user's profile
|
|
// @Tags auth
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Security BearerAuth
|
|
// @Param body body UpdateProfileDTO true "Profile payload"
|
|
// @Success 200 {object} appresult.AppSuccess
|
|
// @Failure 400 {object} appresult.AppError
|
|
// @Failure 401 {object} appresult.AppError
|
|
// @Failure 404 {object} appresult.AppError
|
|
// @Router /profile [put]
|
|
func (h *handler) updateProfile(c *gin.Context) {
|
|
userID, ok := currentUserID(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
|
return
|
|
}
|
|
|
|
var dto UpdateProfileDTO
|
|
if err := c.ShouldBindJSON(&dto); err != nil {
|
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
|
return
|
|
}
|
|
|
|
profile, err := h.repository.UpdateProfile(c.Request.Context(), userID, dto)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
|
return
|
|
}
|
|
if err != nil {
|
|
h.logger.Errorf("update profile failed: %v", err)
|
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
|
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
|
|
}
|
|
}
|