mirror of
http://88.130.71.182:3000/BlitTech/badoHair_fe.git
synced 2026-06-13 08:58:31 +00:00
Update May 12 by Elvis
This commit is contained in:
73
contexts/AuthContext.tsx
Normal file
73
contexts/AuthContext.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect, ReactNode } from "react";
|
||||
import { getToken } from "@/lib/api";
|
||||
import * as authApi from "@/lib/api/auth";
|
||||
|
||||
export type UserProfile = authApi.UserProfile;
|
||||
|
||||
interface AuthContextType {
|
||||
user: UserProfile | null;
|
||||
isLoading: boolean;
|
||||
isAdmin: boolean;
|
||||
login: (email: string, password: string) => Promise<UserProfile>;
|
||||
register: (email: string, password: string, name: string) => Promise<UserProfile>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [user, setUser] = useState<UserProfile | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
authApi.getMe()
|
||||
.then(setUser)
|
||||
.catch(() => authApi.logout())
|
||||
.finally(() => setIsLoading(false));
|
||||
}, []);
|
||||
|
||||
const login = async (email: string, password: string): Promise<UserProfile> => {
|
||||
const profile = await authApi.login(email, password);
|
||||
setUser(profile);
|
||||
return profile;
|
||||
};
|
||||
|
||||
const register = async (email: string, password: string, name: string): Promise<UserProfile> => {
|
||||
const profile = await authApi.register(email, password, name);
|
||||
setUser(profile);
|
||||
return profile;
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
authApi.logout();
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user,
|
||||
isLoading,
|
||||
isAdmin: user?.role === "admin",
|
||||
login,
|
||||
register,
|
||||
logout,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useAuth = () => {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error("useAuth must be used within AuthProvider");
|
||||
return ctx;
|
||||
};
|
||||
Reference in New Issue
Block a user