SDK: Start auth refresh job when constructor is initialised (#9777)

* Refresh auth when SDK is initialised 

If autorefresh is enabled, then this will cause the SDK to refresh tokens whenever it's loaded. This fixes bug #9639 (discussion #9720)

* start autoRefreshJob on constructor and on refresh

* preserve refresh_token before clear it on refresh

Co-authored-by: Jose Varela <joselcvarela@gmail.com>
This commit is contained in:
Joe Innes
2021-11-22 17:11:09 +01:00
committed by GitHub
parent beed15c199
commit ff002443f0

View File

@@ -16,12 +16,13 @@ export class Auth extends IAuth {
private _storage: IStorage;
private _transport: ITransport;
private timer: ReturnType<typeof setTimeout> | false;
private timer: ReturnType<typeof setTimeout> | null;
private passwords?: PasswordsHandler;
constructor(options: AuthOptions) {
super();
this.timer = null;
this._transport = options.transport;
this._storage = options.storage;
@@ -32,9 +33,9 @@ export class Auth extends IAuth {
if (options?.staticToken) {
this.staticToken = options?.staticToken;
this.updateStorage<'StaticToken'>({ access_token: this.staticToken, expires: null, refresh_token: null });
} else if (this.autoRefresh) {
this.autoRefreshJob();
}
this.timer = false;
}
get storage(): IStorage {
@@ -53,6 +54,12 @@ export class Auth extends IAuth {
return (this.passwords = this.passwords || new PasswordsHandler(this._transport));
}
private resetStorage() {
this._storage.auth_token = null;
this._storage.auth_refresh_token = null;
this._storage.auth_expires = null;
}
private updateStorage<T extends AuthTokenType>(result: AuthStorage<T>) {
this._storage.auth_token = result.access_token;
this._storage.auth_refresh_token = result.refresh_token ?? null;
@@ -63,6 +70,8 @@ export class Auth extends IAuth {
if (!this.autoRefresh) return;
if (!this._storage.auth_expires) return;
if (this.timer) clearTimeout(this.timer);
const msWaitUntilRefresh = this._storage.auth_expires - this.msRefreshBeforeExpires;
this.timer = setTimeout(async () => {
@@ -75,12 +84,17 @@ export class Auth extends IAuth {
}
async refresh(): Promise<AuthResult | false> {
const refresh_token = this._storage.auth_refresh_token;
this.resetStorage();
const response = await this._transport.post<AuthResult>('/auth/refresh', {
refresh_token: this.mode === 'json' ? this._storage.auth_refresh_token : undefined,
refresh_token: this.mode === 'json' ? refresh_token : undefined,
});
this.updateStorage<'DynamicToken'>(response.data!);
if (this.autoRefresh) this.autoRefreshJob();
return {
access_token: response.data!.access_token,
refresh_token: response.data?.refresh_token,
@@ -89,6 +103,8 @@ export class Auth extends IAuth {
}
async login(credentials: AuthCredentials): Promise<AuthResult> {
this.resetStorage();
const response = await this._transport.post<AuthResult>(
'/auth/login',
{ mode: this.mode, ...credentials },