
const User = require("./sequelize.js").User;

var loadUsers = module.exports.loadUser = function(req) {
  return new Promise((res, rej) => {
    if (req.user !== undefined) {
      res(req.user);
      return;
    }
    if (req.session && req.session.userId) {
        User.findOne({ where: { id: req.session.userId }}).then(user => {
          res(req.user = user);
        });
    } else {
      res(req.user = null);
    }
  });
}

var generate = module.exports.generate = function(req) {
  return new Promise((res, rej) => {
    loadUsers(req).then((user) => {
      var args = {
        title: "Totoro Book",
      };
      if (user) {
        args.user = user;
        args.username = user.username;
      }
      res(args);
    });
  });
}

module.exports.needLogin = function(req, res) {
  return new Promise((success, reject) => {
    loadUsers(req).then((user) => {
      if (!user) {
        res.locals.message = "Access Denied";
        res.locals.error = {};

        // render the error page
        generate(req).then(args => {
          res.status(403);
          res.render('error', args);
        });
      } else {
        success();
      }
    });
  });
}

