-
Notifications
You must be signed in to change notification settings - Fork 2
/
auth.tsx
109 lines (85 loc) · 2.2 KB
/
auth.tsx
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import React, {
useState,
useContext,
PropsWithChildren,
useEffect,
} from "react";
import { useLocation } from "react-router-dom";
import supabase, { ISupabaseSession, ISupabaseUser } from "services";
interface ILogin {
provider: "discord";
}
interface IAuthContext {
user: ISupabaseUser | null;
login: (options: ILogin) => void;
logout: () => void;
}
const AuthContext = React.createContext<IAuthContext>(null!);
export const useAuth = () => {
const auth = useContext(AuthContext);
if (!auth) {
throw new Error("Must useAuth within AuthProvider");
}
return auth;
};
const useWaitForSession = () => {
const location = useLocation();
if (location.hash) {
const params = new URLSearchParams(location.hash.substring(1));
/*
this is a redirect from discord OAuth
*/
return (
params.has("token_type") &&
params.get("token_type") === "bearer" &&
params.has("access_token") &&
params.has("refresh_token") &&
params.has("provider_token")
);
}
if (localStorage.getItem("supabase.auth.token") === null) {
return false;
}
return true;
};
const AuthProvider = (props: PropsWithChildren<unknown>) => {
const location = useLocation();
const [authenticating, setAuthenticating] = useState<boolean>(
useWaitForSession()
);
const [session, setSession] = useState<ISupabaseSession | null>(null);
const login = ({ provider }: ILogin) => {
const from = location.state?.from?.pathname || "/";
return supabase.auth.signIn(
{
provider,
},
{ redirectTo: `${process.env.REACT_APP_CLIENT_HOST}${from}` }
);
};
const logout = () => supabase.auth.signOut();
useEffect(() => {
const session = supabase.auth.session();
if (session) {
setSession(session);
setAuthenticating(false);
}
supabase.auth.onAuthStateChange((_event, session) => {
setSession(session);
setAuthenticating(false);
});
}, []);
if (authenticating) return null;
return (
<AuthContext.Provider
value={{
user: session?.user ?? null,
login,
logout,
}}
>
{props.children}
</AuthContext.Provider>
);
};
export default AuthProvider;