brainlet/api/v1/authfunctions.js

64 lines
No EOL
1.6 KiB
JavaScript
Executable file

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);
return;
}
jwt.verify(token, secret.jwtPrivateKey, {}, async (err, data) => {
if (err) {
redirect(res, 401, url);
return;
}
if (!data) {
redirect(res, 401, url);
return;
}
if (!data.username) {
redirect(res, 401, url);
return;
}
const user = await User.findByUsername(data.username);
if (!user) {
redirect(res, 401, url);
return;
}
let permissionLevel = config.roleMap[user.role];
if (!permissionLevel) {
permissionLevel = 0;
}
if (permissionLevel < minPermissionLevel) {
redirect(res, 401, url);
return;
}
callback(req, res, user);
});
};
}
module.exports = { authenticateEndpoint };