aboutsummaryrefslogtreecommitdiff
path: root/functions/render.js
blob: a35860a1375853798d50cf384814be8f6caf3d95 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const jwt = require("jsonwebtoken");
require("dotenv").config();
const validationString = process.env.AUTHORIZATION_STRING;
function renderRoute(req, res, page, title, protected = false, data = {}) {
  res.locals.messages = req.flash();
  let currentDomain = req.get("host").split(".");

  // get the ':scheme' from the request header
  let scheme = req.headers['X-Forwarded-Proto'] || req.protocol;
  currentDomain = scheme + "://" + currentDomain.at(-2) + "." + currentDomain.at(-1);
  jwt.verify(req.cookies.token, validationString, (err, decoded) => {
    if (err) {
      res.clearCookie("token");
      if (protected) {
        res.redirect("/");
      } else {
        res.render(page, {
          title: title,
          ...data,
          domain: currentDomain
        });
      }
    } else {
      res.render(page, {
        title: title,
        username: decoded.username,
        ...data,
        domain: currentDomain
      });
    }
  });
}

module.exports = {
  renderRoute,
};