login-required.js 1.8 KB

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