简单的login页面在nodejs中使用快速和护照与mongodb

我在/ login中使用Jade和Express创build了一个简单的login表单,表单数据通过POST发送到/ login

起初它只是基于string的匹配(如果用户名== &&密码==)然后redirect到/ home或redirect到/login

简单。

现在我想把它的数据库驱动程序,用户名和密码存储在一个mongodb数据库,从数据库匹配用户名密码,并进行诉讼。

我希望为此使用passportJS,但是我完全感到震惊,从创build数据库到configuration护照。

有人可以帮助我如何做一个简单的数据库驱动的login页面? 我很新的nodejs的东西。 任何帮助将认真感激

       

网上收集的解决方案 "简单的login页面在nodejs中使用快速和护照与mongodb"

以下是使用护照login/注销用户的简单设置:

在主app.js文件

/* Auth config --------------------------------*/ // @see http://frederiknakstad.com/authentication-in-single-page-applications-with-angular-js/ var passport = require('passport'); var User = require('./app/models/User'), passport.use(User.localStrategy); passport.serializeUser(User.serializeUser); passport.deserializeUser(User.deserializeUser); // Default session handling. Won't explain it as there are a lot of resources out there app.use(express.session({ secret: "mylittlesecret", cookie: {maxAge: new Date(Date.now() + 3600000)}, // 1 hour maxAge: new Date(Date.now() + 3600000), // 1 hour store: new RedisStore(config.database.redis), // You can not use Redis })); // The important part. Must go AFTER the express session is initialized app.use(passport.initialize()); app.use(passport.session()); // Set up your express routes 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); 

在你的用户模型(ej。app / models / User.js)

我正在使用护照本地模块,这进一步简化了login逻辑: https : //github.com/jaredhanson/passport-local

 /* Your normal user model ----------------------*/ 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} }); /* Auth properties ---------------------------*/ /* (passport) ---------------------------*/ // This is your main login logic schema.statics.localStrategy = new PassportLocalStrategy({ usernameField: 'email', passwordField: 'password', }, // @see https://github.com/jaredhanson/passport-local 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.'} ); } // I'm specifying the fields that I want to save into the user's session // *I don't want to save the password in the session 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; 

在应用程序/控制器/ authController.js

我正在使用单页面应用程序,所以我在login/注销时返回JSON。 如果你想redirect到其他地方,你将不得不修改“login成功”和“login失败”function(或调用res.render(…)或其他)。

 var passport = require('passport'); var AuthController = { // Login a user login: passport.authenticate('local', { successRedirect: '/auth/login/success', failureRedirect: '/auth/login/failure' }), // on Login Success callback loginSuccess: function(req, res){ res.json({ success: true, user: req.session.passport.user }); }, // on Login Failure callback loginFailure: function(req, res){ res.json({ success:false, message: 'Invalid username or password.' }); }, // Log out a user logout: function(req, res){ req.logout(); res.end(); }, }; exports = module.exports = AuthController; 

最后,您应该将您的login表单(需要设置method="post"属性)指向/ auth / login。 login成功时,将执行“loginSuccess”callback。 login失败时,将执行“loginFailure”callback。

编辑:

你可以在你的mongo数据库中创build新用户,执行如下所示:

 // On your main app.js file app.post('/auth/register', auth.register); // On your authController.js file, as per the previous example var User = require('./app/models/User'); // The model we defined in the previous example ... 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); ... // Your register error logic here res.redirect('/* Your error redirection path */'); return; } res.redirect('/* Your success redirection path */'); }); }, ... 

然后,将registry单指向/ auth / register。 我没有validation数据,但是您应该在尝试保存用户之前进行validation。