generated from rhdeck/ts-template
/
index.tsx
109 lines (109 loc) · 2.87 KB
/
index.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, {
FC,
useState,
useEffect,
useCallback,
createContext,
useContext,
useMemo,
} from "react";
import { Auth } from "@aws-amplify/auth";
import { Hub } from "@aws-amplify/core";
import type { HubCapsule } from "@aws-amplify/core/lib/Hub";
const context =
createContext<
| {
Auth: typeof Auth;
authState: string;
authData: any;
updateState: typeof updateState;
checkAuthStatus: () => Promise<void>;
}
| undefined
>(undefined);
const { Provider } = context;
function updateState(event: string, data?: any) {
Hub.dispatch("auth", { event, data });
}
export const AuthProvider: FC<{ debug?: boolean }> = ({
children,
debug = false,
}) => {
const [authState, setAuthState] = useState<string>("loading");
const [authData, setAuthData] = useState<any>();
const handleStateChange = useCallback((authState: string, authData: any) => {
if (authState === "signedOut") {
authState = "signIn";
}
setAuthState(authState);
setAuthData(authData);
}, []);
const checkAuthStatus = useCallback(async () => {
try {
const creds = await Auth.currentAuthenticatedUser();
setAuthState("signedIn");
setAuthData(creds);
} catch (e) {
setAuthState((oldAuthState) =>
oldAuthState === "loading" ? "" : oldAuthState
);
}
}, []);
useEffect(() => {
checkAuthStatus();
}, []);
const handler = (capsule: HubCapsule): void => {
if (debug) console.log("got a handler fired in here", capsule);
const { payload } = capsule;
switch (payload.event) {
case "signIn":
handleStateChange("signedIn", payload.data);
break;
case "cognitoHostedUI":
handleStateChange("signedIn", payload.data);
break;
case "cognitoHostedUI_failure":
handleStateChange("signIn", null);
break;
case "parsingUrl_failure":
handleStateChange("signIn", null);
break;
case "signOut":
handleStateChange("signIn", null);
break;
case "customGreetingSignOut":
handleStateChange("signIn", null);
break;
default:
handleStateChange(payload.event, payload.data);
//TODO
break;
}
};
useEffect(() => {
Hub.listen("auth", handler);
return () => {
Hub.remove("auth", handler);
};
}, []);
const value = useMemo(
() => ({ updateState, Auth, authState, authData, checkAuthStatus }),
[authState, authData, checkAuthStatus]
);
return <Provider value={value}>{children}</Provider>;
};
export default AuthProvider;
export const useAuth = () => {
const c = useContext(context);
if (!c) throw "Cannot use useAuth when not under the AuthProvider";
return c;
};
export function withAuthProvider(C: FC): FC {
return (props) => {
return (
<AuthProvider>
<C {...props} />
</AuthProvider>
);
};
}