bridgecord/tokens.js

51 lines
1.5 KiB
JavaScript
Raw Normal View History

import jsonwebtoken from "jsonwebtoken";
import { jwtSecret } from "./config.js";
export function createToken({ username, avatarURL, discordID, guildAccess, isSuperToken=false }) {
return new Promise((resolve, reject) => {
jsonwebtoken.sign({ username, avatarURL, discordID, guildAccess, isSuperToken }, jwtSecret, (err, token) => {
if (err)
return reject(err);
resolve(token);
});
});
}
export function decodeToken(token) {
return new Promise((resolve, reject) => {
jsonwebtoken.verify(token, jwtSecret, (err, token) => {
if (err)
return reject(err);
resolve(token);
});
});
}
export function checkAuth(callback) {
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;
}
};
}