18.05.2016 Views

Mittwoch, 18. Mai, 2016

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

MongoDB CRUD the MVC way with Passport Authentication 75<br />

40 res.render('register', {<br />

41 title: 'Register Form',<br />

42 messages: req.flash('error')<br />

43 });<br />

44 }<br />

45 else {<br />

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

47 }<br />

48 };<br />

49<br />

50 exports.register = function(req, res, next) {<br />

51 if (!req.user) {<br />

52 var user = new User(req.body);<br />

53 var message = null;<br />

54 user.provider = 'local';<br />

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

56 if (err) {<br />

57 var message = getErrorMessage(err);<br />

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

59 return res.redirect('/register');<br />

60 }<br />

61<br />

62 req.login(user, function(err) {<br />

63 if (err)<br />

64 return next(err);<br />

65<br />

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

67 });<br />

68 });<br />

69 }<br />

70 else {<br />

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

72 }<br />

73 };<br />

74<br />

75 exports.logout = function(req, res) {<br />

76 req.logout();<br />

77 res.redirect('/');<br />

78 };<br />

The register() method uses your User model to create new users, so that it first creates a user<br />

object from the HTTP request body. Then, it tries to save it to MongoDB and if an error occurs, the<br />

register() method will use the getErrorMessage() method to fetch the errors. If the user was created

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

Saved successfully!

Ooh no, something went wrong!