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.

73 lines
1.8 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 (["/static/", "/hax/", "/assets/"].find(p => req.path.startsWith(p)) == null) {
  26. if (req.user) {
  27. res.locals.user = {
  28. loggedIn: true,
  29. name: req.user._json.name,
  30. permissions: getPermissions(req.user._json.name),
  31. }
  32. } else {
  33. res.locals.user = {
  34. loggedIn: false,
  35. }
  36. }
  37. }
  38. next()
  39. }
  40. function getPermissions(user) {
  41. return fetch(config.graphqlEndpoint, {
  42. method: "POST",
  43. headers: {
  44. "Content-Type": "application/json",
  45. "Authorization": `Bearer ${generateToken(user, ["member"])}`,
  46. },
  47. body: '{"query":"query { token { user { permissions } } }", "variables": {}}',
  48. credentials: "include",
  49. }).then(res => {
  50. return res.json()
  51. }).then(json => {
  52. return json.data.token.user.permissions
  53. }).catch(err => {
  54. console.error(err)
  55. return []
  56. })
  57. }
  58. const jwt = require("jsonwebtoken")
  59. /**
  60. * @param {string} user
  61. * @param {string[]} permissions
  62. */
  63. function generateToken(user, permissions) {
  64. return jwt.sign({user, permissions, exp: Math.floor((Date.now() / 1000) + 1200)}, config.backend.secret, {header: {kid: config.backend.kid}})
  65. }