add auth module
This commit is contained in:
77
backend/internal/auth/handler.go
Normal file
77
backend/internal/auth/handler.go
Normal file
@@ -0,0 +1,77 @@
|
||||
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,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user