-
Notifications
You must be signed in to change notification settings - Fork 5
/
AuthenticatedProvider.tsx
145 lines (135 loc) · 4.11 KB
/
AuthenticatedProvider.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import {
useAsyncSetEffect,
useDeepState,
useMounted,
} from "@trajano/react-hooks";
import { useAuth } from "@trajano/spring-docker-auth-context";
import {
PropsWithChildren,
useCallback,
useEffect,
useMemo,
useReducer,
useRef,
} from "react";
import EventSource from "react-native-sse";
import { IAuthenticated } from "./IAuthenticated";
import { AuthenticatedContext } from "./IAuthenticatedContext";
import { JwtClaims } from "./JwtClaims";
import { jwtVerify } from "./jwtVerify";
import { useDb } from "./useDb";
/*
* import '@reduxjs/toolkit';
* import { legacy_createStore as createStore } from "redux";
* export const store = createStore((state = 0, action) => state);
*/
/*
* let store;
* try {
* const { configureStore } = require("@reduxjs/toolkit");
* store = configureStore({
* reducer: {},
* });
* } catch (error) {
* alert(`Caught error: ${error}`);
* }
* console.log(store);
*/
// At present this has a problem on restore in that the access token is not valid yet.
type AuthenticatedProviderProps = PropsWithChildren<{
clientId: string;
issuer: string;
verifyClaims?: boolean;
whoAmIEndpoint?: string;
}>;
export function AuthenticatedProvider({
clientId,
issuer,
whoAmIEndpoint = "whoami/",
verifyClaims = true,
children,
}: AuthenticatedProviderProps) {
const { baseUrl, accessToken, authorization } = useAuth();
const [claims, setClaims] = useDeepState<JwtClaims | undefined>();
const isMounted = useMounted();
const username = useMemo(() => claims?.sub ?? "", [claims]);
const verified = useMemo(() => !!claims, [claims]);
const eventStream = useRef<EventSource<string>>();
const { loaded: dbLoaded, db } = useDb("mydb");
const [internalState, updateInternalStateFromServerSentEvent] = useReducer(
(state: string[], nextEvent: string) => [...state, nextEvent].slice(-5),
[]
);
const verifyToken = useCallback(async () => {
if (!verifyClaims) {
return undefined;
}
/*
* when access token changes the value could fail.
* when the internet is broken then the verification will fail
* maybe use a reducer here?
*/
try {
return await jwtVerify(accessToken, `${baseUrl}jwks`, issuer, clientId);
} catch (_e: unknown) {
return Promise.resolve(undefined);
}
}, [verifyClaims, accessToken, baseUrl, issuer, clientId]);
useAsyncSetEffect(verifyToken, setClaims, []);
useEffect(() => {
/*
* this should be refactored to it's own file to provide the data stream
* log.warn({ verified, username })
*/
if (verified && username && accessToken) {
eventStream.current = new EventSource<string>(
new URL("/grpc/Echo/echoStream", baseUrl),
{
headers: {
authorization: `Bearer ${accessToken}`,
"content-type": "application/json",
accept: "text/event-stream",
},
method: "POST",
body: JSON.stringify({ message: `I am ${username}` }),
}
);
eventStream.current.addEventListener("message", (event) => {
if (event.type === "message" && event.data && isMounted()) {
updateInternalStateFromServerSentEvent(event.data);
}
});
return () => eventStream.current?.close();
}
}, [baseUrl, isMounted, verified, username, accessToken]);
const whoami = useCallback(async () => {
console.log({ whoamiCall: accessToken?.slice(-5) });
const r = await fetch(baseUrl + whoAmIEndpoint, {
headers: {
authorization: authorization!,
"content-type": "application/json",
accept: "application/json",
},
method: "GET",
credentials: "omit",
});
return r.json();
}, [accessToken, baseUrl, whoAmIEndpoint, authorization]);
const contextValue = useMemo<IAuthenticated>(
() => ({
internalState,
username,
verified,
whoami,
claims,
dbLoaded,
db,
}),
[internalState, username, verified, whoami, claims, dbLoaded, db]
);
return (
<AuthenticatedContext.Provider value={contextValue}>
{children}
</AuthenticatedContext.Provider>
);
}