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

14 User.findUniqueUsername(possibleUsername, null, function(ava\<br />

15 ilableUsername) {<br />

16 profile.username = availableUsername;<br />

17 user = new User(profile);<br />

18<br />

19 user.save(function(err) {<br />

20 if (err) {<br />

21 var message = _this.getErrorMessage(err);<br />

22 req.flash('error', message);<br />

23 return res.redirect('/signup');<br />

24 }<br />

25<br />

26 return done(err, user);<br />

27 });<br />

28 });<br />

29 }<br />

30 else {<br />

31 return done(err, user);<br />

32 }<br />

33 }<br />

34 }<br />

35 );<br />

36 };<br />

This method accepts a user profile, and then looks for an existing user with providerId and provider<br />

properties. If the user is found, it calls the done() callback method with the user’s MongoDB<br />

document. However, if an existing user isn’t found, it will find a unique username using the _User<br />

_model’s findUniqueUsername() static method and save a new user instance. If an error occurs, the<br />

saveOAuthUserProfile() method will use the req.flash() and getErrorMessage() methods to report<br />

the error; otherwise, it will pass the user object to the done() callback method.<br />

Now, install the Facebook strategy module:<br />

1 npm install passport-facebook --save<br />

Create a Facebook application<br />

Before you can configure your Facebook strategy, you have to go to Facebook’s developer home<br />

page at https://developers.facebook.com/¹³⁵ and create a new Facebook application:<br />

¹³⁵https://developers.facebook.com/

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

Saved successfully!

Ooh no, something went wrong!