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

(improvement) Improve the isAuthenticated() check expires_in validation #242

Merged
merged 2 commits into from
Dec 11, 2023
Merged
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
32 changes: 31 additions & 1 deletion lib/src/core/authentication-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -588,8 +588,38 @@ export class AuthenticationCore<T> {
return (await this._dataLayer.getSessionData(userID))?.access_token;
}

/**
* The created timestamp of the token response in milliseconds.
*
* @param userID - User ID
* @returns Created at timestamp of the token response in milliseconds.
*/
public async getCreatedAt(userID?: string): Promise<number> {
return (await this._dataLayer.getSessionData(userID))?.created_at;
}

/**
* The expires timestamp of the token response in seconds.
*
* @param userID - User ID
* @returns Expires in timestamp of the token response in seconds.
*/
public async getExpiresIn(userID?: string): Promise<string> {
return (await this._dataLayer.getSessionData(userID))?.expires_in;
}

public async isAuthenticated(userID?: string): Promise<boolean> {
const isAuthenticated: boolean = Boolean(await this.getAccessToken(userID));
const isAccessTokenAvailable: boolean = Boolean(await this.getAccessToken(userID));

// Check if the access token is expired.
const createdAt: number = await this.getCreatedAt(userID);

// Convert to milliseconds.
const expiresIn: number = parseInt(await this.getExpiresIn(userID)) * 1000;
const currentTime: number = new Date().getTime();
const isAccessTokenValid: boolean = (createdAt + expiresIn) > currentTime;

const isAuthenticated: boolean = isAccessTokenAvailable && isAccessTokenValid;

return isAuthenticated;
}
Expand Down
Loading