middlewares.js 8.4 KB

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