Skip to content

Commit

Permalink
refactor(auth-js): improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
Badisi committed Feb 29, 2024
1 parent 6c238b1 commit b35bbc2
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 51 deletions.
6 changes: 5 additions & 1 deletion projects/auth-js/oidc/mobile/mobile-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,11 @@ export class MobileStorage implements AsyncStorage {
this._logger.create(`removeItem('${key}')`);

if (CAPACITOR_SECURE_STORAGE) {
await CAPACITOR_SECURE_STORAGE.remove({ key });
try {
await CAPACITOR_SECURE_STORAGE.remove({ key });
} catch {
/* no-op */
}
} else if (CAPACITOR_PREFERENCES) {
await CAPACITOR_PREFERENCES.remove({ key });
} else if (CAPACITOR_STORAGE) {
Expand Down
70 changes: 37 additions & 33 deletions projects/auth-js/oidc/oidc-auth-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,19 @@ export class OIDCAuthManager extends AuthManager<OIDCAuthSettings> {

// Decide what to do..
if (AuthUtils.isUrlMatching(location.href, this.settings.internal?.redirect_uri)) {
await this.runSyncOrAsync(() => this.backFromSigninRedirect());
// Back from signin redirect
await this.runSyncOrAsync(async () => {
const redirectUrl = sessionStorage.getItem(REDIRECT_URL_KEY);
await this.callSignin(() => this.userManager!.signinRedirectCallback(location.href), redirectUrl);
sessionStorage.removeItem(REDIRECT_URL_KEY);
});
} else if (AuthUtils.isUrlMatching(location.href, this.settings.internal?.post_logout_redirect_uri)) {
await this.runSyncOrAsync(() => this.backFromSignoutRedirect());
// Back from signout redirect
await this.runSyncOrAsync(async () => {
const redirectUrl = sessionStorage.getItem(REDIRECT_URL_KEY);
await this.callSignout(() => this.userManager!.signoutRedirectCallback(location.href), redirectUrl);
sessionStorage.removeItem(REDIRECT_URL_KEY);
});
} else if (this.settings.retrieveUserSession || this.settings.loginRequired) {
const signinSilent = async (): Promise<void> => {
await this.runSyncOrAsync(() => this.signinSilent()
Expand Down Expand Up @@ -177,14 +187,11 @@ export class OIDCAuthManager extends AuthManager<OIDCAuthSettings> {
public async logout(args?: LogoutArgs): Promise<void> {
const redirectUrl = args?.redirectUrl ?? location.href;
if (AuthUtils.isNativeMobile()) {
await this.userManager?.signoutMobile(args);
await this.redirect(redirectUrl);
this.postLogoutVerification(redirectUrl);
await this.callSignout(() => this.userManager!.signoutMobile(args), redirectUrl);
} else {
switch (args?.desktopNavigationType ?? this.settings.desktopNavigationType) {
case DesktopNavigation.POPUP:
await this.userManager?.signoutPopup(args);
await this.redirect(redirectUrl);
await this.callSignout(() => this.userManager!.signoutPopup(args), redirectUrl);
break;
case DesktopNavigation.REDIRECT:
default:
Expand All @@ -198,25 +205,11 @@ export class OIDCAuthManager extends AuthManager<OIDCAuthSettings> {
public async login(args?: LoginArgs): Promise<boolean> {
const redirectUrl = args?.redirectUrl ?? location.href;
if (AuthUtils.isNativeMobile()) {
this.notifyRenew(true);
await this.userManager?.signinMobile(args)
.finally(() => this.notifyRenew(false));
await this.redirect(redirectUrl);
await this.callSignin(() => this.userManager!.signinMobile(args), redirectUrl);
} else {
switch (args?.desktopNavigationType ?? this.settings.desktopNavigationType) {
case DesktopNavigation.POPUP:
this.notifyRenew(true);
await this.userManager?.signinPopup(args)
.catch((error: Error) => {
if (error?.message === 'Attempted to navigate on a disposed window') {
error = new Error('[OIDCAuthManager] Attempted to navigate on a disposed window.');
error.stack = undefined;
error.message += '\n\nⓘ This may be due to an ad blocker.';
}
throw error;
})
.finally(() => this.notifyRenew(false));
await this.redirect(redirectUrl);
await this.callSignin(() => this.userManager!.signinPopup(args), redirectUrl);
break;
case DesktopNavigation.REDIRECT:
default:
Expand Down Expand Up @@ -435,30 +428,41 @@ export class OIDCAuthManager extends AuthManager<OIDCAuthSettings> {
}
}

private async backFromSigninRedirect(): Promise<void> {
private async callSignin(managerCall: () => Promise<unknown>, redirectUrl: string | null): Promise<void> {
try {
await this.userManager?.signinRedirectCallback(location.href);
await this.redirect(sessionStorage.getItem(REDIRECT_URL_KEY));
this.notifyRenew(true);
await managerCall().catch((error: Error) => {
if (error?.message === 'Attempted to navigate on a disposed window') {
error = new Error('[OIDCAuthManager] Attempted to navigate on a disposed window.');
error.stack = undefined;
error.message += '\n\nⓘ This may be due to an ad blocker.';
}
throw error;
});
await this.redirect(redirectUrl);
} catch (error) {
await this.redirect('/', error);
throw error;
} finally {
sessionStorage.removeItem(REDIRECT_URL_KEY);
this.notifyRenew(false);
}
}

private async backFromSignoutRedirect(): Promise<void> {
let redirectUrl = sessionStorage.getItem(REDIRECT_URL_KEY);
private async callSignout(managerCall: () => Promise<unknown>, redirectUrl: string | null): Promise<void> {
try {
await this.userManager?.signoutRedirectCallback(location.href);
await managerCall().catch((error: Error) => {
if (error?.message === 'Attempted to navigate on a disposed window') {
error = new Error('[OIDCAuthManager] Attempted to navigate on a disposed window.');
error.stack = undefined;
error.message += '\n\nⓘ This may be due to an ad blocker.';
}
throw error;
});
await this.redirect(redirectUrl);
await this.removeUser();
} catch (error) {
redirectUrl = '/';
await this.redirect(redirectUrl, error);
throw error;
} finally {
sessionStorage.removeItem(REDIRECT_URL_KEY);
this.postLogoutVerification(redirectUrl);
}
}
Expand Down
42 changes: 25 additions & 17 deletions projects/auth-js/oidc/oidc-user-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,17 @@ export class OidcUserManager extends UserManager {

const handle = this._mobileNavigator.prepare(this.settings.post_logout_redirect_uri!, params);

await this._signout({
request_type: 'so:m',
post_logout_redirect_uri: this.settings.post_logout_redirect_uri,
...requestArgs
}, handle);

logger.info('success');
try {
await this._signout({
request_type: 'so:m',
post_logout_redirect_uri: this.settings.post_logout_redirect_uri,
...requestArgs
}, handle);

logger.info('success');
} catch (err) {
logger.error(err);
}
}

public async signinMobile(args: SigninMobileArgs = {}): Promise<void> {
Expand All @@ -93,16 +97,20 @@ export class OidcUserManager extends UserManager {

const handle = this._mobileNavigator.prepare(this.settings.redirect_uri, params);

const user = await this._signin({
request_type: 'si:m',
redirect_uri: this.settings.redirect_uri,
...requestArgs
}, handle);

if (user?.profile?.sub) {
logger.info('success, signed in subject', user.profile.sub);
} else {
logger.info('no subject');
try {
const user = await this._signin({
request_type: 'si:m',
redirect_uri: this.settings.redirect_uri,
...requestArgs
}, handle);

if (user?.profile?.sub) {
logger.info('success, signed in subject', user.profile.sub);
} else {
logger.info('no subject');
}
} catch (err) {
logger.error(err);
}
}
}

0 comments on commit b35bbc2

Please sign in to comment.