I am working with oAuth2.0 package. Here a function "saveToken" generates and saves an access token every time user sends a post request with allowed credentials. But this function generates new access token and stores it each time user requests a token. I want to add a condition to check if the existing token is expired or not. if not then generate a new access token and save it. But I'm not understanding how this needs to be done.
Below function is modified and currently I am checking if there is a token for the user in DB. How can I make the token generation a function and call it inside the nested if?
I would be glad if someone helps me with this one.
var saveToken = function (token, client, user, callback) {
token.client = {
id: client.clientId,
};
token.user = {
username: user.username,
};
var tokenInstance = new tokenModel(token);
tokenModel
.findOne({
user: { username: token.user.username },
})
.lean()
.exec(
function (callback, err, token) {
if (!token) {
tokenInstance.save(
function (callback, err, token) {
token = token.toObject();
delete token._id;
delete token.__v;
callback(err, token);
}.bind(null, callback)
);
console.log("No token found!!! NEW TOKEN GERENATED");
} else {
let currentDate = new Date().getTime()
let tokenExpires = new Date(token.accessTokenExpiresAt).getTime();
let expiry = tokenExpires - currentDate
console.log("currentDate: ", currentDate);
console.log("tokenExpires: ", tokenExpires);
if (expiry < 0) {
console.log("token expired");
// ****** HERE I WANT TO REGENERATE ANOTHER TOKEN AND SAVE TO DB *******
}
else if(expiry > 0){
console.log("token Still alive");
}
}
callback(err, token);
}.bind(null, callback)
);
};
CodePudding user response:
I'm not sure I properly understand your use-case and question, but in else
block you already have existing token and still can use TokenModel
inside.
What you can do is to remove existing token by ID and after that create a new one with TokenInstance
properties you constructed at the beginning. Example:
if (expiry < 0) {
console.log("token expired");
TokenModel.deleteOne({id: token.id}).exec() // handle deletion
TokenInstance.save() // save new one here
}
Please keep in mind that it's pseudo-code and you should adjust it to your needs which means probably doing TokenInstance.save
in deleteOne
exec when it's succesfull, but you should be able to handle that.
Is that answer enough? Or maybe did I understand your question in a wrong way?