79 lines
2.5 KiB
Go
79 lines
2.5 KiB
Go
package api
|
||
|
||
import (
|
||
"encoding/json"
|
||
"errors"
|
||
"log"
|
||
"net/http"
|
||
|
||
"gitea.mrixs.me/minecraft-platform/backend/internal/core"
|
||
"gitea.mrixs.me/minecraft-platform/backend/internal/database"
|
||
"gitea.mrixs.me/minecraft-platform/backend/internal/models"
|
||
"github.com/golang-jwt/jwt/v5"
|
||
)
|
||
|
||
type UserHandler struct {
|
||
Service *core.UserService
|
||
}
|
||
|
||
func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||
var req models.RegisterRequest
|
||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||
return
|
||
}
|
||
|
||
// --- ДОБАВЛЕНО ЛОГИРОВАНИЕ ---
|
||
log.Printf("[Handler] Received registration request for username: '%s', email: '%s'", req.Username, req.Email)
|
||
|
||
err := h.Service.RegisterNewUser(r.Context(), req)
|
||
if err != nil {
|
||
// --- ДОБАВЛЕНО ЛОГИРОВАНИЕ ОШИБКИ ---
|
||
log.Printf("[Handler] Service returned error: %v", err)
|
||
|
||
switch {
|
||
case errors.Is(err, database.ErrUserExists):
|
||
http.Error(w, err.Error(), http.StatusConflict)
|
||
case errors.Is(err, core.ErrInvalidUsername), errors.Is(err, core.ErrInvalidEmail), errors.Is(err, core.ErrPasswordTooShort):
|
||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||
default:
|
||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||
}
|
||
return
|
||
}
|
||
|
||
// --- ДОБАВЛЕНО ЛОГИРОВАНИЕ УСПЕХА ---
|
||
log.Printf("[Handler] User '%s' registered successfully.", req.Username)
|
||
w.WriteHeader(http.StatusCreated)
|
||
}
|
||
|
||
// GetMe возвращает информацию о текущем аутентифицированном пользователе
|
||
func (h *UserHandler) GetMe(w http.ResponseWriter, r *http.Request) {
|
||
claims, ok := r.Context().Value(ClaimsContextKey).(jwt.MapClaims)
|
||
if !ok {
|
||
http.Error(w, "Could not get claims from context", http.StatusInternalServerError)
|
||
return
|
||
}
|
||
|
||
// В AuthMiddleware мы не проверяли тип user_id, там json.Number или float64
|
||
// Обычно jwt-go возвращает float64
|
||
var userID int
|
||
if idFloat, ok := claims["user_id"].(float64); ok {
|
||
userID = int(idFloat)
|
||
} else {
|
||
log.Printf("[Handler] Invalid user_id type in claims: %T", claims["user_id"])
|
||
http.Error(w, "Invalid token claims", http.StatusUnauthorized)
|
||
return
|
||
}
|
||
|
||
user, err := h.Service.GetUserByID(r.Context(), userID)
|
||
if err != nil {
|
||
log.Printf("[Handler] Failed to get user by ID: %v", err)
|
||
http.Error(w, "User not found", http.StatusNotFound)
|
||
return
|
||
}
|
||
|
||
w.Header().Set("Content-Type", "application/json")
|
||
json.NewEncoder(w).Encode(user)
|
||
}
|