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

fix(synchronizer): allow to clear user data on origin conflict #573

Merged
merged 2 commits into from
Nov 23, 2023
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
5 changes: 5 additions & 0 deletions .changeset/three-crews-applaud.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@monokle/synchronizer": patch
---

Clear auth user data on origin conflict by default
23 changes: 20 additions & 3 deletions packages/synchronizer/src/utils/authenticator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ export type AuthenticatorLoginEvent = {
user: User;
};

export type RefreshTokenOptions = {
logoutOnInvalidGrant?: boolean;
logoutOnFail?: boolean;
};

export class Authenticator extends EventEmitter {
private _user: User;

Expand Down Expand Up @@ -72,7 +77,7 @@ export class Authenticator extends EventEmitter {
}
}

async refreshToken(force = false) {
async refreshToken(force = false, options: RefreshTokenOptions = { logoutOnInvalidGrant: true }) {
const authData = this._user.data?.auth;
const tokenData = authData?.token;

Expand All @@ -93,8 +98,20 @@ export class Authenticator extends EventEmitter {
const expiresAtDateMs = new Date(tokenSetData.expires_at * 1000);
const diffMinutes = (expiresAtDateMs.getTime() - new Date().getTime()) / 1000 / 60;
if (diffMinutes < 5 || force) {
const newTokenData = await this._deviceFlowHandler.refreshAuthFlow(tokenSetData.refresh_token);
return this.setUserData(newTokenData);
try {
const newTokenData = await this._deviceFlowHandler.refreshAuthFlow(tokenSetData.refresh_token);
return this.setUserData(newTokenData);
} catch (err: any) {
// This is a workaround for origin conflict where user is logged in already with different origin
// and authenticator is querying different one.
if (options?.logoutOnFail || options?.logoutOnInvalidGrant && err.message.toLowerCase().includes('invalid_grant')) {
await this._storageHandler.emptyStoreData();
this._user = new User(null);
// Do not emit logout event since we treat this as user not being logged in with desired origin.
} else {
throw err;
}
}
}
}

Expand Down
Loading