Initial commit: Эфир мессенджер
This commit is contained in:
80
internal/api/handlers/auth.go
Normal file
80
internal/api/handlers/auth.go
Normal file
@@ -0,0 +1,80 @@
|
||||
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())
|
||||
}
|
||||
Reference in New Issue
Block a user