Files
peakskills/services/auth-service.ts
Julien Froidefond 5c71ce1a54 refactor: update authentication flow and cookie management
- Changed COOKIE_NAME from "peakSkills_userId" to "session_token" for better clarity.
- Updated AuthClient to handle login and registration with new data structures.
- Enhanced AuthWrapper to manage user sessions and display appropriate messages.
- Added error handling in LoginForm and RegisterForm for better user feedback.
- Refactored user service methods to streamline user creation and verification processes.
2025-08-25 16:19:31 +02:00

127 lines
3.5 KiB
TypeScript

import { cookies } from "next/headers";
import { UserProfile } from "@/lib/types";
import { userService } from "@/services/user-service";
// Constantes pour les cookies
export const COOKIE_NAME = "session_token";
export const COOKIE_MAX_AGE = 30 * 24 * 60 * 60; // 30 jours
/**
* Service d'authentification côté serveur
* Implémente les méthodes qui nécessitent next/headers
*/
export class AuthService {
/**
* Récupère l'UUID utilisateur depuis le cookie côté serveur
*/
static async getUserUuidFromCookie(): Promise<string | null> {
const cookieStore = await cookies();
const userUuidCookie = cookieStore.get(COOKIE_NAME);
if (!userUuidCookie?.value) {
return null;
}
return userUuidCookie.value;
}
/**
* Vérifie si l'utilisateur est authentifié côté serveur
*/
static async isUserAuthenticated(): Promise<boolean> {
const userUuid = await this.getUserUuidFromCookie();
return !!userUuid;
}
/**
* Vérifie l'authentification et retourne le profil utilisateur
* @throws {Error} avec status 401 si non authentifié ou 404 si utilisateur non trouvé
*/
static async requireAuthenticatedUser(): Promise<{
userUuid: string;
userProfile: UserProfile;
}> {
const userUuid = await this.getUserUuidFromCookie();
if (!userUuid) {
const error = new Error("Utilisateur non authentifié");
(error as any).status = 401;
throw error;
}
const userProfile = await userService.getUserByUuid(userUuid);
if (!userProfile) {
const error = new Error("Utilisateur introuvable");
(error as any).status = 404;
throw error;
}
return { userUuid, userProfile };
}
/**
* Authentifie un utilisateur et retourne la configuration du cookie
* Note: Cette méthode est maintenant obsolète avec le nouveau système d'auth
* Utilisez login/register à la place
*/
static async authenticateUser(profile: UserProfile): Promise<{
userUuid: string;
cookieConfig: {
name: string;
value: string;
options: {
maxAge: number;
httpOnly: boolean;
secure: boolean;
sameSite: "lax" | "strict" | "none";
path: string;
};
};
}> {
// Vérifier si l'utilisateur existe déjà avec ces informations
const existingUser = await userService.findUserByProfile(profile);
if (!existingUser) {
throw new Error(
"Utilisateur non trouvé. Veuillez vous connecter avec votre email et mot de passe."
);
}
return {
userUuid: existingUser.uuid,
cookieConfig: {
name: COOKIE_NAME,
value: existingUser.uuid,
options: {
maxAge: COOKIE_MAX_AGE,
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
},
},
};
}
/**
* Crée une nouvelle session pour un utilisateur
*/
static async createSession(userUuid: string): Promise<string> {
// Pour l'instant, on utilise l'UUID comme token de session
// Plus tard, on pourra implémenter un système de JWT ou de sessions en base
return userUuid;
}
/**
* Valide un token de session et retourne l'UUID utilisateur
*/
static async validateSession(sessionToken: string): Promise<string | null> {
// Pour l'instant, on considère que le token est valide s'il correspond à un UUID
// Plus tard, on pourra ajouter une validation plus robuste
if (sessionToken && sessionToken.length > 0) {
return sessionToken;
}
return null;
}
}