Step 2
Let's refactor the app, so all endpoint tests pass!
First, update server/util/token.js
as follows:
- const createToken = (user) => {
+ const createToken = (user, expiration) => {
return jwt.sign(
{
sub: user._id,
username: user.username,
role: user.role,
},
process.env.JWT_SECRET,
{
algorithm: "HS256",
- expiresIn: "2d",
+ expiresIn: expiration ? expiration : "2d",
}
);
};
We allow an expiration parameter to exercise more control over the token creation process. This is particularly useful for endpoint testing to create expired tokens!
Next, update the /verify
route handler as follows:
router.post("/verify", async (req, res) => {
+ if (!req.body || !req.body.token) {
+ return res.status(400).json({
+ message: "You must provide a token in request's payload!",
+ });
+ }
const { token } = req.body;
const isValid = await verifyToken(token);
if (!isValid) {
return res.status(403).json({
message: "Invalid or expired token!",
});
}
return res.json({
message: "Token verified, and it is valid!",
token: token,
});
});
Save the changes and rerun the tests! They must all pass.