-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthContext.js
More file actions
65 lines (55 loc) · 1.68 KB
/
AuthContext.js
File metadata and controls
65 lines (55 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"use client";
import { createContext, useContext, useEffect, useState } from "react";
import { auth } from "../lib/firebase";
import { onAuthStateChanged, signOut as firebaseSignOut } from "firebase/auth";
const AuthContext = createContext({
user: null,
loading: true,
signOut: async () => {},
});
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
// Subscribe to auth state changes
const unsubscribe = onAuthStateChanged(auth, async (currentUser) => {
setUser(currentUser);
setLoading(false);
// Set or clear session cookie
if (currentUser) {
// Get the ID token
const token = await currentUser.getIdToken();
// Set session cookie (for middleware)
document.cookie = `session=${token}; path=/; max-age=3600; SameSite=Lax`;
} else {
// Clear session cookie
document.cookie =
"session=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
});
return () => unsubscribe();
}, []);
const signOut = async () => {
try {
await firebaseSignOut(auth);
// Clear session cookie
document.cookie =
"session=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
} catch (error) {
console.error("Error signing out:", error);
throw error;
}
};
return (
<AuthContext.Provider value={{ user, loading, signOut }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
};