2021-03-04 21:28:02 +02:00
|
|
|
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);
|
|
|
|
};
|
|
|
|
|
2021-03-17 03:01:11 +02:00
|
|
|
const checkToken = (token, minPermissionLevel=config.roleMap.RESTRICTED) => {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
if (!token) reject("no token provided");
|
2021-03-04 21:28:02 +02:00
|
|
|
jwt.verify(token, secret.jwtPrivateKey, {}, async (err, data) => {
|
2021-03-17 03:01:11 +02:00
|
|
|
if (err) return reject(err);
|
|
|
|
if (!data || !data.username) return reject("invalid token");
|
2021-03-04 21:28:02 +02:00
|
|
|
const user = await User.findByUsername(data.username);
|
2021-03-17 03:01:11 +02:00
|
|
|
if (!user) return reject("user does not exist");
|
2021-03-04 21:28:02 +02:00
|
|
|
|
|
|
|
let permissionLevel = config.roleMap[user.role];
|
2021-03-17 03:01:11 +02:00
|
|
|
if (!permissionLevel) permissionLevel = 0;
|
2021-03-04 21:28:02 +02:00
|
|
|
|
2021-03-17 03:01:11 +02:00
|
|
|
if (permissionLevel < minPermissionLevel) reject("user does not have the required permission level");
|
|
|
|
resolve(user);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
function authenticateEndpoint(callback, url=undefined, minPermissionLevel=config.roleMap.RESTRICTED) {
|
|
|
|
return (req, res) => {
|
2021-03-27 07:19:11 +02:00
|
|
|
const token = req.headers.authorization || req.cookies.token;
|
2021-03-17 03:01:11 +02:00
|
|
|
if (!token) return redirect(res, 403, url);
|
|
|
|
checkToken(token, minPermissionLevel).then((user) => {
|
|
|
|
if (!user) return redirect(res, 403, url);
|
2021-03-04 21:28:02 +02:00
|
|
|
callback(req, res, user);
|
2021-03-17 03:01:11 +02:00
|
|
|
}).catch(() => {
|
|
|
|
return redirect(res, 403, url);
|
2021-03-04 21:28:02 +02:00
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2021-03-17 03:01:11 +02:00
|
|
|
module.exports = { authenticateEndpoint, checkToken };
|