3. Protecting Routes Flashcards

(7 cards)

1
Q

How do you protect a route?

A

By verifying a user is truly logged in using a JWT (JSON Web Token) token offered to them when they login.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you write the instance method for checking if a user’s password was changed since their JWT token was issued?

A

userSchema.methods.changedPasswordAfter = async function(timeStamp) { if (this.passwordChangedAt && this.passwordChangedAt.getTime() / 1000 > timeStamp) { return true; } return false; }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you write the protect middleware?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you require the Node.js built-in promisify function?

A

const { promisify } = require(‘util’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the most important part of the protect middleware?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you convert a valid date into its value in seconds?

A

date.getTime() / 1000

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the HTTP code that means unauthorized resource or route?

A

401

How well did you know this?
1
Not at all
2
3
4
5
Perfectly