This repository has been archived on 2022-05-17. You can view files and clone it, but cannot push or open issues or pull requests.
brainlet/api/v1/authfunctions.js

64 lines
1.6 KiB
JavaScript
Raw Normal View History

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);
});
};
}
2020-10-05 20:36:03 +03:00
module.exports = { authenticateEndpoint };