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.

57 lines
1.7 KiB

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