narinder1231 commited on
Commit
2efe57e
·
1 Parent(s): 37725e0

Add AuthContext and AuthProvider for authentication state management

Browse files
src/context/AuthContext.tsx ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import { createContext } from "react";
2
+
3
+ interface AuthContextType {
4
+ isAuthenticated: boolean;
5
+ login: (token: string) => void;
6
+ logout: () => void;
7
+ }
8
+
9
+ export const AuthContext = createContext<AuthContextType | null>(null);
src/context/AuthProvider.tsx ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState } from "react";
2
+
3
+ import { AuthContext } from "./AuthContext";
4
+
5
+ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
6
+ const [isAuthenticated, setIsAuthenticated] = useState<boolean>(
7
+ !!localStorage.getItem("auth_token")
8
+ );
9
+
10
+ const login = (token: string) => {
11
+ localStorage.setItem("auth_token", token);
12
+ setIsAuthenticated(true);
13
+ };
14
+
15
+ const logout = () => {
16
+ localStorage.removeItem("auth_token");
17
+ setIsAuthenticated(false);
18
+ window.location.href = "/signin";
19
+ };
20
+
21
+ return (
22
+ <AuthContext.Provider value={{ isAuthenticated, login, logout }}>
23
+ {children}
24
+ </AuthContext.Provider>
25
+ );
26
+ };
src/hooks/useAuth.ts ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useContext } from "react";
2
+
3
+ import { AuthContext } from "../context/AuthContext";
4
+
5
+ export const useAuth = () => {
6
+ const context = useContext(AuthContext);
7
+ if (!context) {
8
+ throw new Error("useAuth must be used within an AuthProvider");
9
+ }
10
+ return context;
11
+ };