2022-02-02 11:46:42 +02:00
|
|
|
import jsonwebtoken from "jsonwebtoken";
|
|
|
|
import { jwtSecret } from "./config.js";
|
2022-02-01 03:49:12 +02:00
|
|
|
|
2022-02-10 01:15:39 +02:00
|
|
|
export function createToken({ username, avatarURL, discordID, guildAccess, isSuperToken=false }) {
|
2022-02-01 03:49:12 +02:00
|
|
|
return new Promise((resolve, reject) => {
|
2022-02-10 01:15:39 +02:00
|
|
|
jsonwebtoken.sign({ username, avatarURL, discordID, guildAccess, isSuperToken }, jwtSecret, (err, token) => {
|
2022-02-01 03:49:12 +02:00
|
|
|
if (err)
|
|
|
|
return reject(err);
|
|
|
|
|
|
|
|
resolve(token);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-02-02 11:46:42 +02:00
|
|
|
export function decodeToken(token) {
|
2022-02-01 03:49:12 +02:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
jsonwebtoken.verify(token, jwtSecret, (err, token) => {
|
|
|
|
if (err)
|
|
|
|
return reject(err);
|
|
|
|
|
|
|
|
resolve(token);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-02-02 11:46:42 +02:00
|
|
|
export function checkAuth(callback) {
|
2022-02-01 03:49:12 +02:00
|
|
|
return async (req, res) => {
|
|
|
|
const token = req.get("authorization");
|
|
|
|
if (token) {
|
|
|
|
let user;
|
|
|
|
try {
|
|
|
|
user = await decodeToken(token);
|
|
|
|
} catch(e) {
|
|
|
|
res.status(403).send({ error: true, message: "ERROR_FORBIDDEN" });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (user) {
|
|
|
|
req.user = user;
|
|
|
|
req.authenticated = true;
|
|
|
|
return await callback(req, res);
|
|
|
|
} else {
|
|
|
|
res.status(401).send({ error: true, message: "ERROR_UNAUTHORIZED" });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
res.status(401).send({ error: true, message: "ERROR_UNAUTHORIZED" });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|