Files
peakskills/services/auth-service.ts
2025-08-25 10:50:39 +02:00

110 lines
3.0 KiB
TypeScript

import { cookies } from "next/headers";
import { UserProfile } from "@/lib/types";
import { userService } from "@/services/user-service";
// Constantes pour les cookies (définies ici car auth-service.ts a été supprimé)
export const COOKIE_NAME = "peakSkills_userId";
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
*/
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);
let userUuid: string;
if (existingUser) {
// Mettre à jour l'utilisateur existant si nécessaire
if (existingUser.teamId !== profile.teamId) {
await userService.updateUserByUuid(existingUser.uuid, profile);
}
userUuid = existingUser.uuid;
} else {
// Créer un nouvel utilisateur
userUuid = await userService.upsertUserUuid(profile);
}
return {
userUuid,
cookieConfig: {
name: COOKIE_NAME,
value: userUuid,
options: {
maxAge: COOKIE_MAX_AGE,
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
},
},
};
}
}