login-required.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const loggerFactory = require('@alias/logger');
  2. const logger = loggerFactory('growi:middleware:login-required');
  3. /**
  4. * require login handler
  5. *
  6. * @param {boolean} isGuestAllowed whethere guest user is allowed (default false)
  7. * @param {function} fallback fallback function which will be triggered when the check cannot be passed
  8. */
  9. module.exports = (crowi, isGuestAllowed = false, fallback = null) => {
  10. return function(req, res, next) {
  11. // check the route config and ACL
  12. if (isGuestAllowed && crowi.aclService.isGuestAllowedToRead()) {
  13. logger.debug('Allowed to read: ', req.path);
  14. return next();
  15. }
  16. // check the page is shared
  17. if (isGuestAllowed && req.isSharedPage) {
  18. logger.debug('Target page is shared page');
  19. return next();
  20. }
  21. const User = crowi.model('User');
  22. // check the user logged in
  23. if (req.user != null && (req.user instanceof Object) && '_id' in req.user) {
  24. if (req.user.status === User.STATUS_ACTIVE) {
  25. // Active の人だけ先に進める
  26. return next();
  27. }
  28. if (req.user.status === User.STATUS_REGISTERED) {
  29. return res.redirect('/login/error/registered');
  30. }
  31. if (req.user.status === User.STATUS_SUSPENDED) {
  32. return res.redirect('/login/error/suspended');
  33. }
  34. if (req.user.status === User.STATUS_INVITED) {
  35. return res.redirect('/login/invited');
  36. }
  37. }
  38. // is api path
  39. const path = req.path || '';
  40. if (path.match(/^\/_api\/.+$/)) {
  41. if (fallback != null) {
  42. return fallback(req, res);
  43. }
  44. return res.sendStatus(403);
  45. }
  46. if (fallback != null) {
  47. return fallback(req, res);
  48. }
  49. req.session.redirectTo = req.originalUrl;
  50. return res.redirect('/login');
  51. };
  52. };