Skip to content

Commit 0031090

Browse files
authored
Merge pull request #242 from Achintha444/master
(improvement) Improve the `isAuthenticated()` check `expires_in` validation
2 parents a666dcf + f7e5c09 commit 0031090

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

lib/src/core/authentication-core.ts

+31-1
Original file line numberDiff line numberDiff line change
@@ -588,8 +588,38 @@ export class AuthenticationCore<T> {
588588
return (await this._dataLayer.getSessionData(userID))?.access_token;
589589
}
590590

591+
/**
592+
* The created timestamp of the token response in milliseconds.
593+
*
594+
* @param userID - User ID
595+
* @returns Created at timestamp of the token response in milliseconds.
596+
*/
597+
public async getCreatedAt(userID?: string): Promise<number> {
598+
return (await this._dataLayer.getSessionData(userID))?.created_at;
599+
}
600+
601+
/**
602+
* The expires timestamp of the token response in seconds.
603+
*
604+
* @param userID - User ID
605+
* @returns Expires in timestamp of the token response in seconds.
606+
*/
607+
public async getExpiresIn(userID?: string): Promise<string> {
608+
return (await this._dataLayer.getSessionData(userID))?.expires_in;
609+
}
610+
591611
public async isAuthenticated(userID?: string): Promise<boolean> {
592-
const isAuthenticated: boolean = Boolean(await this.getAccessToken(userID));
612+
const isAccessTokenAvailable: boolean = Boolean(await this.getAccessToken(userID));
613+
614+
// Check if the access token is expired.
615+
const createdAt: number = await this.getCreatedAt(userID);
616+
617+
// Convert to milliseconds.
618+
const expiresIn: number = parseInt(await this.getExpiresIn(userID)) * 1000;
619+
const currentTime: number = new Date().getTime();
620+
const isAccessTokenValid: boolean = (createdAt + expiresIn) > currentTime;
621+
622+
const isAuthenticated: boolean = isAccessTokenAvailable && isAccessTokenValid;
593623

594624
return isAuthenticated;
595625
}

0 commit comments

Comments
 (0)