3. Protecting Routes Flashcards
(7 cards)
How do you protect a route?
By verifying a user is truly logged in using a JWT (JSON Web Token) token offered to them when they login.
How do you write the instance method for checking if a user’s password was changed since their JWT token was issued?
userSchema.methods.changedPasswordAfter = async function(timeStamp) { if (this.passwordChangedAt && this.passwordChangedAt.getTime() / 1000 > timeStamp) { return true; } return false; }
How do you write the protect middleware?
const protect = catchAsync(async (req, res, next) => { let token; if (req.headers.authorization && req.headers.authorization.startsWith(‘Bearer’)) { token = req.headers.authorization.split(‘ ‘)[1]; } if (!token) { return next(new AppError(‘You are not logged in. Please log in.’, 401)); } const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET); const user = await User.findById(decoded.id); if (!user) { return next(new AppError(‘The user for this token no longer exists in the database’, 401)); } if (await user.changedPasswordAfter(decoded.iat)) { return next(new AppError(‘Password was changed. Please log in again.’, 401)); } req.user = user; next(); });
How do you require the Node.js built-in promisify function?
const { promisify } = require(‘util’);
What is the most important part of the protect middleware?
Setting the req.user to the found user, this is so that the user object can be transferred between middlewares and used for other authorization purposes.
How do you convert a valid date into its value in seconds?
date.getTime() / 1000
What is the HTTP code that means unauthorized resource or route?
401