feat : add front-end using shad cn
This commit is contained in:
62
frontend/src/context/AuthContext.tsx
Normal file
62
frontend/src/context/AuthContext.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import {createContext, useContext, useState} from "react";
|
||||
import api from "@/services/api";
|
||||
|
||||
type AuthContextType = {
|
||||
user: any;
|
||||
token: string | null;
|
||||
login: (username: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
};
|
||||
|
||||
const AuthContext = createContext<AuthContextType | null>(null);
|
||||
|
||||
export function AuthProvider({children}: {children: React.ReactNode}) {
|
||||
const [token, setToken] = useState<string | null>(
|
||||
localStorage.getItem("token"),
|
||||
);
|
||||
|
||||
const [user, setUser] = useState(null);
|
||||
|
||||
async function login(username: string, password: string) {
|
||||
const response = await api.post("/auth/login", {
|
||||
username,
|
||||
password,
|
||||
});
|
||||
|
||||
const token = response.data.token;
|
||||
|
||||
localStorage.setItem("token", token);
|
||||
|
||||
setToken(token);
|
||||
}
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem("token");
|
||||
|
||||
setToken(null);
|
||||
setUser(null);
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user,
|
||||
token,
|
||||
login,
|
||||
logout,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useAuth must be used inside AuthProvider");
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
Reference in New Issue
Block a user