admin.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. import loggerFactory from '~/utils/logger';
  2. import UserGroup from '~/server/models/user-group';
  3. const logger = loggerFactory('growi:routes:admin');
  4. const debug = require('debug')('growi:routes:admin');
  5. /* eslint-disable no-use-before-define */
  6. module.exports = function(crowi, app) {
  7. const models = crowi.models;
  8. const UserGroupRelation = models.UserGroupRelation;
  9. const GlobalNotificationSetting = models.GlobalNotificationSetting;
  10. const {
  11. configManager,
  12. aclService,
  13. slackIntegrationService,
  14. exportService,
  15. } = crowi;
  16. const recommendedWhitelist = require('~/services/xss/recommended-whitelist');
  17. const ApiResponse = require('../util/apiResponse');
  18. const importer = require('../util/importer')(crowi);
  19. const MAX_PAGE_LIST = 50;
  20. const actions = {};
  21. const { check, param } = require('express-validator');
  22. const api = {};
  23. function createPager(total, limit, page, pagesCount, maxPageList) {
  24. const pager = {
  25. page,
  26. pagesCount,
  27. pages: [],
  28. total,
  29. previous: null,
  30. previousDots: false,
  31. next: null,
  32. nextDots: false,
  33. };
  34. if (page > 1) {
  35. pager.previous = page - 1;
  36. }
  37. if (page < pagesCount) {
  38. pager.next = page + 1;
  39. }
  40. let pagerMin = Math.max(1, Math.ceil(page - maxPageList / 2));
  41. let pagerMax = Math.min(pagesCount, Math.floor(page + maxPageList / 2));
  42. if (pagerMin === 1) {
  43. if (MAX_PAGE_LIST < pagesCount) {
  44. pagerMax = MAX_PAGE_LIST;
  45. }
  46. else {
  47. pagerMax = pagesCount;
  48. }
  49. }
  50. if (pagerMax === pagesCount) {
  51. if ((pagerMax - MAX_PAGE_LIST) < 1) {
  52. pagerMin = 1;
  53. }
  54. else {
  55. pagerMin = pagerMax - MAX_PAGE_LIST;
  56. }
  57. }
  58. pager.previousDots = null;
  59. if (pagerMin > 1) {
  60. pager.previousDots = true;
  61. }
  62. pager.nextDots = null;
  63. if (pagerMax < pagesCount) {
  64. pager.nextDots = true;
  65. }
  66. for (let i = pagerMin; i <= pagerMax; i++) {
  67. pager.pages.push(i);
  68. }
  69. return pager;
  70. }
  71. actions.index = function(req, res) {
  72. return res.render('admin/index');
  73. };
  74. // app.get('/admin/app' , admin.app.index);
  75. actions.app = {};
  76. actions.app.index = function(req, res) {
  77. return res.render('admin/app');
  78. };
  79. actions.app.settingUpdate = function(req, res) {
  80. };
  81. // app.get('/admin/security' , admin.security.index);
  82. actions.security = {};
  83. actions.security.index = function(req, res) {
  84. return res.render('admin/security');
  85. };
  86. // app.get('/admin/markdown' , admin.markdown.index);
  87. actions.markdown = {};
  88. actions.markdown.index = function(req, res) {
  89. const markdownSetting = configManager.getConfigByPrefix('markdown', 'markdown:');
  90. return res.render('admin/markdown', {
  91. markdownSetting,
  92. recommendedWhitelist,
  93. });
  94. };
  95. // app.get('/admin/customize' , admin.customize.index);
  96. actions.customize = {};
  97. actions.customize.index = function(req, res) {
  98. const settingForm = configManager.getConfigByPrefix('crowi', 'customize:');
  99. // TODO delete after apiV3
  100. /* eslint-disable quote-props, no-multi-spaces */
  101. const highlightJsCssSelectorOptions = {
  102. 'github': { name: '[Light] GitHub', border: false },
  103. 'github-gist': { name: '[Light] GitHub Gist', border: true },
  104. 'atom-one-light': { name: '[Light] Atom One Light', border: true },
  105. 'xcode': { name: '[Light] Xcode', border: true },
  106. 'vs': { name: '[Light] Vs', border: true },
  107. 'atom-one-dark': { name: '[Dark] Atom One Dark', border: false },
  108. 'hybrid': { name: '[Dark] Hybrid', border: false },
  109. 'monokai': { name: '[Dark] Monokai', border: false },
  110. 'tomorrow-night': { name: '[Dark] Tomorrow Night', border: false },
  111. 'vs2015': { name: '[Dark] Vs 2015', border: false },
  112. };
  113. /* eslint-enable quote-props, no-multi-spaces */
  114. return res.render('admin/customize', {
  115. settingForm,
  116. highlightJsCssSelectorOptions,
  117. });
  118. };
  119. // app.get('/admin/notification' , admin.notification.index);
  120. actions.notification = {};
  121. actions.notification.index = async(req, res) => {
  122. return res.render('admin/notification');
  123. };
  124. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  125. actions.notification.slackAuth = function(req, res) {
  126. const code = req.query.code;
  127. const { t } = req;
  128. if (!code || !slackIntegrationService.isSlackConfigured()) {
  129. return res.redirect('/admin/notification');
  130. }
  131. const slack = crowi.slack;
  132. slack.getOauthAccessToken(code)
  133. .then(async(data) => {
  134. debug('oauth response', data);
  135. try {
  136. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': data.access_token });
  137. req.flash('successMessage', [t('message.successfully_connected')]);
  138. }
  139. catch (err) {
  140. req.flash('errorMessage', [t('message.fail_to_save_access_token')]);
  141. }
  142. return res.redirect('/admin/notification');
  143. })
  144. .catch((err) => {
  145. debug('oauth response ERROR', err);
  146. req.flash('errorMessage', [t('message.fail_to_fetch_access_token')]);
  147. return res.redirect('/admin/notification');
  148. });
  149. };
  150. // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
  151. actions.notification.disconnectFromSlack = async function(req, res) {
  152. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': '' });
  153. req.flash('successMessage', [req.t('successfully_disconnected')]);
  154. return res.redirect('/admin/notification');
  155. };
  156. actions.globalNotification = {};
  157. actions.globalNotification.detail = async(req, res) => {
  158. const notificationSettingId = req.params.id;
  159. let globalNotification;
  160. if (notificationSettingId) {
  161. try {
  162. globalNotification = await GlobalNotificationSetting.findOne({ _id: notificationSettingId });
  163. }
  164. catch (err) {
  165. logger.error(`Error in finding a global notification setting with {_id: ${notificationSettingId}}`);
  166. }
  167. }
  168. return res.render('admin/global-notification-detail', { globalNotification });
  169. };
  170. actions.search = {};
  171. actions.search.index = function(req, res) {
  172. return res.render('admin/search', {});
  173. };
  174. actions.user = {};
  175. actions.user.index = async function(req, res) {
  176. return res.render('admin/users');
  177. };
  178. actions.externalAccount = {};
  179. actions.externalAccount.index = function(req, res) {
  180. return res.render('admin/external-accounts');
  181. };
  182. actions.slackIntegrationLegacy = {};
  183. actions.slackIntegrationLegacy = function(req, res) {
  184. return res.render('admin/slack-integration-legacy');
  185. };
  186. actions.slackIntegration = {};
  187. actions.slackIntegration = function(req, res) {
  188. return res.render('admin/slack-integration');
  189. };
  190. actions.userGroup = {};
  191. actions.userGroup.index = function(req, res) {
  192. const page = parseInt(req.query.page) || 1;
  193. const renderVar = {
  194. userGroups: [],
  195. userGroupRelations: new Map(),
  196. pager: null,
  197. };
  198. UserGroup.findUserGroupsWithPagination({ page })
  199. .then((result) => {
  200. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  201. const userGroups = result.docs;
  202. renderVar.userGroups = userGroups;
  203. renderVar.pager = pager;
  204. return userGroups.map((userGroup) => {
  205. return new Promise((resolve, reject) => {
  206. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  207. .then((relations) => {
  208. return resolve({
  209. id: userGroup._id,
  210. relatedUsers: relations.map((relation) => {
  211. return relation.relatedUser;
  212. }),
  213. });
  214. });
  215. });
  216. });
  217. })
  218. .then((allRelationsPromise) => {
  219. return Promise.all(allRelationsPromise);
  220. })
  221. .then((relations) => {
  222. for (const relation of relations) {
  223. renderVar.userGroupRelations[relation.id] = relation.relatedUsers;
  224. }
  225. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  226. return res.render('admin/user-groups', renderVar);
  227. })
  228. .catch((err) => {
  229. debug('Error on find all relations', err);
  230. return res.json(ApiResponse.error('Error'));
  231. });
  232. };
  233. // グループ詳細
  234. actions.userGroup.detail = async function(req, res) {
  235. const userGroupId = req.params.id;
  236. const userGroup = await UserGroup.findOne({ _id: userGroupId }).populate('parent');
  237. if (userGroup == null) {
  238. logger.error('no userGroup is exists. ', userGroupId);
  239. return res.redirect('/admin/user-groups');
  240. }
  241. return res.render('admin/user-group-detail', { userGroup });
  242. };
  243. // Importer management
  244. actions.importer = {};
  245. actions.importer.api = api;
  246. api.validators = {};
  247. api.validators.importer = {};
  248. actions.importer.index = function(req, res) {
  249. const settingForm = configManager.getConfigByPrefix('crowi', 'importer:');
  250. return res.render('admin/importer', {
  251. settingForm,
  252. });
  253. };
  254. api.validators.importer.esa = function() {
  255. const validator = [
  256. check('importer:esa:team_name').not().isEmpty().withMessage('Error. Empty esa:team_name'),
  257. check('importer:esa:access_token').not().isEmpty().withMessage('Error. Empty esa:access_token'),
  258. ];
  259. return validator;
  260. };
  261. api.validators.importer.qiita = function() {
  262. const validator = [
  263. check('importer:qiita:team_name').not().isEmpty().withMessage('Error. Empty qiita:team_name'),
  264. check('importer:qiita:access_token').not().isEmpty().withMessage('Error. Empty qiita:access_token'),
  265. ];
  266. return validator;
  267. };
  268. // Export management
  269. actions.export = {};
  270. actions.export.api = api;
  271. api.validators.export = {};
  272. actions.export.index = (req, res) => {
  273. return res.render('admin/export');
  274. };
  275. api.validators.export.download = function() {
  276. const validator = [
  277. // https://regex101.com/r/mD4eZs/6
  278. // prevent from pass traversal attack
  279. param('fileName').not().matches(/(\.\.\/|\.\.\\)/),
  280. ];
  281. return validator;
  282. };
  283. actions.export.download = (req, res) => {
  284. const { fileName } = req.params;
  285. const { validationResult } = require('express-validator');
  286. const errors = validationResult(req);
  287. if (!errors.isEmpty()) {
  288. return res.status(422).json({ errors: `${fileName} is invalid. Do not use path like '../'.` });
  289. }
  290. try {
  291. const zipFile = exportService.getFile(fileName);
  292. return res.download(zipFile);
  293. }
  294. catch (err) {
  295. // TODO: use ApiV3Error
  296. logger.error(err);
  297. return res.json(ApiResponse.error());
  298. }
  299. };
  300. actions.api = {};
  301. /**
  302. * save esa settings, update config cache, and response json
  303. *
  304. * @param {*} req
  305. * @param {*} res
  306. */
  307. actions.api.importerSettingEsa = async(req, res) => {
  308. const form = req.body;
  309. const { validationResult } = require('express-validator');
  310. const errors = validationResult(req);
  311. if (!errors.isEmpty()) {
  312. return res.json(ApiResponse.error('esa.io form is blank'));
  313. }
  314. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  315. importer.initializeEsaClient(); // let it run in the back aftert res
  316. return res.json(ApiResponse.success());
  317. };
  318. /**
  319. * save qiita settings, update config cache, and response json
  320. *
  321. * @param {*} req
  322. * @param {*} res
  323. */
  324. actions.api.importerSettingQiita = async(req, res) => {
  325. const form = req.body;
  326. const { validationResult } = require('express-validator');
  327. const errors = validationResult(req);
  328. if (!errors.isEmpty()) {
  329. return res.json(ApiResponse.error('Qiita form is blank'));
  330. }
  331. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  332. importer.initializeQiitaClient(); // let it run in the back aftert res
  333. return res.json(ApiResponse.success());
  334. };
  335. /**
  336. * Import all posts from esa
  337. *
  338. * @param {*} req
  339. * @param {*} res
  340. */
  341. actions.api.importDataFromEsa = async(req, res) => {
  342. const user = req.user;
  343. let errors;
  344. try {
  345. errors = await importer.importDataFromEsa(user);
  346. }
  347. catch (err) {
  348. errors = [err];
  349. }
  350. if (errors.length > 0) {
  351. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  352. }
  353. return res.json(ApiResponse.success());
  354. };
  355. /**
  356. * Import all posts from qiita
  357. *
  358. * @param {*} req
  359. * @param {*} res
  360. */
  361. actions.api.importDataFromQiita = async(req, res) => {
  362. const user = req.user;
  363. let errors;
  364. try {
  365. errors = await importer.importDataFromQiita(user);
  366. }
  367. catch (err) {
  368. errors = [err];
  369. }
  370. if (errors.length > 0) {
  371. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  372. }
  373. return res.json(ApiResponse.success());
  374. };
  375. /**
  376. * Test connection to esa and response result with json
  377. *
  378. * @param {*} req
  379. * @param {*} res
  380. */
  381. actions.api.testEsaAPI = async(req, res) => {
  382. try {
  383. await importer.testConnectionToEsa();
  384. return res.json(ApiResponse.success());
  385. }
  386. catch (err) {
  387. return res.json(ApiResponse.error(err));
  388. }
  389. };
  390. /**
  391. * Test connection to qiita and response result with json
  392. *
  393. * @param {*} req
  394. * @param {*} res
  395. */
  396. actions.api.testQiitaAPI = async(req, res) => {
  397. try {
  398. await importer.testConnectionToQiita();
  399. return res.json(ApiResponse.success());
  400. }
  401. catch (err) {
  402. return res.json(ApiResponse.error(err));
  403. }
  404. };
  405. actions.api.searchBuildIndex = async function(req, res) {
  406. const search = crowi.getSearcher();
  407. if (!search) {
  408. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  409. }
  410. try {
  411. search.buildIndex();
  412. }
  413. catch (err) {
  414. return res.json(ApiResponse.error(err));
  415. }
  416. return res.json(ApiResponse.success());
  417. };
  418. actions.notFound = {};
  419. actions.notFound.index = function(req, res) {
  420. return res.render('admin/not_found');
  421. };
  422. return actions;
  423. };