我正在构建一个连接到ElasticSearch的小型NodeJS服务器。我需要用户身份验证,elasticsearch似乎不太适合存储用户信息。
而不是承担使用例如MongoDB用于存储用户帐户,是否可以将PassportJS本地策略与用户帐户的json文件或内存中的用户帐户数组一起使用?
将手动设置用户-手动编辑用户的json文件将很容易,并且用户将很少。
编辑
如果可能的话,您能举个例子吗?
谢谢
最佳答案
您可以引用这篇出色的博客文章,以了解PassportJS身份验证-Passport authentication。
我还在必要时添加了评论。您只需要将从DB提取用户数据的逻辑更改为从JSON文件获取用户数据的逻辑。
// config/passport.js
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
// load up the users json data
var User = require('../app/data/users');
// expose this function to our app using module.exports
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
// Write a logic to find this particular user from the json data using userID
// If not found return done({});
// else return done(null, userObject);
});
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
// Write a logic to find this particular user from the json data using email
// validate for password
// If not found or password incorrect return done({});
// else return done(null, userObject);
}));
};