Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add getIdToken method #57

Merged
merged 1 commit into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 22 additions & 7 deletions src/createKindeClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,9 @@ const createKindeClient = async (
}
};

const useRefreshToken = async () => {
const useRefreshToken = async (
{tokenType} = {tokenType: 'kinde_access_token'}
) => {
const refresh_token = is_dangerously_use_local_storage
? (localStorage.getItem('kinde_refresh_token') as string)
: (store.getItem('kinde_refresh_token') as string);
Expand All @@ -146,30 +148,42 @@ const createKindeClient = async (
const data = await response.json();
setStore(data);

if (tokenType === 'kinde_id_token') {
return data.id_token;
}

return data.access_token;
} catch (err) {
console.error(err);
}
}
};

const getToken = async () => {
const getTokenType = async (tokenType: string) => {
const token = store.getItem('kinde_token') as KindeState;

if (!token) {
return await useRefreshToken();
return await useRefreshToken({tokenType});
}

const accessToken = store.getItem('kinde_access_token');
const isTokenValid = isValidJwt(accessToken as JWT);
const tokenToReturn = store.getItem(tokenType);
const isTokenValid = isValidJwt(tokenToReturn as JWT);

if (isTokenValid) {
return token.access_token;
return tokenToReturn;
} else {
return await useRefreshToken();
return await useRefreshToken({tokenType});
}
};

const getToken = async () => {
return await getTokenType('kinde_access_token');
};

const getIdToken = async () => {
return await getTokenType('kinde_id_token');
};

const isAuthenticated = async () => {
const accessToken = store.getItem('kinde_access_token');
if (!accessToken) {
Expand Down Expand Up @@ -419,6 +433,7 @@ const createKindeClient = async (

return {
getToken,
getIdToken,
getUser,
getUserProfile,
login,
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export type RedirectOptions = OrgOptions &

export type KindeClient = {
getToken: () => Promise<string | undefined>;
getIdToken: () => Promise<string | undefined>;
isAuthenticated: () => Promise<boolean>;
getUser: () => KindeUser;
getUserProfile: () => Promise<KindeUser | undefined>;
Expand Down
Loading