middlewares.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. var debug = require('debug')('crowi:lib:middlewares');
  2. var md5 = require('md5');
  3. exports.csrfKeyGenerator = function(crowi, app) {
  4. return function(req, res, next) {
  5. var csrfKey = (req.session && req.session.id) || 'anon';
  6. if (req.csrfToken === null) {
  7. req.csrfToken = crowi.getTokens().create(csrfKey);
  8. }
  9. next();
  10. }
  11. }
  12. exports.loginChecker = function(crowi, app) {
  13. return function(req, res, next) {
  14. var User = crowi.model('User');
  15. // session に user object が入ってる
  16. if (req.session.user && '_id' in req.session.user) {
  17. User.findById(req.session.user._id, function(err, userData) {
  18. if (err) {
  19. next();
  20. } else {
  21. req.user = req.session.user = userData;
  22. res.locals.user = req.user;
  23. next();
  24. }
  25. });
  26. } else {
  27. req.user = req.session.user = false;
  28. res.locals.user = req.user;
  29. next();
  30. }
  31. };
  32. };
  33. exports.loginCheckerForPassport = function(crowi, app) {
  34. return function(req, res, next) {
  35. res.locals.user = req.user;
  36. next();
  37. };
  38. };
  39. exports.csrfVerify = function(crowi, app) {
  40. return function(req, res, next) {
  41. var token = req.body._csrf || req.query._csrf || null;
  42. var csrfKey = (req.session && req.session.id) || 'anon';
  43. debug('req.skipCsrfVerify', req.skipCsrfVerify);
  44. if (req.skipCsrfVerify) {
  45. debug('csrf verify skipped');
  46. return next();
  47. }
  48. if (crowi.getTokens().verify(csrfKey, token)) {
  49. debug('csrf successfully verified');
  50. return next();
  51. }
  52. debug('csrf verification failed. return 403', csrfKey, token);
  53. return res.sendStatus(403);
  54. };
  55. };
  56. exports.swigFunctions = function(crowi, app) {
  57. return function(req, res, next) {
  58. require('../util/swigFunctions')(crowi, app, req, res.locals);
  59. next();
  60. };
  61. };
  62. exports.swigFilters = function(app, swig) {
  63. // define a function for Gravatar
  64. const generateGravatarSrc = function(user) {
  65. const hash = md5(user.email.trim().toLowerCase());
  66. return `https://gravatar.com/avatar/${hash}`;
  67. };
  68. // define a function for uploaded picture
  69. const getUploadedPictureSrc = function(user) {
  70. if (user.image) {
  71. return user.image;
  72. }
  73. else {
  74. return '/images/userpicture.png';
  75. }
  76. };
  77. return function(req, res, next) {
  78. swig.setFilter('path2name', function(string) {
  79. var name = string.replace(/(\/)$/, '');
  80. if (name.match(/.+\/([^/]+\/\d{4}\/\d{2}\/\d{2})$/)) { // /.../hoge/YYYY/MM/DD 形式のページ
  81. return name.replace(/.+\/([^/]+\/\d{4}\/\d{2}\/\d{2})$/, '$1');
  82. }
  83. if (name.match(/.+\/([^/]+\/\d{4}\/\d{2})$/)) { // /.../hoge/YYYY/MM 形式のページ
  84. return name.replace(/.+\/([^/]+\/\d{4}\/\d{2})$/, '$1');
  85. }
  86. if (name.match(/.+\/([^/]+\/\d{4})$/)) { // /.../hoge/YYYY 形式のページ
  87. return name.replace(/.+\/([^/]+\/\d{4})$/, '$1');
  88. }
  89. return name.replace(/.+\/(.+)?$/, '$1'); // ページの末尾を拾う
  90. });
  91. swig.setFilter('normalizeDateInPath', function(path) {
  92. var patterns = [
  93. [/20(\d{2})(\d{2})(\d{2})(.+)/g, '20$1/$2/$3/$4'],
  94. [/20(\d{2})(\d{2})(\d{2})/g, '20$1/$2/$3'],
  95. [/20(\d{2})(\d{2})(.+)/g, '20$1/$2/$3'],
  96. [/20(\d{2})(\d{2})/g, '20$1/$2'],
  97. [/20(\d{2})_(\d{1,2})_(\d{1,2})_?(.+)/g, '20$1/$2/$3/$4'],
  98. [/20(\d{2})_(\d{1,2})_(\d{1,2})/g, '20$1/$2/$3'],
  99. [/20(\d{2})_(\d{1,2})_?(.+)/g, '20$1/$2/$3'],
  100. [/20(\d{2})_(\d{1,2})/g, '20$1/$2'],
  101. ];
  102. for (var i = 0; i < patterns.length ; i++) {
  103. var mat = patterns[i][0];
  104. var rep = patterns[i][1];
  105. if (path.match(mat)) {
  106. return path.replace(mat, rep);
  107. }
  108. }
  109. return path;
  110. });
  111. swig.setFilter('datetz', function(input, format) {
  112. // timezone
  113. var swigFilters = require('swig-templates/lib/filters');
  114. return swigFilters.date(input, format, app.get('tzoffset'));
  115. });
  116. swig.setFilter('nl2br', function(string) {
  117. return string
  118. .replace(/\n/g, '<br>');
  119. });
  120. swig.setFilter('removeLastSlash', function(string) {
  121. if (string == '/') {
  122. return string;
  123. }
  124. return string.substr(0, string.length - 1);
  125. });
  126. swig.setFilter('presentation', function(string) {
  127. // 手抜き
  128. return string
  129. .replace(/[\n]+#/g, '\n\n\n#')
  130. .replace(/\s(https?.+(jpe?g|png|gif))\s/, '\n\n\n![]($1)\n\n\n');
  131. });
  132. swig.setFilter('gravatar', generateGravatarSrc);
  133. swig.setFilter('uploadedpicture', getUploadedPictureSrc);
  134. swig.setFilter('picture', function(user) {
  135. if (!user) {
  136. return '/images/userpicture.png';
  137. }
  138. if (user.isGravatarEnabled === true) {
  139. return generateGravatarSrc(user);
  140. }
  141. else {
  142. return getUploadedPictureSrc(user);
  143. }
  144. });
  145. next();
  146. };
  147. };
  148. exports.adminRequired = function() {
  149. return function(req, res, next) {
  150. if (req.user && '_id' in req.user) {
  151. if (req.user.admin) {
  152. next();
  153. return;
  154. }
  155. return res.redirect('/');
  156. }
  157. return res.redirect('/login');
  158. };
  159. };
  160. /**
  161. * require login handler
  162. *
  163. * @param {any} crowi
  164. * @param {any} app
  165. * @param {boolean} isStrictly whethere strictly restricted (default true)
  166. */
  167. exports.loginRequired = function(crowi, app, isStrictly = true) {
  168. return function(req, res, next) {
  169. var User = crowi.model('User')
  170. // when the route is not strictly restricted
  171. if (!isStrictly) {
  172. var config = req.config;
  173. var Config = crowi.model('Config');
  174. // when allowed to read
  175. if (Config.isGuesstAllowedToRead(config)) {
  176. return next();
  177. }
  178. }
  179. if (req.user && '_id' in req.user) {
  180. if (req.user.status === User.STATUS_ACTIVE) {
  181. // Active の人だけ先に進める
  182. return next();
  183. } else if (req.user.status === User.STATUS_REGISTERED) {
  184. return res.redirect('/login/error/registered');
  185. } else if (req.user.status === User.STATUS_SUSPENDED) {
  186. return res.redirect('/login/error/suspended');
  187. } else if (req.user.status === User.STATUS_INVITED) {
  188. return res.redirect('/login/invited');
  189. }
  190. }
  191. // is api path
  192. var path = req.path || '';
  193. if (path.match(/^\/_api\/.+$/)) {
  194. return res.sendStatus(403);
  195. }
  196. req.session.jumpTo = req.originalUrl;
  197. return res.redirect('/login');
  198. };
  199. };
  200. exports.accessTokenParser = function(crowi, app) {
  201. return function(req, res, next) {
  202. // TODO: comply HTTP header of RFC6750 / Authorization: Bearer
  203. var accessToken = req.query.access_token || req.body.access_token || null;
  204. if (!accessToken) {
  205. return next();
  206. }
  207. var User = crowi.model('User')
  208. debug('accessToken is', accessToken);
  209. User.findUserByApiToken(accessToken)
  210. .then(function(userData) {
  211. req.user = userData;
  212. req.skipCsrfVerify = true;
  213. debug('Access token parsed: skipCsrfVerify');
  214. next();
  215. }).catch(function(err) {
  216. next();
  217. });
  218. };
  219. };
  220. // this is for Installer
  221. exports.applicationNotInstalled = function() {
  222. return function(req, res, next) {
  223. var config = req.config;
  224. if (Object.keys(config.crowi).length !== 1) {
  225. req.flash('errorMessage', 'Application already installed.');
  226. return res.redirect('admin'); // admin以外はadminRequiredで'/'にリダイレクトされる
  227. }
  228. return next();
  229. };
  230. };
  231. exports.checkSearchIndicesGenerated = function(crowi, app) {
  232. return function(req, res, next) {
  233. const searcher = crowi.getSearcher();
  234. // build index
  235. if (searcher) {
  236. searcher.buildIndex()
  237. .then((data) => {
  238. if (!data.errors) {
  239. debug('Index created.');
  240. }
  241. return searcher.addAllPages();
  242. });
  243. }
  244. return next();
  245. };
  246. }
  247. exports.applicationInstalled = function() {
  248. return function(req, res, next) {
  249. var config = req.config;
  250. if (Object.keys(config.crowi).length === 1) { // app:url is set by process
  251. return res.redirect('/installer');
  252. }
  253. return next();
  254. };
  255. };
  256. exports.awsEnabled = function() {
  257. return function (req, res, next) {
  258. var config = req.config;
  259. if (config.crowi['aws:region'] !== '' && config.crowi['aws:bucket'] !== '' && config.crowi['aws:accessKeyId'] !== '' && config.crowi['aws:secretAccessKey'] !== '') {
  260. req.flash('globalError', 'AWS settings required to use this function. Please ask the administrator.');
  261. return res.redirect('/');
  262. }
  263. return next();
  264. };
  265. };