admin.js 14 KB

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