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.

Finishing Angular TODO application and deploying to production 116<br />

1 exports.requiresLogin = function(req, res, next) {<br />

2 if (!req.isAuthenticated()) {<br />

3 return res.status(401).send({<br />

4 message: 'User is not logged in'<br />

5 });<br />

6 }<br />

7 next();<br />

8 };<br />

This middleware uses the Passport initiated req.isAuthenticated method to check whether a user<br />

is currently authenticated. If it finds out the user is indeed signed in, it will call the next middleware<br />

in the chain; otherwise it will respond with an authentication error and an HTTP error code. Full<br />

code listing for this file is below:<br />

1 var User = require('mongoose').model('User'),<br />

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

3<br />

4 var getErrorMessage = function(err) {<br />

5 var message = '';<br />

6 if (err.code) {<br />

7 switch (err.code) {<br />

8 case 11000:<br />

9 case 11001:<br />

10 message = 'Username already exists';<br />

11 break;<br />

12 default:<br />

13 message = 'Something went wrong';<br />

14 }<br />

15 } else {<br />

16 for (var errName in err.errors) {<br />

17 if (err.errors[errName].message)<br />

18 message = err.errors[errName].message;<br />

19 }<br />

20 }<br />

21<br />

22 return message;<br />

23 };<br />

24<br />

25 exports.renderLogin = function(req, res, next) {<br />

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

27 res.render('login', {<br />

28 title: 'Log-in Form',

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

Saved successfully!

Ooh no, something went wrong!