这里是使用passport进行用户登录/注销的简单设置示例:
在主要的 app.js 文件中
var passport = require('passport');
var User = require('./app/models/User'),
passport.use(User.localStrategy);
passport.serializeUser(User.serializeUser);
passport.deserializeUser(User.deserializeUser);
app.use(express.session({
secret: "mylittlesecret",
cookie: {maxAge: new Date(Date.now() + 3600000)},
maxAge: new Date(Date.now() + 3600000),
store: new RedisStore(config.database.redis),
}));
app.use(passport.initialize());
app.use(passport.session());
var auth = require('./app/controllers/authController.js');
app.post('/auth/login', auth.login);
app.post('/auth/logout', auth.logout);
app.get('/auth/login/success', auth.loginSuccess);
app.get('/auth/login/failure', auth.loginFailure);
在你的用户模型上(例如 app/models/User.js)
我正在使用 passport-local 模块,它进一步简化了登录逻辑:https://github.com/jaredhanson/passport-local
var mongoose = require('mongoose'),
ObjectId = mongoose.Schema.Types.ObjectId,
PassportLocalStrategy = require('passport-local').Strategy;
var schema = new mongoose.Schema({
name: {type:String, required:true, trim:true},
email: {type:String, required: true, trim: true, lowercase:true, unique: true},
image: {type:String},
password: {type:String, required: true },
created: {type: Date, default: Date.now}
});
schema.statics.localStrategy = new PassportLocalStrategy({
usernameField: 'email',
passwordField: 'password',
},
function (username, password, done){
var User = require('./User');
User.findOne({email: username}, function(err, user){
if (err) { return done(err); }
if (!user){
return done(null, false, { message: 'User not found.'} );
}
if (!user.validPassword(password)){
return done(null, false, { message: 'Incorrect password.'} );
}
return done(null, {
id: user._id,
name: user.name,
image: user.image,
email: user.email,
});
});
}
);
schema.methods.validPassword = function(password){
if (this.password == password){
return true;
}
return false;
}
schema.statics.serializeUser = function(user, done){
done(null, user);
};
schema.statics.deserializeUser = function(obj, done){
done(null, obj);
};
var model = mongoose.model('User', schema);
exports = module.exports = model;
在app/controllers/authController.js中
我正在使用单页面应用程序,因此在登录/注销时返回JSON。如果您想要重定向到其他地方,则必须修改“登录成功”和“登录失败”函数(或调用res.render(...)或其他函数)。
var passport = require('passport');
var AuthController = {
login: passport.authenticate('local', {
successRedirect: '/auth/login/success',
failureRedirect: '/auth/login/failure'
}),
loginSuccess: function(req, res){
res.json({
success: true,
user: req.session.passport.user
});
},
loginFailure: function(req, res){
res.json({
success:false,
message: 'Invalid username or password.'
});
},
logout: function(req, res){
req.logout();
res.end();
},
};
exports = module.exports = AuthController;
最后,你需要将登录表单(需要设置
method="post"
属性)指向/auth/login。登录成功时,“loginSuccess”回调将被执行。登录失败时,“loginFailure”回调将被执行。
编辑:
你可以通过执行以下类似的操作在mongo数据库中创建新用户:
app.post('/auth/register', auth.register);
var User = require('./app/models/User');
...
register: function(req, res){
User.create({name: req.body.name, email: req.body.email, password: req.body.password}, function(err){
if (err) {
console.log(err);
...
res.redirect('/* Your error redirection path */');
return;
}
res.redirect('/* Your success redirection path */');
});
},
...
接下来,将注册表单指向/auth/register。我没有对数据进行验证,但在尝试保存用户之前,您应该验证它。