I saw the following code:
const User = require('../model/User');
const jwt = require('jsonwebtoken');
const handleRefreshToken = async (req, res) => {
const cookies = req.cookies;
if (!cookies?.jwt) return res.sendStatus(401);
const refreshToken = cookies.jwt;
const foundUser = await User.findOne({ refreshToken }).exec();
if (!foundUser) return res.sendStatus(403); //Forbidden
// evaluate jwt
jwt.verify(
refreshToken,
process.env.REFRESH_TOKEN_SECRET,
(err, decoded) => {
if (err || foundUser.username !== decoded.username) return res.sendStatus(403);
const roles = Object.values(foundUser.roles);
const accessToken = jwt.sign(
{
"UserInfo": {
"username": decoded.username,
"roles": roles
}
},
process.env.ACCESS_TOKEN_SECRET,
{ expiresIn: '10s' }
);
res.json({ roles, accessToken })
}
);
}
module.exports = { handleRefreshToken }
And I can not understand what is the Object
in this line of code:
const roles = Object.values(foundUser.roles);
I mean is it instance of a class? What class? Where did it instantiated?
What does this Object
refer to?
CodePudding user response:
It's Global Object Class.
The Object class represents one of JavaScript's data types.
It is used to store various keyed collections and more complex entities. etc...
You can read Doc.
In your case.
const roles = Object.values(foundUser.roles);
this Object.values()
method'll return all values of your user.roles
Example
const users = { roles: { key1: 'value1', key2: 'value2' } };
console.log(Object.values(users.roles));
// Return array [ value1, value2 ]
// Another Keys Example
console.log(Object.keys(users.roles));
// Return array [ key1, key2 ]
CodePudding user response:
An object in Node.JS is anything that's within curly brackets, JSON basically. And if you actually read into it everything in Node.JS is actually an object, but that's off topic.
What that line of code is doing is it is finding the foundUser, and getting all of the values under the 'roles' category, so I would assume it would be sending back all of the roles the found user has.
if you want to research more, or if I wasn't clear enough check out this page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object