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