feat: add 2FA verification to auth provider
- Introduced `verify2fa` method for handling two-factor authentication. - Updated `login` to support 2FA response handling. - Enhanced `AuthContext` with new `verify2fa` method and types.
This commit is contained in:
@@ -5,14 +5,15 @@ import * as React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { AuthService } from "@/services/auth.service";
|
||||
import { UserService } from "@/services/user.service";
|
||||
import type { RegisterPayload } from "@/types/auth";
|
||||
import type { LoginResponse, RegisterPayload } from "@/types/auth";
|
||||
import type { User } from "@/types/user";
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
isLoading: boolean;
|
||||
isAuthenticated: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
login: (email: string, password: string) => Promise<LoginResponse>;
|
||||
verify2fa: (userId: string, token: string) => Promise<void>;
|
||||
register: (payload: RegisterPayload) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
refreshUser: () => Promise<void>;
|
||||
@@ -59,12 +60,43 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
try {
|
||||
await AuthService.login(email, password);
|
||||
const response = await AuthService.login(email, password);
|
||||
if (response.userId && response.message === "Please provide 2FA token") {
|
||||
return response;
|
||||
}
|
||||
await refreshUser();
|
||||
toast.success("Connexion réussie !");
|
||||
router.push("/");
|
||||
return response;
|
||||
} catch (error: unknown) {
|
||||
let errorMessage = "Erreur de connexion";
|
||||
if (
|
||||
error &&
|
||||
typeof error === "object" &&
|
||||
"response" in error &&
|
||||
error.response &&
|
||||
typeof error.response === "object" &&
|
||||
"data" in error.response &&
|
||||
error.response.data &&
|
||||
typeof error.response.data === "object" &&
|
||||
"message" in error.response.data &&
|
||||
typeof error.response.data.message === "string"
|
||||
) {
|
||||
errorMessage = error.response.data.message;
|
||||
}
|
||||
toast.error(errorMessage);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const verify2fa = async (userId: string, token: string) => {
|
||||
try {
|
||||
await AuthService.verify2fa(userId, token);
|
||||
await refreshUser();
|
||||
toast.success("Connexion réussie !");
|
||||
router.push("/");
|
||||
} catch (error: unknown) {
|
||||
let errorMessage = "Erreur de connexion";
|
||||
let errorMessage = "Code 2FA invalide";
|
||||
if (
|
||||
error &&
|
||||
typeof error === "object" &&
|
||||
@@ -130,6 +162,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
isLoading,
|
||||
isAuthenticated: !!user,
|
||||
login,
|
||||
verify2fa,
|
||||
register,
|
||||
logout,
|
||||
refreshUser,
|
||||
|
||||
Reference in New Issue
Block a user