Mittwoch, 18. Mai, 2016
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
MongoDB CRUD the MVC way with Passport Authentication 65<br />
1 passport = require('./config/passport');<br />
2 ...<br />
3 var passport = passport();<br />
Also, require it in the config/express.js file like this:<br />
1 passport = require('passport');<br />
2<br />
3 //use this code before any route definitions<br />
4 app.use(passport.initialize());<br />
5 app.use(passport.session());<br />
Now you need to install at least one authentication strategy, and here I’ll show you three: local<br />
strategy (username/password) authentication, Facebook OAuth authentication and Twitter OAuth<br />
authentication with exact steps.<br />
Local authentication strategy<br />
First, install the local strategy authentication module:<br />
1 $ npm install passport-local --save<br />
Now, in the config folder, create a new folder called strategies and a new file local.js with the<br />
following code:<br />
1 var passport = require('passport'),<br />
2 LocalStrategy = require('passport-local').Strategy,<br />
3 User = require('mongoose').model('User');<br />
4<br />
5 module.exports = function() {<br />
6 passport.use(new LocalStrategy(function(username, password, done) {<br />
7 User.findOne(<br />
8 {username: username},<br />
9 function(err, user) {<br />
10 if (err) {<br />
11 return done(err);<br />
12 }<br />
13<br />
14 if (!user) {<br />
15 return done(null, false, {message: 'Unknown user'});<br />
16 }