|
|
const config = require("../config")
module.exports = (req, res, next) => { if (res.marko) { res.markoAsync = async(template, input) => { const locals = Object.assign({}, (res.locals || {}), input)
try { for (const key in locals) { const value = locals[key] if (value instanceof Promise) { locals[key] = await value } } if (locals.user.permissions != null) { locals.user.permissions = await locals.user.permissions } } catch(err) { if (JSON.stringify(err) === "{}") { return next(err) } return res.status(404).json(err) }
return res.marko(template, locals) } }
if (["/static/", "/hax/", "/assets/"].find(p => req.path.startsWith(p)) == null) { if (req.user) { res.locals.user = { loggedIn: true, name: req.user._json.name, permissions: getPermissions(req.user._json.name), } } else { res.locals.user = { loggedIn: false, } } }
next() }
function getPermissions(user) { return fetch(config.graphqlEndpoint, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${generateToken(user, ["member"])}`, }, body: '{"query":"query { token { user { permissions } } }", "variables": {}}', credentials: "include", }).then(res => { return res.json() }).then(json => { return json.data.token.user.permissions }).catch(err => { console.error(err) return [] }) }
const jwt = require("jsonwebtoken") /** * @param {string} user * @param {string[]} permissions */ function generateToken(user, permissions) { return jwt.sign({user, permissions, exp: Math.floor((Date.now() / 1000) + 1200)}, config.backend.secret, {header: {kid: config.backend.kid}}) }
|