feat: add /api/user/me endpoint for session restoration
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user