Basically, the server gives me a token
object. I am planning to check the token
on the client if it is expired/valid before making a request to the server.
The function below works as expected. I just want to know if my code catch-all edge cases? I don't want, even 1 second that will request will fail due to an expired access token.
I am using moment
for comparing dates. I also converted the current date and expiry date to UTC so that I'm making sure that they are in the same timezone before comparing them.
const moment = require('moment');
/**
The token object passed in the function looks like this:
{
access_token: '2hbssMdXDpwQX5WcnZ-iJlO754MLkEeDCmF-f1A-MaU',
token_type: 'Bearer',
expires_in: 604800,
refresh_token: 'VxnN9uBVIcNMpuwRVpvXo2YxWuNFEayHqfnCM7aCTSI',
scope: 'public',
created_at: 1603604241
}
*/
export default function tokenValid(token = {}) {
const currentDate = moment().utc();
const expiryDate = moment.unix(token.created_at).add(token.expires_in, 'seconds').utc();
return currentDate < expiryDate;
}
EDIT (based on @hjpotter92's comment)
export default function tokenValid(token = {}) {
const currentDate = moment().unix();
const expiryDate = token.created_at + token.expires_in;
return currentDate < expiryDate;
}