const express = require("express") const jwt = require("jsonwebtoken") const config = require("../config") const { query } = require("../rpdata/client") const router = express.Router() router.post("/", (req, res) => { if (!req.header("Content-Type").startsWith("application/json")) { res.status(400).json({errors: [{message: "Incorrect input type, expected application/json"}]}) return } const user = res.locals.user const permissions = (req.header("X-Permissions") || "").split(",").filter(t => t != "" && t != "undefined" && t != "null") let authorization = req.header("Authorization") if (authorization == "null") { authorization = "" } if (!authorization && permissions.length > 0 && user.loggedIn) { authorization = `Bearer ${generateToken(user.name, permissions)}` } fetch(config.graphqlEndpoint, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": authorization, }, body: JSON.stringify(req.body), credentials: "include", }).then(fetchRes => { res.setHeader("Content-Type", fetchRes.headers.get("Content-Type")) res.status(fetchRes.status) return fetchRes.json() }).then(json => { res.json(json) }).catch(err => { res.status(500).text(err) return null }) }) /** * @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}}) } module.exports = router