如何一起实现LocalStrategy和CustomStrategy?

时间:2016-10-13 15:58:20

标签: node.js mongodb express passport.js

我正在为在线测验创建一个应用程序。服务器端的技术堆栈是node,express,passport,mongo和mongoose。客户端是Angular。

在这个应用程序中,我需要创建两种身份验证和会话。对于管理员,我需要实现具有固定会话时间的LocalStrategy(用户名,密码)。对于候选人,CustomStrategy(emailID)具有单独的会话和到期时间。

我该如何实现?

1 个答案:

答案 0 :(得分:1)

我一起使用了CustomStrategy和LocalStrategy。

passport.use(new LocalStrategy({
    usernameField: 'email'
}, function(email, password, done) {
    User.findOne({
        email: email.toLowerCase()
    }, function(err, user) {
        if (!user) {
            return done(null, false, {
                msg: 'Email ' + email + ' not found.'
            });
        }
        user.comparePassword(password, function(err, isMatch) {
            if (isMatch) {
                return done(null, user);
            } else {
                return done(null, false, {
                    msg: 'Invalid email or password.'
                });
            }
        });
    });
}));



passport.use(new CustomStrategy(
    function(req, done) {
        Invite.findById(req.params.id, function(err, invite) {
            if (err) {
                console.log(err)
            }
            if (!invite) {
                return done(null, false, {
                    msg: 'Invite not found.'
                });
            }
            done(null, invite);
        });
    }
));