Passport login and persisting session

前端 未结 5 1059
悲哀的现实
悲哀的现实 2020-12-22 22:11

Background

I have a MEAN application with CRUD capabilities fully tested with postman. I have been trying to persist login for quite some time now with no luck. I

5条回答
  •  生来不讨喜
    2020-12-22 22:18

    As per the passport documentation, req.user will be set to the authenticated user. In order for this to work though, you will need the express-session module. You shouldn't need anything else beyond what you already have for passport to work.

    As far as testing the session, you can have a middleware function that checks if req.user is set, if it is, we know the user is authenticated, and if it isn't, you can redirect the user.

    You could for example have a middleware function that you can use on any routes you want authenticated.

    authenticated.js

    module.exports = function (req, res, next) {
        // if user is authenticated in the session, carry on
        if (req.user) {
            next();
        }
        // if they aren't redirect them to the login page
        else {
            res.redirect('/login');
        }
    };
    

    controller

    var authenticated = require('./authenticated');
    
    router.get('/protectedpage', authenticated, function(req, res, next) {
        //Do something here
    });
    

提交回复
热议问题