103 lines
2.6 KiB
Go
103 lines
2.6 KiB
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/dhao2001/mygo/internal/api"
|
|
"github.com/dhao2001/mygo/internal/service"
|
|
)
|
|
|
|
// AuthHandler handles authentication endpoints.
|
|
type AuthHandler struct {
|
|
authService *service.AuthService
|
|
}
|
|
|
|
// NewAuthHandler creates an AuthHandler.
|
|
func NewAuthHandler(authService *service.AuthService) *AuthHandler {
|
|
return &AuthHandler{authService: authService}
|
|
}
|
|
|
|
type registerRequest struct {
|
|
Username string `json:"username" binding:"required"`
|
|
Email string `json:"email" binding:"required,email"`
|
|
Password string `json:"password" binding:"required,min=6"`
|
|
}
|
|
|
|
type loginRequest struct {
|
|
Email string `json:"email" binding:"required,email"`
|
|
Password string `json:"password" binding:"required"`
|
|
}
|
|
|
|
type tokenRequest struct {
|
|
RefreshToken string `json:"refresh_token" binding:"required"`
|
|
}
|
|
|
|
// Register handles POST /api/v1/auth/register.
|
|
func (h *AuthHandler) Register(c *gin.Context) {
|
|
var req registerRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
api.Error(c, http.StatusBadRequest, "invalid request: "+err.Error())
|
|
return
|
|
}
|
|
|
|
user, err := h.authService.Register(c.Request.Context(), req.Username, req.Email, req.Password)
|
|
if err != nil {
|
|
api.Error(c, http.StatusConflict, err.Error())
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusCreated, user)
|
|
}
|
|
|
|
// Login handles POST /api/v1/auth/login.
|
|
func (h *AuthHandler) Login(c *gin.Context) {
|
|
var req loginRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
api.Error(c, http.StatusBadRequest, "invalid request: "+err.Error())
|
|
return
|
|
}
|
|
|
|
pair, err := h.authService.Login(c.Request.Context(), req.Email, req.Password)
|
|
if err != nil {
|
|
api.Error(c, http.StatusUnauthorized, err.Error())
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, pair)
|
|
}
|
|
|
|
// Refresh handles POST /api/v1/auth/refresh.
|
|
func (h *AuthHandler) Refresh(c *gin.Context) {
|
|
var req tokenRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
api.Error(c, http.StatusBadRequest, "invalid request: "+err.Error())
|
|
return
|
|
}
|
|
|
|
pair, err := h.authService.Refresh(c.Request.Context(), req.RefreshToken)
|
|
if err != nil {
|
|
api.Error(c, http.StatusUnauthorized, err.Error())
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, pair)
|
|
}
|
|
|
|
// Logout handles POST /api/v1/auth/logout.
|
|
func (h *AuthHandler) Logout(c *gin.Context) {
|
|
var req tokenRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
api.Error(c, http.StatusBadRequest, "invalid request: "+err.Error())
|
|
return
|
|
}
|
|
|
|
if err := h.authService.Logout(c.Request.Context(), req.RefreshToken); err != nil {
|
|
api.Error(c, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
c.Status(http.StatusOK)
|
|
}
|