简体   繁体   中英

Passport middleware for Node.js

I am using Passport authentication middleware for Node.js. I would like to use it from within my own objects (rather than inline in a route definition). The reason for this that the auth mechanism will change depending on application settings and I would like to maintain separation of concerns and testability.

An example of use from the documentation:

app.post('/session/create', 
  passport.authenticate('local', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

I would like something like this:

app.post('/session/create', sessionController.create);

...where session controller encapsulates the coordination of authentication via Passport.

Can someone help me structure my use of Passport in this way?

Here is an example I am using :

 // Bootstrap controllers
 var controllers_path = __dirname + '/controllers';
 fs.readdirSync(controllers_path).forEach(function(file) {
     if (~file.indexOf('.js')) {
        app.controllers[file.slice(0, - 3)] = require(controllers_path + '/' + file);
     }
  });

My router:

 app.server.post('/login', app.controllers.users.doLogin);

And my user controller :

exports.doLogin = function(req, res, next) {
        app.passport.authenticate('local', function(err, user, info) {
            if (err) {
                return next(err);
            }
            if (!user) {
                req.flash('error', 'Invalid username or password');
                return res.redirect('/login' + (req.body.target ? '?target=' + req.body.target : ''));
            }
            req.logIn(user, function(err) {
                if (err) {
                    return next(err);
                }
                return res.redirect(req.body.target || '/');
            });
        })(req, res, next);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM