Seth0330 commited on
Commit
6d4a9a4
·
verified ·
1 Parent(s): cf15125

Create contexts/AuthContext.jsx

Browse files
frontend/src/contexts/AuthContext.jsx ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { createContext, useContext, useState, useEffect } from "react";
2
+ import { getCurrentUser, login, logout as apiLogout } from "@/services/auth";
3
+
4
+ const AuthContext = createContext(null);
5
+
6
+ export function AuthProvider({ children }) {
7
+ const [user, setUser] = useState(null);
8
+ const [loading, setLoading] = useState(true);
9
+ const [token, setToken] = useState(localStorage.getItem("auth_token"));
10
+
11
+ useEffect(() => {
12
+ // Check if user is already authenticated
13
+ if (token) {
14
+ checkAuth();
15
+ } else {
16
+ setLoading(false);
17
+ }
18
+ }, [token]);
19
+
20
+ const checkAuth = async () => {
21
+ try {
22
+ const userData = await getCurrentUser();
23
+ setUser(userData);
24
+ } catch (error) {
25
+ // Token is invalid, clear it
26
+ localStorage.removeItem("auth_token");
27
+ setToken(null);
28
+ setUser(null);
29
+ } finally {
30
+ setLoading(false);
31
+ }
32
+ };
33
+
34
+ const handleLogin = () => {
35
+ // Redirect to backend OAuth login
36
+ const apiUrl = import.meta.env.VITE_API_BASE_URL || "";
37
+ window.location.href = `${apiUrl}/api/auth/login`;
38
+ };
39
+
40
+ const handleLogout = async () => {
41
+ try {
42
+ await apiLogout();
43
+ } catch (error) {
44
+ console.error("Logout error:", error);
45
+ } finally {
46
+ localStorage.removeItem("auth_token");
47
+ setToken(null);
48
+ setUser(null);
49
+ }
50
+ };
51
+
52
+ const handleAuthCallback = (newToken) => {
53
+ localStorage.setItem("auth_token", newToken);
54
+ setToken(newToken);
55
+ checkAuth();
56
+ };
57
+
58
+ const value = {
59
+ user,
60
+ token,
61
+ loading,
62
+ login: handleLogin,
63
+ logout: handleLogout,
64
+ handleAuthCallback,
65
+ isAuthenticated: !!user,
66
+ };
67
+
68
+ return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
69
+ }
70
+
71
+ export function useAuth() {
72
+ const context = useContext(AuthContext);
73
+ if (!context) {
74
+ throw new Error("useAuth must be used within an AuthProvider");
75
+ }
76
+ return context;
77
+ }
78
+