From aa9ce199b0421bc6c26c55c1e9fb852669efe58a Mon Sep 17 00:00:00 2001 From: Thomas Forgione Date: Tue, 26 Sep 2017 11:42:31 +0200 Subject: [PATCH] Added redirectIfNotLogged decorator. Fixes #5 --- controllers/auth/views.js | 19 ++++++++++++++++++- controllers/settings/views.js | 6 ++++-- controllers/total/views.js | 5 +++-- 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/controllers/auth/views.js b/controllers/auth/views.js index 019dfd0..f11afcb 100644 --- a/controllers/auth/views.js +++ b/controllers/auth/views.js @@ -5,6 +5,19 @@ const mail = require('mail'); const pug = require('pug'); const config = require('settings/config'); +module.exports.redirectIfNotLogged = function(redirectionPage, toDecorate) { + return function(req, res, render) { + if (req.session.user === undefined) { + req.session.redirectAfterLog = redirectionPage; + req.session.save(); + res.redirect(getUrl('login')); + return; + } + + return toDecorate(...arguments); + }; +} + module.exports.login = function(req, res, render) { render('login.pug'); } @@ -26,8 +39,12 @@ module.exports.loginTarget = function(req, res, render) { } else { if (testPassword(req.body.password, user.password)) { req.session.user = user; + + let redirection = req.session.redirectAfterLog || 'index'; + req.session.redirectAfterLog = undefined; req.session.save(); - res.redirect(getUrl('index')); + + res.redirect(getUrl(redirection)); } else { res.redirect(getUrl('login')); } diff --git a/controllers/settings/views.js b/controllers/settings/views.js index 0cf2392..6c34ab2 100644 --- a/controllers/settings/views.js +++ b/controllers/settings/views.js @@ -1,9 +1,11 @@ const getUrl = require('create-url').getUrl; const User = require('auth/models'); -module.exports.settings = function(req, res, render) { +const redirectIfNotLogged = require('auth/views').redirectIfNotLogged; + +module.exports.settings = redirectIfNotLogged('settings', function(req, res, render) { render('settings.pug'); -} +}); module.exports.settingsTarget = function(req, res, render) { let projectId = parseInt(req.body.projectId, 10); diff --git a/controllers/total/views.js b/controllers/total/views.js index d75f4bb..43087aa 100644 --- a/controllers/total/views.js +++ b/controllers/total/views.js @@ -1,4 +1,5 @@ const cal = require('calendar'); +const redirectIfNotLogged = require('auth/views').redirectIfNotLogged; function computeUserTable(user, callback) { @@ -33,9 +34,9 @@ function computeUserTable(user, callback) { }); } -module.exports.total = function(req, res, render) { +module.exports.total = redirectIfNotLogged('total', function(req, res, render) { render('total.pug'); -} +}); module.exports.totalTable = function(req, res, render) { computeUserTable(req.session.user, (result) => {