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.

71 lines
1.7 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. const config = require("../config")
  2. module.exports = (req, res, next) => {
  3. if (res.marko) {
  4. res.markoAsync = async(template, input) => {
  5. const locals = Object.assign({}, (res.locals || {}), input)
  6. try {
  7. for (const key in locals) {
  8. const value = locals[key]
  9. if (value instanceof Promise) {
  10. locals[key] = await value
  11. }
  12. }
  13. if (locals.user.permissions != null) {
  14. locals.user.permissions = await locals.user.permissions
  15. }
  16. } catch(err) {
  17. if (JSON.stringify(err) === "{}") {
  18. return next(err)
  19. }
  20. return res.status(404).json(err)
  21. }
  22. return res.marko(template, locals)
  23. }
  24. }
  25. if (req.user) {
  26. res.locals.user = {
  27. loggedIn: true,
  28. name: req.user._json.name,
  29. permissions: getPermissions(req.user._json.name),
  30. }
  31. } else {
  32. res.locals.user = {
  33. loggedIn: false,
  34. }
  35. }
  36. next()
  37. }
  38. function getPermissions(user) {
  39. return fetch(config.graphqlEndpoint, {
  40. method: "POST",
  41. headers: {
  42. "Content-Type": "application/json",
  43. "Authorization": `Bearer ${generateToken(user, ["member"])}`,
  44. },
  45. body: '{"query":"query { token { user { permissions } } }", "variables": {}}',
  46. credentials: "include",
  47. }).then(res => {
  48. return res.json()
  49. }).then(json => {
  50. return json.data.token.user.permissions
  51. }).catch(err => {
  52. console.error(err)
  53. return []
  54. })
  55. }
  56. const jwt = require("jsonwebtoken")
  57. /**
  58. * @param {string} user
  59. * @param {string[]} permissions
  60. */
  61. function generateToken(user, permissions) {
  62. return jwt.sign({user, permissions, exp: Math.floor((Date.now() / 1000) + 1200)}, config.backend.secret, {header: {kid: config.backend.kid}})
  63. }