admin.js 16 KB

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