用mongoose + express.js认证用户 [英] authenticate user with mongoose + express.js
问题描述
使用Mongoose和ExpreeJS验证用户的最佳方式是什么。
What's the best way to authenticate a user with Mongoose and ExpreeJS.
我使用的是mongoose 3.x,看起来这个包没有被更新再次: https://github.com/bnoguchi/mongoose-auth
I'm using mongoose 3.x and it looks like this package isn't being updated anymore: https://github.com/bnoguchi/mongoose-auth
理想情况下,我可以通过twitter和Facebook验证用户。
Ideally I could authenticate user with twitter and facebook too.
推荐答案
我总是不喜欢为每个问题使用插件或模块。使用只是mongoose你可以这样做:
I always prefer not to use a plugin or module for every problem. Using just mongoose you could do it like this:
有一个db.js为您的mongoDB配置
Have a db.js for your mongoDB configuration
var mongoose = require('mongoose');
mongoose.connect("mongodb://...");
var userSchema = new mongoose.Schema({
username: String,
salt: String,
hash: String
});
exports.User = mongoose.model("user", userSchema);
使用TJ的 pass.js 文件到哈希密码。它使用 crypto.pbkdf2 进行加密。
Use TJ's pass.js file to hash passwords. It uses crypto.pbkdf2 for encryption.
手工创建用户或使用表单允许自行注册:
Create a user by hand or use a form to allow self registration:
var db = require('./db');
var pwd = require('./pwd');
var user = new db.User();
user.username = "Admin";
pwd.hash("adminPassword", function(err, salt, hash) {
if (err) {
console.log(err);
}
user.salt = salt;
user.hash = hash;
user.save(function(err) {
if (err) {
console.log(err);
} else {
console.log("user saved");
}
});
});
现在你应该有一个用户名,加密密码和哈希数据库。要检查登录是否使用中间件功能:
Now you should have a user with username, encrypted password and hash in your db. To check on login use a middleware function:
function authenticate(name, pass, fn) {
db.User.findOne ({username: name}, function(err, user) {
if (!user) return fn(new Error('cannot find user'));
hash(pass, user.salt, function(err, hash){
if (err) return fn(err);
if (hash == user.hash) return fn(null, user);
fn(new Error('invalid password'));
})
})
}
app.post('/login', function(req, res){
authenticate(req.body.username, req.body.password, function(err, user){
if (user) {
req.session.regenerate(function(){
req.session.user = user;
res.redirect('back');
});
} else {
res.redirect('login');
}
});
});
// middleware
function restrict(req, res, next) {
if (req.session.user) {
next();
} else {
req.session.error = 'Access denied!';
res.redirect('/login');
}
}
// route with restrict middleware
app.get('/restricted', restrict, function(req, res){
res.send('Wahoo! restricted area');
});
大部分代码都是从 auth 示例,我添加了mongoose的东西。希望这有帮助!
Most of the code is taken from the auth example and I added the stuff for mongoose. Hope this helps!
这篇关于用mongoose + express.js认证用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!