const User = require("../../models/User");
const secret = require("../../secret");
const config = require("../../config");
const jwt = require("jsonwebtoken");
const redirect = (res, status=401, url=undefined) => {
if (!url) {
res.status(status).json({
error: true,
message: "ERROR_ACCESS_DENIED"
});
return;
}
res.redirect(url);
};
function authenticateEndpoint(callback, url=undefined, minPermissionLevel=config.roleMap.RESTRICTED) {
return (req, res) => {
const token = req.cookies.token;
if (!token) {
redirect(res, 403, url);
jwt.verify(token, secret.jwtPrivateKey, {}, async (err, data) => {
if (err) {
redirect(res, 401, url);
if (!data) {
if (!data.username) {
const user = await User.findByUsername(data.username);
if (!user) {
let permissionLevel = config.roleMap[user.role];
if (!permissionLevel) {
permissionLevel = 0;
if (permissionLevel < minPermissionLevel) {
callback(req, res, user);
module.exports = { authenticateEndpoint };