const db = require('../lib/db');

module.exports = (req, res, next) => {
  if (!req.session.userId) {
    req.flash('error', 'Please sign in to continue.');
    return res.redirect(`/${req.params.lang || 'en'}/login`);
  }
  const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.session.userId);
  if (!user) {
    req.session.destroy(() => {});
    return res.redirect('/en/login');
  }
  req.user          = user;
  res.locals.user   = user;
  res.locals.flash  = { success: req.flash('success'), error: req.flash('error') };
  next();
};
