Advertisement
Guest User

Untitled

a guest
Apr 21st, 2017
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. // Check if the user is authenticated: I have a middleware function named CheckAuth which I use on every route that needs the user to be authenticated:
  2. function checkAuth(req, res, next) {
  3. if (!req.session.user_id) {
  4. res.send('You are not authorized to view this page');
  5. } else {
  6. next();
  7. }
  8. }
  9.  
  10. // I use this function in my routes like this:
  11. app.get('/my_secret_page', checkAuth, function (req, res) {
  12. res.send('if you are viewing this page it means you are logged in');
  13. });
  14.  
  15. // 2) The login route:
  16. app.post('/login', function (req, res) {
  17. var post = req.body;
  18. if (post.user === 'john' && post.password === 'johnspassword') {
  19. req.session.user_id = johns_user_id_here;
  20. res.redirect('/my_secret_page');
  21. } else {
  22. res.send('Bad user/pass');
  23. }
  24. });
  25.  
  26. // 3) The logout route:
  27. app.get('/logout', function (req, res) {
  28. delete req.session.user_id;
  29. res.redirect('/login');
  30. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement