72 lines
1.5 KiB
TypeScript
72 lines
1.5 KiB
TypeScript
"use client";
|
|
|
|
import { UserProfile } from "./types";
|
|
|
|
/**
|
|
* Service d'authentification côté client
|
|
*/
|
|
export class AuthService {
|
|
/**
|
|
* Authentifie un utilisateur et créé le cookie
|
|
*/
|
|
static async login(
|
|
profile: UserProfile
|
|
): Promise<{ user: UserProfile & { uuid: string }; userUuid: string }> {
|
|
const response = await fetch("/api/auth", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify(profile),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error("Failed to authenticate user");
|
|
}
|
|
|
|
return response.json();
|
|
}
|
|
|
|
/**
|
|
* Récupère l'utilisateur actuel depuis le cookie
|
|
*/
|
|
static async getCurrentUser(): Promise<UserProfile | null> {
|
|
try {
|
|
const response = await fetch("/api/auth", {
|
|
method: "GET",
|
|
credentials: "same-origin",
|
|
});
|
|
|
|
if (!response.ok) {
|
|
return null;
|
|
}
|
|
|
|
const data = await response.json();
|
|
return data.user;
|
|
} catch (error) {
|
|
console.error("Failed to get current user:", error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Déconnecte l'utilisateur (supprime le cookie)
|
|
*/
|
|
static async logout(): Promise<void> {
|
|
const response = await fetch("/api/auth", {
|
|
method: "DELETE",
|
|
credentials: "same-origin",
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error("Failed to logout");
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Constantes pour les cookies
|
|
*/
|
|
export const COOKIE_NAME = "peakSkills_userId";
|
|
export const COOKIE_MAX_AGE = 30 * 24 * 60 * 60; // 30 jours
|