nodejs中使用express和passport以及mongodb的简单登录页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19024878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple login page in nodejs using express and passport with mongodb
提问by Anathema.Imbued
I created a simple login form in using Jade and Express at /login the form data is sent via POST to /login
我在 /login 处使用 Jade 和 Express 创建了一个简单的登录表单,表单数据通过 POST 发送到 /login
At first It was just string based matching ( if username== && password== ) then redirect to /home or redirect to /login
起初它只是基于字符串的匹配(如果 username== && password== )然后重定向到 /home 或重定向到 /login
Simple.
简单的。
Now I want to make it database driver, username and password to be stored on a mongodb database, match username password from db and do the proceedings.
现在我想将数据库驱动程序,用户名和密码存储在mongodb数据库中,从db匹配用户名密码并进行程序。
I wish to use passportJS for this, but I'm totally struck at it, from creating database to configuring passport.
我希望为此使用passportJS,但我对它感到非常震惊,从创建数据库到配置passport。
Can someone just help me how to make a simple database driven login page ? I'm very new to nodejs stuff. Any help would be seriously appreciated
有人可以帮我制作一个简单的数据库驱动登录页面吗?我对 nodejs 的东西很陌生。任何帮助将不胜感激
回答by David Oliveros
Here is a simple setup using passport to login / logout the users:
这是使用通行证登录/注销用户的简单设置:
On the main app.js file
在主 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);
On your user model (ej. app/models/User.js)
在您的用户模型上 (ej.app/models/User.js)
I'm using the passport-local module, which further simplifies the login logic: https://github.com/jaredhanson/passport-local
我使用的是passport-local模块,进一步简化了登录逻辑: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;
On app/controllers/authController.js
在 app/controllers/authController.js 上
I'm using a single-page application, so I'm returning JSON on login / logout. If you wish to redirect to somewhere else, you will have to modify the "login success" and "login failure" functions (or call res.render(...) or whatever).
我使用的是单页应用程序,所以我在登录/注销时返回 JSON。如果您希望重定向到其他地方,则必须修改“登录成功”和“登录失败”函数(或调用 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;
Lastly, you should point your login form (which needs to have the method="post"attribute set) to /auth/login. On login success, the "loginSuccess" callback will be executed. On login failure, the "loginFailure" callback will be executed.
最后,您应该将登录表单(需要method="post"设置属性)指向 /auth/login。登录成功后,将执行“loginSuccess”回调。登录失败时,将执行“loginFailure”回调。
Edit:
编辑:
You can create new users in your mongo database by executing something like:
您可以通过执行以下操作在 mongo 数据库中创建新用户:
// 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 */');
});
},
...
Then, point a registration form to /auth/register. I didn't validated the data, but you should validate it before trying to save the user.
然后,将注册表单指向 /auth/register。我没有验证数据,但您应该在尝试保存用户之前验证它。

