Support for multiple user types by Passport-local mongoose node.js

前端 未结 3 2016
一个人的身影
一个人的身影 2020-12-29 16:48

I wanted two types of users logging in (User, Client). How exactly can I create localStrategies, serialize and deserialize user for both types in my app.js I have two separa

相关标签:
3条回答
  • 2020-12-29 17:32

    You can make role in mongoose schema and give it to user or client. Based on the role you can do the authentication

    0 讨论(0)
  • 2020-12-29 17:55

    After going through the documentation of passport.js (kudos to Jared), I understood that I was doing almost everything wrong.

    1. Created two localStrategies

      passport.use('userLocal', new LocalStrategy(User.authenticate())); passport.use('clientLocal', new LocalStrategy(Client.authenticate()));

    and to authenticate,

    passport.authenticate('userLocal')(req, res, function () {
        res.redirect('/profile');
      });
    and
    passport.authenticate('clientLocal')(req, res, function () {
        res.redirect('/client');
      });
    
    1. Used passport module (l=not using the passport-local-mongoose module) for serializeUser and deseriealizeUser.

      passport.serializeUser(function(user, done) { done(null, user); });

      passport.deserializeUser(function(user, done) { if(user!=null) done(null,user); });

    The whole user schema (object) is now stored in the request and can be accessed through any of your routes.

    Hope it helps out others with a similar issue.

    0 讨论(0)
  • 2020-12-29 17:55

    you need to create two strategy and edit your serialize and deserialize function for support multiple formats When you call authenticate() you can specify startegy name

    for example In middleware

    exports.authenticateUserA = function (req, res, next) {
        console.log('authenticateA', req.body.hostname)
        passport.authenticate('loginA', {failureRedirect: '/login-fail',successRedirect: "/home"}, function (err, player, info) {}})
    

    In passport-config.js

      passport.serializeUser(function (user, done) {
         console.log('deserialize user ')
         if (typeof user.mac_address == 'undefined') {
    
          user.data_type = 'userTypeA'
          done(null, user);
         } else{
            user.data_type = 'userTypeB'
            done(null, user);
        }
    
        });
    
    0 讨论(0)
提交回复
热议问题