问题描述
我有一个expressjs应用程序,我正在尝试为简单的用户身份验证设置passportjsjs.我的路线存储在单独的文件中.我有一个与我所有与用户相关的路由的路由文件(users.js).我还有一个名为UserController的控制器文件,其中包含用户相关内容的所有功能并处理我的数据库.
I have an expressjs application and I am trying to get passportjs set up for simple user authentication. My routes are stored in a separate file. I have a routes file (users.js) for all my user related routes. I also have a controller file called UserController that contains all the functions for user related stuff and deals with my database.
我的问题是,应该在哪里声明护照策略,使其遵循MVC模式?
My question is, where should I declare the passport strategy so that it follows the MVC pattern?
将其放入路由文件之外的任何其他文件中将不起作用,因为它没有通行证对象.
Putting it in any other file besides the routes file doesn't work as it does not have the passport object.
推荐答案
我将我的护照文件放在config文件夹中.这是passport.js文件的示例.这是用于本地登录策略的.
I put my passport file in a config folder. Here is an example of a passport.js file. This is for the local-login strategy.
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
}); // if you are using sessions
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
}); // if you are using sessions
passport.use('local-login', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
// mongodb example - you have to query for user,
// check password, and return user if successful
User.findOne({ 'local.email' : email },
function(err, user) {
if (err) return done(err);
if (!user) return done(null, false);
if (!user.validPassword(password) {
return done(null, false);
}
else
return done(null, user); // all good return user
});
});
};
然后在app.js中执行:
then in app.js I do:
require('./config/passport.js')(passport);
app.use(passport.initialize())
var usersRoutes = require('./server/routes/usersRoutes')(app, express, passport);
app.use('/users', usersRoutes);
然后在您的路线文件中:
then in your routes file:
module.exports = function(app, express, passport) {
var usersRouter = express.Router();
return usersRouter;
};
现在您的护照功能在您的路线中可用.我会在网络上搜索"easy-node-authentication"以查找良好的示例.
now your passport functions are available in your route. I would search 'easy-node-authentication' for good examples on the web.
这篇关于在哪里将PassportJs的本地策略放在快速应用程序中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!