78 lines
1.9 KiB
TypeScript
78 lines
1.9 KiB
TypeScript
import { signIn, signOut } from "next-auth/react";
|
|
import { BaseHttpClient } from "../base/http-client";
|
|
|
|
export interface LoginCredentials {
|
|
email: string;
|
|
password: string;
|
|
}
|
|
|
|
export interface RegisterData {
|
|
firstName: string;
|
|
lastName: string;
|
|
email: string;
|
|
password: string;
|
|
teamId: string;
|
|
}
|
|
|
|
export interface AuthUser {
|
|
id: string;
|
|
firstName: string;
|
|
lastName: string;
|
|
email: string;
|
|
teamId: string;
|
|
}
|
|
|
|
export class AuthClient extends BaseHttpClient {
|
|
/**
|
|
* Connecte un utilisateur avec email/password via NextAuth
|
|
*/
|
|
async login(credentials: LoginCredentials): Promise<{ success: boolean; error?: string }> {
|
|
const result = await signIn("credentials", {
|
|
email: credentials.email,
|
|
password: credentials.password,
|
|
redirect: false,
|
|
});
|
|
|
|
if (result?.error) {
|
|
return { success: false, error: "Email ou mot de passe incorrect" };
|
|
}
|
|
|
|
return { success: true };
|
|
}
|
|
|
|
/**
|
|
* Crée un nouveau compte utilisateur puis se connecte automatiquement
|
|
*/
|
|
async register(data: RegisterData): Promise<{ success: boolean; error?: string }> {
|
|
try {
|
|
// Créer l'utilisateur via l'API
|
|
const response = await this.post<{ user: AuthUser; message: string }>("/auth/register", data);
|
|
|
|
// Se connecter automatiquement après création
|
|
const loginResult = await signIn("credentials", {
|
|
email: data.email,
|
|
password: data.password,
|
|
redirect: false,
|
|
});
|
|
|
|
if (loginResult?.error) {
|
|
return { success: false, error: "Compte créé mais erreur de connexion" };
|
|
}
|
|
|
|
return { success: true };
|
|
} catch (error: any) {
|
|
return {
|
|
success: false,
|
|
error: error.message || "Erreur lors de la création du compte"
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Déconnecte l'utilisateur via NextAuth
|
|
*/
|
|
async logout(): Promise<void> {
|
|
await signOut({ redirect: false });
|
|
}
|
|
}
|