Skip to content

Instantly share code, notes, and snippets.

@dapperAuteur
Created March 19, 2018 02:43
Show Gist options
  • Save dapperAuteur/627772dc71c470257c6da63003a271c7 to your computer and use it in GitHub Desktop.
Save dapperAuteur/627772dc71c470257c6da63003a271c7 to your computer and use it in GitHub Desktop.
require('dotenv').load()
var jwt = require("jsonwebtoken")
exports.loginRequired = function (req, res, next) {
try {
var token = req.headers.authorization.split(" ")[1]
jwt.verify(token, process.env.SECRET_KEY, function (err, decoded) {
if (decoded) {
next();
} else {
res.status(401).json({ message: "Please log in first" })
}
});
} catch (e) {
res.status(401).json({ message: "Please log in first" })
}
}
exports.ensureCorrectUser = function (req, res, next) {
try {
var token = req.headers.authorization.split(" ")[1]
jwt.verify(token, process.env.SECRET_KEY, function (err, decoded) {
if (decoded && decoded.userId === req.params.id) {
next();
} else {
res.status(401).json({ message: "You do NOT have the proper credentials for this action." })
}
});
} catch (e) {
res.status(401).json({ message: "Unauthorized" })
}
}
exports.ensureCorrectRole = function (req, res, next) {
try {
var token = req.headers.authorization.split(" ")[1]
jwt.verify(token, process.env.SECRET_KEY, function (err, decoded) {
if (decoded && decoded.userRole === 0) {
console.log(0);
next();
} else {
res.status(401).json({ message: "You do NOT have the proper credentials for this action." })
}
})
} catch (e) {
res.status(401).json({ message: "Unauthorized" })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment