Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the protect middleware #6

Merged
merged 1 commit into from
Nov 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion src/services/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,36 @@ const createSendToken = (data, status, message, res) => {
});
};

const protect = asyncHandler(async (req, res, next) => {
// get token and check if it is there
let token;

if (
req.headers.authorization
&& req.headers.authorization.startsWith('Bearer')
) {
token = req.headers.authorization.split(' ')[1];
}

if (!token) {
return res.json({ message: 'You are not logged in! Please login to get access' });
}

// validate signToken or verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);

/* check if user still exist (important! especially if the user has been deleted after jwt has been issued) */
const currentUser = await User.findById(decoded.id);
if (!currentUser) {
return res.json({ message: 'The user that this token belongs to no longer exists' });
}

// Grant access to protected route
req.user = currentUser;
next();
});

module.exports = {
createSendToken
createSendToken,
protect,
}
5 changes: 3 additions & 2 deletions src/services/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const {createSendToken} = require("./auth")
const {createSendToken, protect} = require("./auth")


module.exports = {
createSendToken
createSendToken,
protect
}