feat: enhance evaluation loading with cookie authentication
- Updated the GET method in the evaluations route to support user authentication via cookies, improving security and user experience. - Added compatibility for legacy parameter-based authentication to ensure backward compatibility. - Refactored the useEvaluation hook to load user profiles from cookies instead of localStorage, streamlining the authentication process. - Introduced a new method in EvaluationService to retrieve user profiles by ID, enhancing data retrieval efficiency. - Updated ApiClient to handle cookie-based requests for loading evaluations, ensuring proper session management.
This commit is contained in:
98
app/api/auth/route.ts
Normal file
98
app/api/auth/route.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { EvaluationService } from "@/services/evaluation-service";
|
||||
import { UserProfile } from "@/lib/types";
|
||||
|
||||
const COOKIE_NAME = "peakSkills_userId";
|
||||
const COOKIE_MAX_AGE = 30 * 24 * 60 * 60; // 30 jours
|
||||
|
||||
/**
|
||||
* GET /api/auth - Récupère l'utilisateur actuel depuis le cookie
|
||||
*/
|
||||
export async function GET() {
|
||||
try {
|
||||
const cookieStore = await cookies();
|
||||
const userId = cookieStore.get(COOKIE_NAME)?.value;
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ user: null }, { status: 200 });
|
||||
}
|
||||
|
||||
const evaluationService = new EvaluationService();
|
||||
const userProfile = await evaluationService.getUserById(parseInt(userId));
|
||||
|
||||
if (!userProfile) {
|
||||
// Cookie invalide, le supprimer
|
||||
const response = NextResponse.json({ user: null }, { status: 200 });
|
||||
response.cookies.set(COOKIE_NAME, "", { maxAge: 0 });
|
||||
return response;
|
||||
}
|
||||
|
||||
return NextResponse.json({ user: userProfile }, { status: 200 });
|
||||
} catch (error) {
|
||||
console.error("Error getting current user:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to get current user" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/auth - Authentifie un utilisateur et créé/met à jour le cookie
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const profile: UserProfile = await request.json();
|
||||
|
||||
if (!profile.firstName || !profile.lastName || !profile.teamId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Missing required fields" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const evaluationService = new EvaluationService();
|
||||
const userId = await evaluationService.upsertUser(profile);
|
||||
|
||||
// Créer la réponse avec le cookie
|
||||
const response = NextResponse.json({
|
||||
user: { ...profile, id: userId },
|
||||
userId
|
||||
}, { status: 200 });
|
||||
|
||||
// Définir le cookie avec l'ID utilisateur
|
||||
response.cookies.set(COOKIE_NAME, userId.toString(), {
|
||||
maxAge: COOKIE_MAX_AGE,
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
});
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error("Error authenticating user:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to authenticate user" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/auth - Déconnecte l'utilisateur (supprime le cookie)
|
||||
*/
|
||||
export async function DELETE() {
|
||||
try {
|
||||
const response = NextResponse.json({ success: true }, { status: 200 });
|
||||
response.cookies.set(COOKIE_NAME, "", { maxAge: 0 });
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error("Error logging out user:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to logout" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,44 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import { evaluationService } from "@/services/evaluation-service";
|
||||
import { UserEvaluation, UserProfile } from "@/lib/types";
|
||||
import { COOKIE_NAME } from "@/lib/auth-utils";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const firstName = searchParams.get("firstName");
|
||||
const lastName = searchParams.get("lastName");
|
||||
const teamId = searchParams.get("teamId");
|
||||
const cookieStore = await cookies();
|
||||
const userId = cookieStore.get(COOKIE_NAME)?.value;
|
||||
const userIdNum = userId ? parseInt(userId) : null;
|
||||
|
||||
if (!firstName || !lastName || !teamId) {
|
||||
// Support pour l'ancien mode avec paramètres (pour la compatibilité)
|
||||
if (!userIdNum) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const firstName = searchParams.get("firstName");
|
||||
const lastName = searchParams.get("lastName");
|
||||
const teamId = searchParams.get("teamId");
|
||||
|
||||
if (!firstName || !lastName || !teamId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Utilisateur non authentifié" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const profile: UserProfile = { firstName, lastName, teamId };
|
||||
const evaluation = await evaluationService.loadUserEvaluation(profile);
|
||||
return NextResponse.json({ evaluation });
|
||||
}
|
||||
|
||||
// Mode authentifié par cookie
|
||||
const userProfile = await evaluationService.getUserById(userIdNum);
|
||||
if (!userProfile) {
|
||||
return NextResponse.json(
|
||||
{ error: "firstName, lastName et teamId sont requis" },
|
||||
{ status: 400 }
|
||||
{ error: "Utilisateur non trouvé" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
const profile: UserProfile = { firstName, lastName, teamId };
|
||||
const evaluation = await evaluationService.loadUserEvaluation(profile);
|
||||
|
||||
const evaluation = await evaluationService.loadUserEvaluation(userProfile);
|
||||
return NextResponse.json({ evaluation });
|
||||
} catch (error) {
|
||||
console.error("Erreur lors du chargement de l'évaluation:", error);
|
||||
|
||||
Reference in New Issue
Block a user