Переглянути джерело

Add middleware for checking for a logged in user.
Add session to the merchant model.

Lee Morgan 5 роки тому
батько
коміт
2bb3dfe326
3 змінених файлів з 40 додано та 5 видалено
  1. 35 5
      app.js
  2. 1 0
      controllers/renderer.js
  3. 4 0
      models/merchant.js

+ 35 - 5
app.js

@@ -4,6 +4,10 @@ const mongoose = require("mongoose");
 const compression = require("compression");
 const https = require("https");
 const fs = require("fs");
+const Merchant = require("./models/merchant.js");
+const helper = require("./controllers/helper.js");
+
+let protectedRoutes = [];
 
 const app = express();
 
@@ -28,18 +32,44 @@ if(process.env.NODE_ENV === "production"){
     });
 }
 
-app.use((req, res, next)=>{
-    console.log(req.session);
-    next();
-});
 app.use(compression());
 app.use(session({
-    secret: "Super Secret Subline Subliminally Saving Secrets So Sneaky Snakes Stay Sullen",
+    secret: "Super Secret Subline Subliminally Saving Secrets So Sneaky Snakes Stay Sullen. Simply Superb.",
     cookie: {secure: true},
     saveUninitialized: true,
     resave: false
 }));
+app.use((req, res, next)=>{
+    if(protectedRoutes.includes(req.url)){
+        if(req.session.user === undefined) return res.redirect("/");
 
+        Merchant.findOne({"session.sessionId": req.session.user})
+            .then((merchant)=>{
+                if(merchant === null){
+                    throw "no merchant";
+                }
+
+                if(merchant.session.date < new Date()){
+                    let newExpiration = new Date();
+                    newExpiration.setDate(newExpiration.getDate() + 90);
+
+                    merchant.session.sessionId = helper.generateId(25);
+                    merchant.session.date = newExpiration;
+                    merchant.save();
+                    return res.redirect("/");
+                }
+
+                res.locals.merchant = merchant;
+                return next();
+            })
+            .catch((err)=>{
+                if(err === "no merchant"){
+                    return res.redirect("PLEASE LOG IN");
+                }
+                return res.json("ERROR: UNABLE TO RETRIEVE DATA");
+            });
+    }
+});
 app.use(express.urlencoded({extended: true}));
 app.use(express.json());
 

+ 1 - 0
controllers/renderer.js

@@ -13,6 +13,7 @@ module.exports = {
     Renders landingPage
     */
     landingPage: function(req, res){
+        console.log(res.locals.otherData);
         new Activity({
             ipAddr: req.headers['x-forwarded-for'] || req.connection.remoteAddress,
             merchant: req.session.user,

+ 4 - 0
models/merchant.js

@@ -62,6 +62,10 @@ const MerchantSchema = new mongoose.Schema({
         type: mongoose.Schema.Types.ObjectId,
         ref: "Recipe"
     }],
+    session: {
+        sessionId: String,
+        expiration: Date
+    },
     verifyId: String
 });