middlewares.js 8.4 KB

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