Skip to content

Commit b8cabf5

Browse files
authored
Merge pull request #178 from kinde-oss/feat/store-injection
Feat/store injection
2 parents c4c5d3e + 4bf76c9 commit b8cabf5

File tree

2 files changed

+77
-96
lines changed

2 files changed

+77
-96
lines changed

src/state/KindeProvider.tsx

Lines changed: 76 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
Role,
2929
GeneratePortalUrlParams,
3030
navigateToKinde,
31+
setActiveStorage,
3132
} from "@kinde/js-utils";
3233
import * as storeState from "./store";
3334
import React, {
@@ -41,7 +42,11 @@ import { KindeContext, KindeContextProps } from "./KindeContext";
4142
import { getRedirectUrl } from "../utils/getRedirectUrl";
4243
import packageJson from "../../package.json";
4344
import { ErrorProps, LogoutOptions, PopupOptions } from "./types";
44-
import type { RefreshTokenResult } from "@kinde/js-utils";
45+
import type {
46+
RefreshTokenResult,
47+
Scopes,
48+
SessionManager,
49+
} from "@kinde/js-utils";
4550
// TODO: need to look for old token store and convert.
4651
storageSettings.keyPrefix = "";
4752

@@ -104,6 +109,7 @@ type KindeProviderProps = {
104109
* This is the options for the popup window.
105110
*/
106111
popupOptions?: PopupOptions;
112+
store?: SessionManager;
107113
};
108114

109115
const defaultCallbacks: KindeCallbacks = {
@@ -138,9 +144,14 @@ export const KindeProvider = ({
138144
logoutUri,
139145
forceChildrenRender = false,
140146
popupOptions = {},
147+
store = storeState.memoryStorage,
141148
}: KindeProviderProps) => {
142149
const mergedCallbacks = { ...defaultCallbacks, ...callbacks };
143150

151+
useEffect(() => {
152+
setActiveStorage(store);
153+
}, [store]);
154+
144155
frameworkSettings.framework = "react";
145156
frameworkSettings.frameworkVersion = React.version;
146157
frameworkSettings.sdkVersion = packageJson.version;
@@ -154,17 +165,6 @@ export const KindeProvider = ({
154165
});
155166
const initRef = useRef(false);
156167

157-
useEffect(() => {
158-
storeState.memoryStorage.setItems({
159-
[storeState.LocalKeys.domain]: domain,
160-
[storeState.LocalKeys.clientId]: clientId,
161-
[storeState.LocalKeys.audience]: audience,
162-
[storeState.LocalKeys.redirectUri]: redirectUri,
163-
[storeState.LocalKeys.logoutUri]: logoutUri,
164-
});
165-
return;
166-
}, [audience, scope, clientId, domain, redirectUri, logoutUri]);
167-
168168
const login = useCallback(
169169
async (
170170
options: LoginMethodParams & { state?: Record<string, string> } = {},
@@ -178,6 +178,7 @@ export const KindeProvider = ({
178178
clientId,
179179
...options,
180180
supportsReauth: true,
181+
scope: scope?.split(" ") as Scopes[],
181182
state: base64UrlEncode(
182183
JSON.stringify({
183184
kinde: { event: AuthEvent.login },
@@ -187,10 +188,6 @@ export const KindeProvider = ({
187188
redirectURL: getRedirectUrl(options.redirectURL || redirectUri),
188189
};
189190

190-
const domain = (await storeState.memoryStorage.getSessionItem(
191-
storeState.LocalKeys.domain,
192-
)) as string;
193-
194191
const authUrl = await generateAuthUrl(
195192
domain,
196193
IssuerRouteTypes.login,
@@ -214,7 +211,7 @@ export const KindeProvider = ({
214211
);
215212
}
216213
},
217-
[audience, clientId, redirectUri, popupOptions, mergedCallbacks],
214+
[audience, clientId, redirectUri, popupOptions, mergedCallbacks, domain, scope],
218215
);
219216

220217
const register = useCallback(
@@ -234,21 +231,13 @@ export const KindeProvider = ({
234231
}),
235232
),
236233
supportsReauth: true,
237-
audience: (await storeState.memoryStorage.getSessionItem(
238-
storeState.LocalKeys.audience,
239-
)) as string,
240-
clientId: (await storeState.memoryStorage.getSessionItem(
241-
storeState.LocalKeys.clientId,
242-
)) as string,
234+
audience,
235+
clientId,
243236
redirectURL: getRedirectUrl(options?.redirectURL || redirectUri),
244237
prompt: PromptTypes.create,
245238
};
246239

247240
try {
248-
const domain = (await storeState.memoryStorage.getSessionItem(
249-
storeState.LocalKeys.domain,
250-
)) as string;
251-
252241
const authUrl = await generateAuthUrl(
253242
domain,
254243
IssuerRouteTypes.register,
@@ -282,75 +271,74 @@ export const KindeProvider = ({
282271
);
283272
}
284273
},
285-
[redirectUri, popupOptions, mergedCallbacks],
274+
[redirectUri, popupOptions, mergedCallbacks, audience, clientId, domain],
286275
);
287276

288-
const logout = useCallback(async (options?: string | LogoutOptions) => {
289-
try {
290-
const domain = (await storeState.memoryStorage.getSessionItem(
291-
storeState.LocalKeys.domain,
292-
)) as string;
293-
294-
const params = new URLSearchParams();
295-
296-
if (options) {
297-
if (options && typeof options === "string") {
298-
params.append("redirect", options);
299-
} else if (typeof options === "object") {
300-
if (options.redirectUrl || logoutUri) {
301-
params.append("redirect", options.redirectUrl || logoutUri || "");
302-
}
303-
if (options.allSessions) {
304-
params.append("all_sessions", String(options.allSessions));
277+
const logout = useCallback(
278+
async (options?: string | LogoutOptions) => {
279+
try {
280+
const params = new URLSearchParams();
281+
282+
if (options) {
283+
if (options && typeof options === "string") {
284+
params.append("redirect", options);
285+
} else if (typeof options === "object") {
286+
if (options.redirectUrl || logoutUri) {
287+
params.append("redirect", options.redirectUrl || logoutUri || "");
288+
}
289+
if (options.allSessions) {
290+
params.append("all_sessions", String(options.allSessions));
291+
}
305292
}
293+
} else {
294+
params.append("redirect", logoutUri || "");
306295
}
307-
} else {
308-
params.append("redirect", logoutUri || "");
309-
}
310296

311-
setState((val) => {
312-
return { ...val, user: undefined, isAuthenticated: false };
313-
});
297+
await Promise.all([
298+
store.removeSessionItem(StorageKeys.idToken),
299+
store.removeSessionItem(StorageKeys.accessToken),
300+
store.removeSessionItem(StorageKeys.refreshToken),
301+
storeState.localStorage.removeSessionItem(StorageKeys.refreshToken),
302+
]);
314303

315-
await Promise.all([
316-
storeState.memoryStorage.removeSessionItem(StorageKeys.idToken),
317-
storeState.memoryStorage.removeSessionItem(StorageKeys.accessToken),
318-
storeState.memoryStorage.removeSessionItem(StorageKeys.refreshToken),
319-
storeState.localStorage.removeSessionItem(StorageKeys.refreshToken),
320-
]);
304+
setState((val) => {
305+
return { ...val, user: undefined, isAuthenticated: false };
306+
});
321307

322-
await storeState.localStorage.setSessionItem(
323-
storeState.LocalKeys.performingLogout,
324-
"true",
325-
);
308+
await storeState.localStorage.setSessionItem(
309+
storeState.LocalKeys.performingLogout,
310+
"true",
311+
);
326312

327-
try {
328-
await navigateToKinde({
329-
url: `${domain}/logout?${params.toString()}`,
330-
popupOptions,
331-
});
313+
try {
314+
await navigateToKinde({
315+
url: `${domain}/logout?${params.toString()}`,
316+
popupOptions,
317+
});
318+
} catch (error) {
319+
mergedCallbacks.onError?.(
320+
{
321+
error: "ERR_POPUP",
322+
errorDescription: (error as Error).message,
323+
},
324+
{},
325+
{} as KindeContextProps,
326+
);
327+
}
332328
} catch (error) {
329+
console.error("Logout error:", error);
333330
mergedCallbacks.onError?.(
334331
{
335-
error: "ERR_POPUP",
336-
errorDescription: (error as Error).message,
332+
error: "ERR_LOGOUT",
333+
errorDescription: String(error),
337334
},
338335
{},
339-
{} as KindeContextProps,
336+
contextValue,
340337
);
341338
}
342-
} catch (error) {
343-
console.error("Logout error:", error);
344-
mergedCallbacks.onError?.(
345-
{
346-
error: "ERR_LOGOUT",
347-
errorDescription: String(error),
348-
},
349-
{},
350-
contextValue,
351-
);
352-
}
353-
}, []);
339+
},
340+
[store, popupOptions, mergedCallbacks, logoutUri, domain],
341+
);
354342

355343
const contextValue = useMemo((): KindeContextProps => {
356344
return {
@@ -553,13 +541,13 @@ export const KindeProvider = ({
553541
const init = useCallback(async () => {
554542
if (initRef.current) return;
555543
try {
556-
try {
557-
await checkAuth({ domain, clientId });
558-
} catch (err) {
559-
console.warn("checkAuth failed:", err);
560-
setState((v: ProviderState) => ({ ...v, isLoading: false }));
561-
}
562-
initRef.current = true;
544+
try {
545+
await checkAuth({ domain, clientId });
546+
} catch (err) {
547+
console.warn("checkAuth failed:", err);
548+
setState((v: ProviderState) => ({ ...v, isLoading: false }));
549+
}
550+
initRef.current = true;
563551
const params = new URLSearchParams(window.location.search);
564552

565553
if (params.has("error")) {

src/state/store.ts

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,12 @@ import {
66
} from "@kinde/js-utils";
77

88
enum LocalKeys {
9-
domain = "domain",
10-
clientId = "client_id",
11-
audience = "audience",
12-
redirectUri = "redirect_uri",
13-
logoutUri = "logout_uri",
149
performingLogout = "performing_logout",
1510
}
1611

17-
const memoryStorage = new MemoryStorage<LocalKeys>();
12+
const memoryStorage = new MemoryStorage();
1813
const localStorage = new LocalStorage<LocalKeys>();
1914

20-
// TODO: Resolve type issue
21-
//@ts-expect-error valid assignment
2215
setActiveStorage(memoryStorage);
2316
//@ts-expect-error valid assignment
2417
setInsecureStorage(localStorage);

0 commit comments

Comments
 (0)