ric*_*ick 5 node.js express passport.js
我正在构建一个连接到 ElasticSearch 的小型 NodeJS 服务器。我需要用户身份验证,而elasticsearch 似乎不太适合存储用户信息。
与其承担使用例如 MongoDB 存储用户帐户的额外开销,是否可以将 PassportJS 本地策略与用户帐户的 json 文件或内存中的用户帐户数组一起使用?
用户将被手动配置 - 手动编辑用户的 json 文件会很容易,而且用户很少。
编辑 如果可能的话,你能给我举个例子吗?
谢谢
您可以参考这篇优秀的博客文章来了解passportJS身份验证-Passport身份验证。我还在必要的地方添加了评论。您只需将从 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);
}));
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3168 次 |
最近记录: |