Files

80 lines
1.8 KiB
Go
Raw Permalink Normal View History

package handlers
import (
"encoding/json"
"messenger/internal/api/middleware"
"messenger/internal/api/responses"
"messenger/internal/service"
"net/http"
)
type AuthHandler struct {
authService *service.AuthService
}
func NewAuthHandler(authService *service.AuthService) *AuthHandler {
return &AuthHandler{authService: authService}
}
type RegisterRequest struct {
Login string `json:"login"`
Password string `json:"password"`
}
type LoginRequest struct {
Login string `json:"login"`
Password string `json:"password"`
}
type AuthResponse struct {
Token string `json:"token"`
User interface{} `json:"user"`
}
func (h *AuthHandler) Register(w http.ResponseWriter, r *http.Request) {
var req RegisterRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
responses.BadRequest(w, "invalid request body")
return
}
user, token, err := h.authService.Register(r.Context(), req.Login, req.Password)
if err != nil {
responses.BadRequest(w, err.Error())
return
}
responses.Success(w, http.StatusCreated, AuthResponse{
Token: token,
User: user.ToSafe(),
})
}
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
var req LoginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
responses.BadRequest(w, "invalid request body")
return
}
user, token, err := h.authService.Login(r.Context(), req.Login, req.Password)
if err != nil {
responses.Unauthorized(w, err.Error())
return
}
responses.Success(w, http.StatusOK, AuthResponse{
Token: token,
User: user.ToSafe(),
})
}
func (h *AuthHandler) GetMe(w http.ResponseWriter, r *http.Request) {
user := middleware.GetUserFromContext(r.Context())
if user == nil {
responses.Unauthorized(w, "user not found")
return
}
responses.Success(w, http.StatusOK, user.ToSafe())
}