使用多个LocalStrategy PassportJs / ExpressJs进行序列化/反序列化

时间:2015-04-25 10:51:31

标签: node.js express passport.js

我从PassportJs / ExpressJs应用程序开始进行身份验证  我有两种不同的用户和管理员模型  这是passport.js代码

passport.use('admin', new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password'
  },
  function(email, password, done) {
    var adminflag = 'admin';
    console.log('---------------------in admin')

    db.adminUser.find({ where: { email: email }}).success(function(user) {
      if (!user) {
        done(null, false, { message: 'Unknown user' });
      } else if (!user.authenticate(password)) {
        done(null, false, { message: 'Invalid password'});
      } else {
        console.log('Login (local) : { id: ' + user.id + ', username: ' + user.username + ' }');
        done(null, user);
      }
    }).error(function(err){
      done(err);
    });
  }
));

用户的LocalStrategy

passport.use('user', new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password'
  },
  function(email, password, done) {
    console.log('---------------------in user')
    var userflag = 'user';
    db.User.find({ where: { email: email }}).success(function(admin) {
      if (!admin) {
        done(null, false, { message: 'Unknown user' });
      } else if (!admin.authenticate(password)) {
        done(null, false, { message: 'Invalid password'});
      } else {
        console.log('Login (local) : { id: ' + admin.id + ', username: ' + admin.username + ' }');
        done(null, admin);
      }
    }).error(function(err){
      done(err);
    });
  }
));

所以我的问题是如何为admin和user编写serializeUser / deserializeUser

passport.serializeUser(function(admin, done) {
    if (admin.isSuperAdmin == 0 || admin.isSuperAdmin == 1 ) {
        flag = true;
           done(null, admin.id);       
           console.log('----------------------ADMIN');
    }else{
        flag = false;
        console.log('------------------USER');
        done(null, admin.id);       
    }; 
});

passport.deserializeUser(function(id ,done) {
        db.User.find({where: {id: id}}).success(function(admin){
        console.log('Session: { id: ' + user.id + ', username: ' + user.username + ' }');
            done(null, admin);
        }).error(function(err){
            done(err, null);
        });        
});

1 个答案:

答案 0 :(得分:3)

serializeUser isn't limited to just scalar values, so you can serialize an object that contains the type (admin or plain user):

passport.serializeUser(function(user, done) {
  var isAdmin = user.isSuperAdmin === 0 || user.isSuperAdmin === 1;
  return done(null, { id : user.id, isAdmin : isAdmin };    
});

In your deserialize function, you can check for that type:

passport.deserializeUser(function(user, done) {
  var collection = user.isAdmin ? db.adminUser : db.User;
  collection.find({ id : user.id }, ...);
});

However, if possible I would consider merging those two collections into one User collection and use a flag to signify if a user is admin or not.