Skip to content

Commit

Permalink
refactor(renew): clean an debug (alpha) (#1273)
Browse files Browse the repository at this point in the history
  • Loading branch information
guillaume-chervet authored Feb 1, 2024
1 parent ffc597b commit 0a15e60
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 27 deletions.
2 changes: 1 addition & 1 deletion examples/react-oidc-demo/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="application/javascript" src="/src/index.js"></script>
<script type="module" src="/src/index.tsx"></script>
</body>
</html>
5 changes: 2 additions & 3 deletions examples/react-oidc-demo/src/MultiAuth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ const fetchWithLogs = (fetch: Fetch) => async (...params: Parameters<Fetch>) =>
return await fetch(url, options, ...rest);
};

const MultiAuth = ({ configurationName, handleConfigurationChange }) => {
console.log('MultiAuth', configurationName);
const MultiAuth = ({ configurationName, handleConfigurationChange }) => {;
const { login, logout, isAuthenticated } = useOidc(configurationName);
const { isAuthenticated: isAuthenticatedDefault } = useOidc('default');
const [fname, setFname] = useState('');
Expand Down Expand Up @@ -156,7 +155,7 @@ export const MultiAuthContainer = () => {
// console.log(`oidc:${configurationName}:${eventName}`, data);
dispatch({ type: 'event', data: { name: `oidc:${configurationName}:${eventName}`, data } });
};
console.log('MultiAuthContainer', configurationName);

return (
<>
<OidcProvider configuration={configurations[configurationName]}
Expand Down
4 changes: 2 additions & 2 deletions packages/oidc-client/src/keepSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const tryKeepSessionAsync = async (oidc: Oidc) =>{
oidc.tokens = tokens;
const getLoginParams = serviceWorker.getLoginParams(oidc.configurationName);
// @ts-ignore
oidc.timeoutId = autoRenewTokens(oidc, oidc.tokens.refreshToken, oidc.tokens.expiresAt, getLoginParams.extras);
oidc.timeoutId = autoRenewTokens(oidc, oidc.tokens.expiresAt, getLoginParams.extras);
const sessionState = await serviceWorker.getSessionStateAsync();
// @ts-ignore
await oidc.startCheckSessionAsync(oidcServerConfiguration.check_session_iframe, configuration.client_id, sessionState);
Expand All @@ -51,7 +51,7 @@ export const tryKeepSessionAsync = async (oidc: Oidc) =>{
oidc.tokens = setTokens(tokens, null, configuration.token_renew_mode);
const getLoginParams = session.getLoginParams();
// @ts-ignore
oidc.timeoutId = autoRenewTokens(oidc, tokens.refreshToken, oidc.tokens.expiresAt, getLoginParams.extras);
oidc.timeoutId = autoRenewTokens(oidc, oidc.tokens.expiresAt, getLoginParams.extras);
const sessionState = await session.getSessionStateAsync();
// @ts-ignore
await oidc.startCheckSessionAsync(oidcServerConfiguration.check_session_iframe, configuration.client_id, sessionState);
Expand Down
18 changes: 9 additions & 9 deletions packages/oidc-client/src/oidc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export type InternalLoginCallback = {

const loginCallbackWithAutoTokensRenewAsync = async (oidc) : Promise<LoginCallback> => {
const { parsedTokens, callbackPath } = await oidc.loginCallbackAsync();
oidc.timeoutId = autoRenewTokens(oidc, parsedTokens.refreshToken, parsedTokens.expiresAt);
oidc.timeoutId = autoRenewTokens(oidc, parsedTokens.expiresAt);
return { callbackPath };
};

Expand Down Expand Up @@ -292,7 +292,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio



async synchroniseTokensAsync(refreshToken, index = 0, forceRefresh = false, extras:StringMap = null, updateTokens) {
async synchroniseTokensAsync(index = 0, forceRefresh = false, extras:StringMap = null, updateTokens) {

while (!navigator.onLine && document.hidden) {
await sleepAsync({milliseconds: 1000});
Expand Down Expand Up @@ -344,7 +344,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
}
}
this.publishEvent(eventNames.refreshTokensAsync_error, { message: 'refresh token silent return' });
return await this.synchroniseTokensAsync(null, nextIndex, forceRefresh, extras, updateTokens);
return await this.synchroniseTokensAsync(nextIndex, forceRefresh, extras, updateTokens);
};

if (index > 4) {
Expand Down Expand Up @@ -374,11 +374,11 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
this.publishEvent(eventNames.logout_from_another_tab, { status: 'session syncTokensAsync' });
return { tokens: null, status: 'LOGGED_OUT' };
case synchroniseTokensStatus.REQUIRE_SYNC_TOKENS:
this.publishEvent(eventNames.refreshTokensAsync_begin, { refreshToken, status, tryNumber: index });
this.publishEvent(eventNames.refreshTokensAsync_begin, { refreshToken: tokens.refreshToken, status, tryNumber: index });
return await localsilentLoginAsync();
default: {
this.publishEvent(eventNames.refreshTokensAsync_begin, { refreshToken, status, tryNumber: index });
if (!refreshToken) {
this.publishEvent(eventNames.refreshTokensAsync_begin, { refreshToken: tokens.refreshToken, status, tryNumber: index });
if (!tokens.refreshToken) {
return await localsilentLoginAsync();
}

Expand Down Expand Up @@ -440,7 +440,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
message: 'bad request',
tokenResponse,
});
return await this.synchroniseTokensAsync(refreshToken, nextIndex, forceRefresh, extras, updateTokens);
return await this.synchroniseTokensAsync(nextIndex, forceRefresh, extras, updateTokens);
}
};
return await localFunctionAsync();
Expand All @@ -449,7 +449,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
} catch (exception: any) {
console.error(exception);
this.publishEvent(eventNames.refreshTokensAsync_silent_error, { message: 'exception', exception: exception.message });
return this.synchroniseTokensAsync(refreshToken, nextIndex, forceRefresh, extras, updateTokens);
return this.synchroniseTokensAsync(nextIndex, forceRefresh, extras, updateTokens);
}
}

Expand Down Expand Up @@ -512,7 +512,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
}
timer.clearTimeout(this.timeoutId);
// @ts-ignore
this.renewTokensPromise = renewTokensAndStartTimerAsync(this, this.tokens.refreshToken, true, extras);
this.renewTokensPromise = renewTokensAndStartTimerAsync(this, true, extras);
return this.renewTokensPromise.then(result => {
this.renewTokensPromise = null;
return result;
Expand Down
25 changes: 14 additions & 11 deletions packages/oidc-client/src/renewTokens.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import {initSession} from './initSession.js';
import {initWorkerAsync} from './initWorker.js';
import Oidc from './oidc.js';
import {computeTimeLeft, setTokens} from './parseTokens.js';
import {computeTimeLeft, setTokens, Tokens} from './parseTokens.js';
import timer from './timer.js';
import {OidcConfiguration, StringMap} from './types.js';

async function syncTokens(oidc:Oidc, refreshToken, forceRefresh: boolean, extras: StringMap) {
async function syncTokens(oidc:Oidc, forceRefresh: boolean, extras: StringMap) {
const updateTokens = (tokens) => {
oidc.tokens = tokens;
};
const {tokens, status} = await oidc.synchroniseTokensAsync(refreshToken, 0, forceRefresh, extras, updateTokens);
const {tokens, status} = await oidc.synchroniseTokensAsync(0, forceRefresh, extras, updateTokens);

const serviceWorker = await initWorkerAsync(oidc.configuration, oidc.configurationName);
if (!serviceWorker) {
Expand All @@ -24,7 +24,7 @@ async function syncTokens(oidc:Oidc, refreshToken, forceRefresh: boolean, extras
return tokens;
}

async function loadLatestTokensAsync(oidc, configuration) {
const loadLatestTokensAsync = async (oidc:Oidc, configuration:OidcConfiguration) :Promise<Tokens> => {
const serviceWorker = await initWorkerAsync(configuration, oidc.configurationName);
if (serviceWorker) {
const oidcServerConfiguration = await oidc.initAsync(configuration.authority, configuration.authority_configuration);
Expand All @@ -39,7 +39,7 @@ async function loadLatestTokensAsync(oidc, configuration) {
}
}

export async function renewTokensAndStartTimerAsync(oidc, refreshToken, forceRefresh = false, extras:StringMap = null) {
export async function renewTokensAndStartTimerAsync(oidc, forceRefresh = false, extras:StringMap = null) {

const configuration = oidc.configuration;
const lockResourcesName = `${configuration.client_id}_${oidc.configurationName}_${configuration.authority}`;
Expand All @@ -48,14 +48,14 @@ export async function renewTokensAndStartTimerAsync(oidc, refreshToken, forceRef
const serviceWorker = await initWorkerAsync(oidc.configuration, oidc.configurationName);

if(configuration?.storage === window?.sessionStorage && !serviceWorker) {
tokens = await syncTokens(oidc, refreshToken, forceRefresh, extras);
tokens = await syncTokens(oidc, forceRefresh, extras);
} else {
tokens = await navigator.locks.request(lockResourcesName, { ifAvailable: true }, async (lock) => {
if(!lock){
oidc.publishEvent(Oidc.eventNames.syncTokensAsync_lock_not_available, { lock: 'lock not available' });
return await loadLatestTokensAsync(oidc, configuration);
}
return await syncTokens(oidc, refreshToken, forceRefresh, extras);
return await syncTokens(oidc, forceRefresh, extras);
});

}
Expand All @@ -66,19 +66,19 @@ export async function renewTokensAndStartTimerAsync(oidc, refreshToken, forceRef

if (oidc.timeoutId) {
// @ts-ignore
oidc.timeoutId = autoRenewTokens(oidc, tokens.refreshToken, oidc.tokens.expiresAt, extras);
oidc.timeoutId = autoRenewTokens(oidc, oidc.tokens.expiresAt, extras);
}

return oidc.tokens;
}

export const autoRenewTokens = (oidc:Oidc, refreshToken, expiresAt, extras:StringMap = null) => {
export const autoRenewTokens = (oidc:Oidc, expiresAt, extras:StringMap = null) => {
const refreshTimeBeforeTokensExpirationInSecond = oidc.configuration.refresh_time_before_tokens_expiration_in_second;
return timer.setTimeout(async () => {
const timeLeft = computeTimeLeft(refreshTimeBeforeTokensExpirationInSecond, expiresAt);
const timeInfo = { timeLeft };
oidc.publishEvent(Oidc.eventNames.token_timer, timeInfo);
await renewTokensAndStartTimerAsync(oidc, refreshToken, false, extras);
await renewTokensAndStartTimerAsync(oidc, false, extras);
}, 1000);
};

Expand Down Expand Up @@ -118,7 +118,10 @@ export const syncTokensInfoAsync = (oidc: Oidc) => async (configuration:OidcConf
nonce = await serviceWorker.getNonceAsync();
} else {
const session = initSession(configurationName, configuration.storage ?? sessionStorage);
const { tokens, status } = await session.initAsync();
let { tokens, status } = await session.initAsync();
if(tokens){
tokens = setTokens(tokens, oidc.tokens, configuration.token_renew_mode);
}
if (!tokens) {
return { tokens: null, status: 'LOGOUT_FROM_ANOTHER_TAB', nonce: nullNonce };
} else if (status === 'SESSIONS_LOST') {
Expand Down
2 changes: 1 addition & 1 deletion packages/oidc-client/src/silentLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export const defaultSilentLoginAsync = (window, configurationName, configuration
oidc.tokens = silentResult.tokens;
publishEvent(eventNames.token_aquired, {});
// @ts-ignore
oidc.timeoutId = autoRenewTokens(oidc, oidc.tokens.refreshToken, oidc.tokens.expiresAt, extras);
oidc.timeoutId = autoRenewTokens(oidc, oidc.tokens.expiresAt, extras);
return {};
}
} catch (e) {
Expand Down

0 comments on commit 0a15e60

Please sign in to comment.