unauthorized.js 941 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * unauthorized.js
  3. *
  4. * A custom response that content-negotiates the current request to either:
  5. * • log out the current user and redirect them to the login page
  6. * • or send back 401 (Unauthorized) with no response body.
  7. *
  8. * Example usage:
  9. * ```
  10. * return res.unauthorized();
  11. * ```
  12. *
  13. * Or with actions2:
  14. * ```
  15. * exits: {
  16. * badCombo: {
  17. * description: 'That email address and password combination is not recognized.',
  18. * responseType: 'unauthorized'
  19. * }
  20. * }
  21. * ```
  22. */
  23. module.exports = function unauthorized() {
  24. var req = this.req;
  25. var res = this.res;
  26. sails.log.verbose('Ran custom response: res.unauthorized()');
  27. if (req.wantsJSON) {
  28. return res.sendStatus(401);
  29. }
  30. // Or log them out (if necessary) and then redirect to the login page.
  31. else {
  32. if (req.session.userId) {
  33. delete req.session.userId;
  34. }
  35. return res.redirect('/login');
  36. }
  37. };