The frontend/UI server, written in JS using the MarkoJS library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.5 KiB

6 years ago
  1. const express = require("express")
  2. const jwt = require("jsonwebtoken")
  3. const config = require("../config")
  4. const { query } = require("../rpdata/client")
  5. const router = express.Router()
  6. router.post("/", (req, res) => {
  7. if (!req.header("Content-Type").startsWith("application/json")) {
  8. res.status(400).json({errors: [{message: "Incorrect input type, expected application/json"}]})
  9. return
  10. }
  11. const user = res.locals.user
  12. const permissions = (req.header("X-Permissions") || "").split(",").filter(t => t != "" && t != "undefined" && t != "null")
  13. let authorization = req.header("Authorization")
  14. if (authorization == "null") {
  15. authorization = ""
  16. }
  17. if (!authorization && permissions.length > 0 && user.loggedIn) {
  18. authorization = `Bearer ${generateToken(user.name, permissions)}`
  19. }
  20. fetch(config.graphqlEndpoint, {
  21. method: "POST",
  22. headers: {
  23. "Content-Type": "application/json",
  24. "Authorization": authorization,
  25. },
  26. body: JSON.stringify(req.body),
  27. credentials: "include",
  28. }).then(fetchRes => {
  29. res.setHeader("Content-Type", fetchRes.headers.get("Content-Type"))
  30. res.status(fetchRes.status)
  31. return fetchRes.json()
  32. }).then(json => {
  33. res.json(json)
  34. }).catch(err => {
  35. res.status(500).text(err)
  36. return null
  37. })
  38. })
  39. /**
  40. * @param {string} user
  41. * @param {string[]} permissions
  42. */
  43. function generateToken(user, permissions) {
  44. return jwt.sign({user, permissions, exp: Math.floor((Date.now() / 1000) + 1200)}, config.backend.secret, {header: {kid: config.backend.kid}})
  45. }
  46. module.exports = router