From 0ae014549d47a7d556ffc8ddfb42e4c00903f5ed Mon Sep 17 00:00:00 2001 From: flifloo Date: Mon, 12 Oct 2020 23:34:51 +0200 Subject: [PATCH] Setup permissions check on index --- app.js | 6 +++--- routes/index.js | 4 ++-- routes/utils/error.js | 4 ++++ routes/utils/sessionCheck.js | 15 +++++++++++++++ 4 files changed, 24 insertions(+), 5 deletions(-) create mode 100644 routes/utils/error.js create mode 100644 routes/utils/sessionCheck.js diff --git a/app.js b/app.js index cfc8175..fd0d56e 100644 --- a/app.js +++ b/app.js @@ -1,10 +1,10 @@ -let createError = require("http-errors"); let express = require("express"); let path = require("path"); let cookieParser = require("cookie-parser"); let logger = require("morgan"); let sassMiddleware = require("node-sass-middleware"); const session = require("express-session"); +const error = require("./routes/utils/error"); let config = process.env.NODE_ENV === "test" ? {} : require("./config/config.json"); let indexRouter = require("./routes/index"); @@ -42,8 +42,8 @@ app.use("/", indexRouter); app.use("/login", loginRouter); // catch 404 and forward to error handler -app.use((req, res, next) => { - next(createError(404)); +app.use((req, res) => { + return error(req, res, "Page not found", 404); }); // error handler diff --git a/routes/index.js b/routes/index.js index 6b2b7df..b8592d3 100644 --- a/routes/index.js +++ b/routes/index.js @@ -1,8 +1,8 @@ let express = require("express"); let router = express.Router(); +const sessionCheck = require("./utils/sessionCheck"); -/* GET home page. */ -router.get("/", (req, res) => { +router.get("/", sessionCheck(1), (req, res) => { res.render("index", { title: "L'ETU" }); }); diff --git a/routes/utils/error.js b/routes/utils/error.js new file mode 100644 index 0000000..81799dc --- /dev/null +++ b/routes/utils/error.js @@ -0,0 +1,4 @@ +module.exports = (req, res, message, status, subMessage) => { + res.status(status || 500); + res.render("error", {message: message, error: {status: subMessage || undefined}}); +}; diff --git a/routes/utils/sessionCheck.js b/routes/utils/sessionCheck.js new file mode 100644 index 0000000..a85ad8f --- /dev/null +++ b/routes/utils/sessionCheck.js @@ -0,0 +1,15 @@ +let error = require("./error"); + +function sessionCheck(permission) { + return (req, res, next) => { + if (!req.session.user) { + req.session.lastUrl = req.originalUrl; + req.session.save(() => res.redirect("/login")); + } else if (req.session.user.permissions < permission) + return error(req, res, "Permission denied !", 403); + else + next(); + } +} + +module.exports = sessionCheck;