forked from Movalabs-crew/mova-store
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthContext.js
More file actions
78 lines (65 loc) · 1.89 KB
/
Copy pathAuthContext.js
File metadata and controls
78 lines (65 loc) · 1.89 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
66
67
68
69
70
71
72
73
74
75
76
77
78
"use client";
import React, { createContext, useContext, useEffect, useState, useMemo } from "react";
import { supabase } from "./supabase";
import { mapAuthUser } from "./auth";
const AuthContext = createContext();
/**
* Checks if an email is in the admin whitelist.
* @param {string|null|undefined} email - User email to check
* @returns {boolean} True if user is an admin
*/
const checkIsAdmin = (email) => {
if (!email) return false;
const adminEmailsRaw = process.env.NEXT_PUBLIC_ADMIN_EMAILS || "";
const adminEmails = adminEmailsRaw
.split(",")
.map((e) => e.trim().toLowerCase())
.filter((e) => e !== "");
return adminEmails.includes(email.toLowerCase());
};
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let mounted = true;
supabase.auth
.getSession()
.then(({ data: { session } }) => {
if (!mounted) return;
setUser(mapAuthUser(session?.user));
setLoading(false);
})
.catch((err) => {
if (!mounted) return;
console.error("Failed to retrieve auth session:", err);
setUser(null);
setLoading(false);
});
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((_event, session) => {
setUser(mapAuthUser(session?.user));
setLoading(false);
});
return () => {
mounted = false;
subscription.unsubscribe();
};
}, []);
const isAdmin = useMemo(() => {
return user?.email ? checkIsAdmin(user.email) : false;
}, [user?.email]);
const value = useMemo(
() => ({
user,
loading,
isAdmin,
isAuthenticated: !!user,
}),
[user, loading, isAdmin]
);
return (
React.createElement(AuthContext.Provider, { value }, children)
);
};
export const useAuth = () => useContext(AuthContext);