Files
online-backend/internal/identity/auth/handler.go

262 lines
7.4 KiB
Go
Executable File

package auth
import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/pkg/logging"
"online-back/pkg/sms"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const (
loginURL = "/login"
tokenURL = "/token"
profileURL = "/profile"
registerURL = "/register"
verifyURL = "/register/verify"
)
type handler struct {
logger *logging.Logger
repository Repository
service *Service
}
func NewHandler(logger *logging.Logger, repository Repository, sender sms.Sender) handlers.Handler {
return &handler{logger: logger, repository: repository, service: NewService(repository, sender)}
}
func (h *handler) Register(router *gin.RouterGroup) {
router.POST(loginURL, h.login)
router.POST(tokenURL, h.refreshToken)
router.POST(registerURL, h.register)
router.POST(verifyURL, h.verify)
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))
}
// register godoc
// @Summary Register
// @Description Starts registration and sends an SMS verification code. Replace sms.LogSender with your SMS client.
// @Tags auth
// @Accept json
// @Produce json
// @Param body body RegisterDTO true "Registration payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 409 {object} appresult.AppError
// @Router /register [post]
func (h *handler) register(c *gin.Context) {
var dto RegisterDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.service.Register(c.Request.Context(), dto)
if err != nil {
h.respondRegisterError(c, err)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// verify godoc
// @Summary Verify phone
// @Description Confirms the SMS code and creates the user account
// @Tags auth
// @Accept json
// @Produce json
// @Param body body VerifyDTO true "Verification payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 409 {object} appresult.AppError
// @Router /register/verify [post]
func (h *handler) verify(c *gin.Context) {
var dto VerifyDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
tokenPair, err := h.service.Verify(c.Request.Context(), dto)
if err != nil {
h.respondRegisterError(c, err)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
}
func (h *handler) respondRegisterError(c *gin.Context, err error) {
switch {
case errors.Is(err, ErrPasswordMismatch):
c.JSON(http.StatusBadRequest, appresult.ErrPasswordMismatch)
case errors.Is(err, ErrInvalidPhone), errors.Is(err, ErrInvalidInput):
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
case errors.Is(err, ErrConflict):
c.JSON(http.StatusConflict, appresult.ErrConflict)
case errors.Is(err, ErrInvalidCode):
c.JSON(http.StatusBadRequest, appresult.ErrInvalidCode)
default:
h.logger.Errorf("register/verify failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
}
}
// 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
}
}