admin.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. return res.render('admin/customize', {
  102. settingForm,
  103. });
  104. };
  105. // app.get('/admin/notification' , admin.notification.index);
  106. actions.notification = {};
  107. actions.notification.index = async(req, res) => {
  108. return res.render('admin/notification');
  109. };
  110. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  111. actions.notification.slackAuth = function(req, res) {
  112. const code = req.query.code;
  113. const { t } = req;
  114. if (!code || !slackIntegrationService.isSlackConfigured()) {
  115. return res.redirect('/admin/notification');
  116. }
  117. const slack = crowi.slack;
  118. slack.getOauthAccessToken(code)
  119. .then(async(data) => {
  120. debug('oauth response', data);
  121. try {
  122. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': data.access_token });
  123. req.flash('successMessage', [t('message.successfully_connected')]);
  124. }
  125. catch (err) {
  126. req.flash('errorMessage', [t('message.fail_to_save_access_token')]);
  127. }
  128. return res.redirect('/admin/notification');
  129. })
  130. .catch((err) => {
  131. debug('oauth response ERROR', err);
  132. req.flash('errorMessage', [t('message.fail_to_fetch_access_token')]);
  133. return res.redirect('/admin/notification');
  134. });
  135. };
  136. // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
  137. actions.notification.disconnectFromSlack = async function(req, res) {
  138. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': '' });
  139. req.flash('successMessage', [req.t('successfully_disconnected')]);
  140. return res.redirect('/admin/notification');
  141. };
  142. // actions.globalNotification = {};
  143. // actions.globalNotification.detail = async(req, res) => {
  144. // const notificationSettingId = req.params.id;
  145. // let globalNotification;
  146. // if (notificationSettingId) {
  147. // try {
  148. // globalNotification = await GlobalNotificationSetting.findOne({ _id: notificationSettingId });
  149. // }
  150. // catch (err) {
  151. // logger.error(`Error in finding a global notification setting with {_id: ${notificationSettingId}}`);
  152. // }
  153. // }
  154. // return res.render('admin/global-notification-detail', { globalNotification });
  155. // };
  156. actions.search = {};
  157. actions.search.index = function(req, res) {
  158. return res.render('admin/search', {});
  159. };
  160. actions.user = {};
  161. actions.user.index = async function(req, res) {
  162. return res.render('admin/users');
  163. };
  164. actions.externalAccount = {};
  165. actions.externalAccount.index = function(req, res) {
  166. return res.render('admin/external-accounts');
  167. };
  168. actions.slackIntegrationLegacy = {};
  169. actions.slackIntegrationLegacy = function(req, res) {
  170. return res.render('admin/slack-integration-legacy');
  171. };
  172. actions.slackIntegration = {};
  173. actions.slackIntegration = function(req, res) {
  174. return res.render('admin/slack-integration');
  175. };
  176. actions.userGroup = {};
  177. actions.userGroup.index = function(req, res) {
  178. const page = parseInt(req.query.page) || 1;
  179. const renderVar = {
  180. userGroups: [],
  181. userGroupRelations: new Map(),
  182. pager: null,
  183. };
  184. UserGroup.findUserGroupsWithPagination({ page })
  185. .then((result) => {
  186. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  187. const userGroups = result.docs;
  188. renderVar.userGroups = userGroups;
  189. renderVar.pager = pager;
  190. return userGroups.map((userGroup) => {
  191. return new Promise((resolve, reject) => {
  192. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  193. .then((relations) => {
  194. return resolve({
  195. id: userGroup._id,
  196. relatedUsers: relations.map((relation) => {
  197. return relation.relatedUser;
  198. }),
  199. });
  200. });
  201. });
  202. });
  203. })
  204. .then((allRelationsPromise) => {
  205. return Promise.all(allRelationsPromise);
  206. })
  207. .then((relations) => {
  208. for (const relation of relations) {
  209. renderVar.userGroupRelations[relation.id] = relation.relatedUsers;
  210. }
  211. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  212. return res.render('admin/user-groups', renderVar);
  213. })
  214. .catch((err) => {
  215. debug('Error on find all relations', err);
  216. return res.json(ApiResponse.error('Error'));
  217. });
  218. };
  219. // グループ詳細
  220. // actions.userGroup.detail = async function(req, res) {
  221. // const userGroupId = req.params.id;
  222. // const userGroup = await UserGroup.findOne({ _id: userGroupId }).populate('parent');
  223. // if (userGroup == null) {
  224. // logger.error('no userGroup is exists. ', userGroupId);
  225. // return res.redirect('/admin/user-groups');
  226. // }
  227. // return res.render('admin/user-group-detail', { userGroup });
  228. // };
  229. // AuditLog
  230. actions.auditLog = {};
  231. actions.auditLog.index = (req, res) => {
  232. return res.render('admin/audit-log');
  233. };
  234. // Importer management
  235. actions.importer = {};
  236. actions.importer.api = api;
  237. api.validators = {};
  238. api.validators.importer = {};
  239. api.validators.importer.esa = function() {
  240. const validator = [
  241. check('importer:esa:team_name').not().isEmpty().withMessage('Error. Empty esa:team_name'),
  242. check('importer:esa:access_token').not().isEmpty().withMessage('Error. Empty esa:access_token'),
  243. ];
  244. return validator;
  245. };
  246. api.validators.importer.qiita = function() {
  247. const validator = [
  248. check('importer:qiita:team_name').not().isEmpty().withMessage('Error. Empty qiita:team_name'),
  249. check('importer:qiita:access_token').not().isEmpty().withMessage('Error. Empty qiita:access_token'),
  250. ];
  251. return validator;
  252. };
  253. // Export management
  254. actions.export = {};
  255. actions.export.api = api;
  256. api.validators.export = {};
  257. api.validators.export.download = function() {
  258. const validator = [
  259. // https://regex101.com/r/mD4eZs/6
  260. // prevent from pass traversal attack
  261. param('fileName').not().matches(/(\.\.\/|\.\.\\)/),
  262. ];
  263. return validator;
  264. };
  265. actions.export.download = (req, res) => {
  266. const { fileName } = req.params;
  267. const { validationResult } = require('express-validator');
  268. const errors = validationResult(req);
  269. if (!errors.isEmpty()) {
  270. return res.status(422).json({ errors: `${fileName} is invalid. Do not use path like '../'.` });
  271. }
  272. try {
  273. const zipFile = exportService.getFile(fileName);
  274. const parameters = {
  275. ip: req.ip,
  276. endpoint: req.originalUrl,
  277. action: SupportedAction.ACTION_ADMIN_ARCHIVE_DATA_DOWNLOAD,
  278. user: req.user?._id,
  279. snapshot: {
  280. username: req.user?.username,
  281. },
  282. };
  283. crowi.activityService.createActivity(parameters);
  284. return res.download(zipFile);
  285. }
  286. catch (err) {
  287. // TODO: use ApiV3Error
  288. logger.error(err);
  289. return res.json(ApiResponse.error());
  290. }
  291. };
  292. actions.api = {};
  293. /**
  294. * save esa settings, update config cache, and response json
  295. *
  296. * @param {*} req
  297. * @param {*} res
  298. */
  299. actions.api.importerSettingEsa = async(req, res) => {
  300. const form = req.body;
  301. const { validationResult } = require('express-validator');
  302. const errors = validationResult(req);
  303. if (!errors.isEmpty()) {
  304. return res.json(ApiResponse.error('esa.io form is blank'));
  305. }
  306. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  307. importer.initializeEsaClient(); // let it run in the back aftert res
  308. const parameters = { action: SupportedAction.ACTION_ADMIN_ESA_DATA_UPDATED };
  309. activityEvent.emit('update', res.locals.activity._id, parameters);
  310. return res.json(ApiResponse.success());
  311. };
  312. /**
  313. * save qiita settings, update config cache, and response json
  314. *
  315. * @param {*} req
  316. * @param {*} res
  317. */
  318. actions.api.importerSettingQiita = async(req, res) => {
  319. const form = req.body;
  320. const { validationResult } = require('express-validator');
  321. const errors = validationResult(req);
  322. if (!errors.isEmpty()) {
  323. return res.json(ApiResponse.error('Qiita form is blank'));
  324. }
  325. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  326. importer.initializeQiitaClient(); // let it run in the back aftert res
  327. const parameters = { action: SupportedAction.ACTION_ADMIN_QIITA_DATA_UPDATED };
  328. activityEvent.emit('update', res.locals.activity._id, parameters);
  329. return res.json(ApiResponse.success());
  330. };
  331. /**
  332. * Import all posts from esa
  333. *
  334. * @param {*} req
  335. * @param {*} res
  336. */
  337. actions.api.importDataFromEsa = async(req, res) => {
  338. const user = req.user;
  339. let errors;
  340. try {
  341. errors = await importer.importDataFromEsa(user);
  342. const parameters = { action: SupportedAction.ACTION_ADMIN_ESA_DATA_IMPORTED };
  343. activityEvent.emit('update', res.locals.activity._id, parameters);
  344. }
  345. catch (err) {
  346. errors = [err];
  347. }
  348. if (errors.length > 0) {
  349. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  350. }
  351. return res.json(ApiResponse.success());
  352. };
  353. /**
  354. * Import all posts from qiita
  355. *
  356. * @param {*} req
  357. * @param {*} res
  358. */
  359. actions.api.importDataFromQiita = async(req, res) => {
  360. const user = req.user;
  361. let errors;
  362. try {
  363. errors = await importer.importDataFromQiita(user);
  364. const parameters = { action: SupportedAction.ACTION_ADMIN_QIITA_DATA_IMPORTED };
  365. activityEvent.emit('update', res.locals.activity._id, parameters);
  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. const parameters = { action: SupportedAction.ACTION_ADMIN_CONNECTION_TEST_OF_ESA_DATA };
  385. activityEvent.emit('update', res.locals.activity._id, parameters);
  386. return res.json(ApiResponse.success());
  387. }
  388. catch (err) {
  389. return res.json(ApiResponse.error(err));
  390. }
  391. };
  392. /**
  393. * Test connection to qiita and response result with json
  394. *
  395. * @param {*} req
  396. * @param {*} res
  397. */
  398. actions.api.testQiitaAPI = async(req, res) => {
  399. try {
  400. await importer.testConnectionToQiita();
  401. const parameters = { action: SupportedAction.ACTION_ADMIN_CONNECTION_TEST_OF_QIITA_DATA };
  402. activityEvent.emit('update', res.locals.activity._id, parameters);
  403. return res.json(ApiResponse.success());
  404. }
  405. catch (err) {
  406. return res.json(ApiResponse.error(err));
  407. }
  408. };
  409. actions.api.searchBuildIndex = async function(req, res) {
  410. const search = crowi.getSearcher();
  411. if (!search) {
  412. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  413. }
  414. try {
  415. search.buildIndex();
  416. }
  417. catch (err) {
  418. return res.json(ApiResponse.error(err));
  419. }
  420. return res.json(ApiResponse.success());
  421. };
  422. return actions;
  423. };