-
Notifications
You must be signed in to change notification settings - Fork 2
/
AuthContext.tsx
79 lines (67 loc) · 2.32 KB
/
AuthContext.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
import { createContext, useEffect, useState } from "react";
import { useLoader } from "../../hooks/useLoader";
import { AuthContextData, AuthMethod, AuthMethodKey, AuthProviderProps, AuthUser, User } from "./auth.model";
import { IAuth } from "./IAuth";
export const AuthContext = createContext<AuthContextData>(
{ } as AuthContextData,
);
export function AuthProvider({ children }: AuthProviderProps) {
const [user, setUser] = useState<User>();
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [authMethod, setAuthMethod] = useState<IAuth>();
const { setIsLoading } = useLoader();
useEffect(() => {
createAuthMethodFromStorage();
}, []);
async function signIn(method: AuthMethodKey, authUser?: AuthUser) {
localStorage.setItem('@Auth.method', method);
const auth = AuthMethod[method];
setAuthMethod(auth);
setIsLoading(true);
const user = await auth.signIn(authUser);
if(user != undefined) {
await setUserLogged(auth)
}
}
function signOut() {
if(authMethod) {
setIsAuthenticated(false);
setUser(undefined);
authMethod?.signOut();
localStorage.removeItem('@Auth.method');
localStorage.removeItem('@Auth.user')
}
else {
console.error('auth method undefined');
}
}
useEffect(() => {
if(authMethod) {
setUserLogged(authMethod);
}
}, [authMethod])
async function setUserLogged(authMethod: IAuth) {
const isAuthenticated = await authMethod.isAuthenticated();
setIsAuthenticated(isAuthenticated);
const user = await authMethod.getUser();
setUser(user);
}
async function createAuthMethodFromStorage(){
const storageMethod = await localStorage.getItem('@Auth.method');
if(storageMethod) {
const method = storageMethod as AuthMethodKey;
const auth = AuthMethod[method];
setAuthMethod(auth);
}
}
function getAuthMethodType(){
return authMethod ? authMethod.type : 'undefined';
}
return (
<AuthContext.Provider
value={{ user, isAuthenticated, signIn, signOut, getAuthMethodType }}
>
{children}
</AuthContext.Provider>
);
}