18.05.2016 Views

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 66<br />

17<br />

18 if (!user.authenticate(password)) {<br />

19 return done(null, false, {message: 'Invalid password'});<br />

20 }<br />

21<br />

22 return done(null, user);<br />

23 }<br />

24 );<br />

25 }));<br />

26 };<br />

Here you first require the Passport module, then the local strategy module’s Strategy object, and<br />

finally your User Mongoose model. Then, you register the strategy using the passport.use() method<br />

that uses an instance of the LocalStrategy object. Inside the callback function you use the User<br />

Mongoose model to find a user with the passed username and try to authenticate it.<br />

Now, create a passport.js file in the config folder and add this code:<br />

1 var passport = require('passport'),<br />

2 mongoose = require('mongoose');<br />

3<br />

4 module.exports = function() {<br />

5 var User = mongoose.model('User');<br />

6<br />

7 passport.serializeUser(function(user, done) {<br />

8 done(null, user.id);<br />

9 });<br />

10<br />

11 passport.deserializeUser(function(id, done) {<br />

12 User.findOne(<br />

13 {_id: id},<br />

14 '-password',<br />

15 function(err, user) {<br />

16 done(err, user);<br />

17 }<br />

18 );<br />

19 });<br />

20<br />

21 require('./strategies/local.js')();<br />

22 };<br />

With passport.serializeUser() and passport.deserializeUser() methods you defined how Passport<br />

will handle user serialization. When a user is authenticated, Passport will save its _id property to

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!