handle expired token and return new token
This commit is contained in:
parent
82ee4f6e5b
commit
8c6eab23e5
|
@ -0,0 +1,7 @@
|
|||
|
||||
module.exports = async(token, accessTokenConfig) => {
|
||||
const now = new Date();
|
||||
const differenceMilliseconds = now - token.created;
|
||||
const differenceSeconds = Math.floor(differenceMilliseconds / 1000);
|
||||
return differenceSeconds > accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime;
|
||||
};
|
|
@ -1,5 +1,12 @@
|
|||
const UserError = require('vn-loopback/util/user-error');
|
||||
|
||||
const handlePromiseLogout = (Self, {id}, courtesyTime = 60) => {
|
||||
new Promise(res => {
|
||||
setTimeout(() => {
|
||||
res(Self.logout(id));
|
||||
}
|
||||
, courtesyTime * 1000);
|
||||
});
|
||||
};
|
||||
module.exports = Self => {
|
||||
Self.remoteMethodCtx('renewToken', {
|
||||
description: 'Checks if the token has more than renewPeriod seconds to live and if so, renews it',
|
||||
|
@ -19,17 +26,16 @@ module.exports = Self => {
|
|||
const models = Self.app.models;
|
||||
const token = ctx.req.accessToken;
|
||||
|
||||
const now = new Date();
|
||||
const differenceMilliseconds = now - token.created;
|
||||
const differenceSeconds = Math.floor(differenceMilliseconds / 1000);
|
||||
// Check if current token is valid
|
||||
const isValid = await Self.validateToken(token);
|
||||
if (!isValid) throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded');
|
||||
const fields = ['courtesyTime'];
|
||||
const {courtesyTime} = await models.AccessTokenConfig.findOne({fields});
|
||||
|
||||
const fields = ['renewPeriod', 'courtesyTime'];
|
||||
const accessTokenConfig = await models.AccessTokenConfig.findOne({fields});
|
||||
// Schedule to remove current token
|
||||
handlePromiseLogout(Self, token, courtesyTime);
|
||||
|
||||
if (differenceSeconds < accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime)
|
||||
throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded');
|
||||
|
||||
await Self.logout(token.id);
|
||||
// Create new accessToken
|
||||
const user = await Self.findById(token.userId);
|
||||
const accessToken = await user.createAccessToken();
|
||||
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
const isTokenValid = require('./is-token-valid');
|
||||
|
||||
module.exports = Self => {
|
||||
Self.remoteMethod('validateToken', {
|
||||
description: 'Validates the current logged user token',
|
||||
|
@ -11,7 +13,10 @@ module.exports = Self => {
|
|||
}
|
||||
});
|
||||
|
||||
Self.validateToken = async function() {
|
||||
return true;
|
||||
Self.validateToken = async function(token) {
|
||||
const fields = ['renewPeriod', 'courtesyTime'];
|
||||
const accessTokenConfig = await Self.app.models.AccessTokenConfig.findOne({fields});
|
||||
const isValid = await isTokenValid(token, accessTokenConfig);
|
||||
return isValid;
|
||||
};
|
||||
};
|
||||
|
|
Loading…
Reference in New Issue