Files
delivery-tracker/backend/internal/auth/handler.go
Egor Pozharov be0b13acbf add auth module
2026-04-15 19:17:10 +06:00

78 lines
1.9 KiB
Go

package auth
import (
"net/http"
"github.com/gin-gonic/gin"
)
type Handler struct {
authService *Service
}
func NewHandler(authService *Service) *Handler {
return &Handler{
authService: authService,
}
}
type LoginRequest struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
type RegisterRequest struct {
Username string `json:"username" binding:"required,min=3,max=50"`
Password string `json:"password" binding:"required,min=6"`
}
func (h *Handler) Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request", "details": err.Error()})
return
}
token, err := h.authService.Login(c.Request.Context(), req.Username, req.Password)
if err != nil {
switch err {
case ErrUserNotFound, ErrInvalidCredentials:
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": "login failed"})
}
return
}
c.JSON(http.StatusOK, gin.H{"token": token})
}
func (h *Handler) Register(c *gin.Context) {
var req RegisterRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request", "details": err.Error()})
return
}
user, token, err := h.authService.Register(c.Request.Context(), req.Username, req.Password)
if err != nil {
switch err {
case ErrUserExists:
c.JSON(http.StatusConflict, gin.H{"error": "user already exists"})
case ErrPasswordTooShort:
c.JSON(http.StatusBadRequest, gin.H{"error": "password too short"})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": "registration failed"})
}
return
}
c.JSON(http.StatusCreated, gin.H{
"user": gin.H{
"id": user.ID,
"username": user.Username,
},
"token": token,
})
}