From e98d10ae1d8d960567abcf36cd7369f352af1130 Mon Sep 17 00:00:00 2001 From: Vladimir Zagainov Date: Sun, 4 Jan 2026 14:31:34 +0300 Subject: [PATCH] feat: add /api/user/me endpoint for session restoration --- cmd/server/main.go | 1 + internal/api/user_handler.go | 31 ++++++++++++++++++++++++++++ internal/core/user_service.go | 5 +++++ internal/database/user_repository.go | 21 +++++++++++++++++++ 4 files changed, 58 insertions(+) diff --git a/cmd/server/main.go b/cmd/server/main.go index 230860c..638d1ff 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -91,6 +91,7 @@ func main() { r.Route("/api/user", func(r chi.Router) { r.Post("/skin", profileHandler.UploadSkin) + r.Get("/me", userHandler.GetMe) }) r.Route("/api/admin", func(r chi.Router) { diff --git a/internal/api/user_handler.go b/internal/api/user_handler.go index 99e3631..8ecb9aa 100644 --- a/internal/api/user_handler.go +++ b/internal/api/user_handler.go @@ -9,6 +9,7 @@ import ( "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 { @@ -45,3 +46,33 @@ func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) { 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) +} diff --git a/internal/core/user_service.go b/internal/core/user_service.go index 03b1405..ca3e397 100644 --- a/internal/core/user_service.go +++ b/internal/core/user_service.go @@ -60,6 +60,11 @@ func (s *UserService) RegisterNewUser(ctx context.Context, req models.RegisterRe return s.Repo.CreateUserTx(ctx, user) } +// GetUserByID возвращает пользователя по его ID +func (s *UserService) GetUserByID(ctx context.Context, userID int) (*models.User, error) { + return s.Repo.GetUserByID(ctx, userID) +} + // ValidateJoinRequest проверяет запрос на присоединение к серверу. func (s *AuthService) ValidateJoinRequest(ctx context.Context, req models.JoinRequest) error { var uuidStr string diff --git a/internal/database/user_repository.go b/internal/database/user_repository.go index f2bf4b9..9e61084 100644 --- a/internal/database/user_repository.go +++ b/internal/database/user_repository.go @@ -227,3 +227,24 @@ func (r *UserRepository) UpdateUserRole(ctx context.Context, userID int, newRole } return nil } + +// GetUserByID находит пользователя по его ID. +func (r *UserRepository) GetUserByID(ctx context.Context, userID int) (*models.User, error) { + user := &models.User{} + var userUUID string + + query := "SELECT id, uuid, username, email, password_hash, role, created_at, updated_at FROM users WHERE id = $1" + err := r.DB.QueryRow(ctx, query, userID).Scan( + &user.ID, &userUUID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, + ) + + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrUserNotFound + } + return nil, err + } + + user.UUID, _ = uuid.Parse(userUUID) + return user, nil +}