admin.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. import loggerFactory from '~/utils/logger';
  2. const logger = loggerFactory('growi:routes:admin');
  3. const debug = require('debug')('growi:routes:admin');
  4. /* eslint-disable no-use-before-define */
  5. module.exports = function(crowi, app) {
  6. const models = crowi.models;
  7. const UserGroup = models.UserGroup;
  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. const isWikiModeForced = aclService.isWikiModeForced();
  85. const guestModeValue = aclService.getGuestModeValue();
  86. return res.render('admin/security', {
  87. isWikiModeForced,
  88. guestModeValue,
  89. });
  90. };
  91. // app.get('/admin/markdown' , admin.markdown.index);
  92. actions.markdown = {};
  93. actions.markdown.index = function(req, res) {
  94. const markdownSetting = configManager.getConfigByPrefix('markdown', 'markdown:');
  95. return res.render('admin/markdown', {
  96. markdownSetting,
  97. recommendedWhitelist,
  98. });
  99. };
  100. // app.get('/admin/customize' , admin.customize.index);
  101. actions.customize = {};
  102. actions.customize.index = function(req, res) {
  103. const settingForm = configManager.getConfigByPrefix('crowi', 'customize:');
  104. // TODO delete after apiV3
  105. /* eslint-disable quote-props, no-multi-spaces */
  106. const highlightJsCssSelectorOptions = {
  107. 'github': { name: '[Light] GitHub', border: false },
  108. 'github-gist': { name: '[Light] GitHub Gist', border: true },
  109. 'atom-one-light': { name: '[Light] Atom One Light', border: true },
  110. 'xcode': { name: '[Light] Xcode', border: true },
  111. 'vs': { name: '[Light] Vs', border: true },
  112. 'atom-one-dark': { name: '[Dark] Atom One Dark', border: false },
  113. 'hybrid': { name: '[Dark] Hybrid', border: false },
  114. 'monokai': { name: '[Dark] Monokai', border: false },
  115. 'tomorrow-night': { name: '[Dark] Tomorrow Night', border: false },
  116. 'vs2015': { name: '[Dark] Vs 2015', border: false },
  117. };
  118. /* eslint-enable quote-props, no-multi-spaces */
  119. return res.render('admin/customize', {
  120. settingForm,
  121. highlightJsCssSelectorOptions,
  122. });
  123. };
  124. // app.get('/admin/notification' , admin.notification.index);
  125. actions.notification = {};
  126. actions.notification.index = async(req, res) => {
  127. return res.render('admin/notification');
  128. };
  129. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  130. actions.notification.slackAuth = function(req, res) {
  131. const code = req.query.code;
  132. const { t } = req;
  133. if (!code || !slackIntegrationService.isSlackConfigured()) {
  134. return res.redirect('/admin/notification');
  135. }
  136. const slack = crowi.slack;
  137. slack.getOauthAccessToken(code)
  138. .then(async(data) => {
  139. debug('oauth response', data);
  140. try {
  141. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': data.access_token });
  142. req.flash('successMessage', [t('message.successfully_connected')]);
  143. }
  144. catch (err) {
  145. req.flash('errorMessage', [t('message.fail_to_save_access_token')]);
  146. }
  147. return res.redirect('/admin/notification');
  148. })
  149. .catch((err) => {
  150. debug('oauth response ERROR', err);
  151. req.flash('errorMessage', [t('message.fail_to_fetch_access_token')]);
  152. return res.redirect('/admin/notification');
  153. });
  154. };
  155. // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
  156. actions.notification.disconnectFromSlack = async function(req, res) {
  157. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': '' });
  158. req.flash('successMessage', [req.t('successfully_disconnected')]);
  159. return res.redirect('/admin/notification');
  160. };
  161. actions.globalNotification = {};
  162. actions.globalNotification.detail = async(req, res) => {
  163. const notificationSettingId = req.params.id;
  164. let globalNotification;
  165. if (notificationSettingId) {
  166. try {
  167. globalNotification = await GlobalNotificationSetting.findOne({ _id: notificationSettingId });
  168. }
  169. catch (err) {
  170. logger.error(`Error in finding a global notification setting with {_id: ${notificationSettingId}}`);
  171. }
  172. }
  173. return res.render('admin/global-notification-detail', { globalNotification });
  174. };
  175. actions.search = {};
  176. actions.search.index = function(req, res) {
  177. return res.render('admin/search', {});
  178. };
  179. actions.user = {};
  180. actions.user.index = async function(req, res) {
  181. return res.render('admin/users');
  182. };
  183. actions.externalAccount = {};
  184. actions.externalAccount.index = function(req, res) {
  185. return res.render('admin/external-accounts');
  186. };
  187. actions.slackIntegrationLegacy = {};
  188. actions.slackIntegrationLegacy = function(req, res) {
  189. return res.render('admin/slack-integration-legacy');
  190. };
  191. actions.slackIntegration = {};
  192. actions.slackIntegration = function(req, res) {
  193. return res.render('admin/slack-integration');
  194. };
  195. actions.userGroup = {};
  196. actions.userGroup.index = function(req, res) {
  197. const page = parseInt(req.query.page) || 1;
  198. const isAclEnabled = aclService.isAclEnabled();
  199. const renderVar = {
  200. userGroups: [],
  201. userGroupRelations: new Map(),
  202. pager: null,
  203. isAclEnabled,
  204. };
  205. UserGroup.findUserGroupsWithPagination({ page })
  206. .then((result) => {
  207. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  208. const userGroups = result.docs;
  209. renderVar.userGroups = userGroups;
  210. renderVar.pager = pager;
  211. return userGroups.map((userGroup) => {
  212. return new Promise((resolve, reject) => {
  213. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  214. .then((relations) => {
  215. return resolve({
  216. id: userGroup._id,
  217. relatedUsers: relations.map((relation) => {
  218. return relation.relatedUser;
  219. }),
  220. });
  221. });
  222. });
  223. });
  224. })
  225. .then((allRelationsPromise) => {
  226. return Promise.all(allRelationsPromise);
  227. })
  228. .then((relations) => {
  229. for (const relation of relations) {
  230. renderVar.userGroupRelations[relation.id] = relation.relatedUsers;
  231. }
  232. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  233. return res.render('admin/user-groups', renderVar);
  234. })
  235. .catch((err) => {
  236. debug('Error on find all relations', err);
  237. return res.json(ApiResponse.error('Error'));
  238. });
  239. };
  240. // グループ詳細
  241. actions.userGroup.detail = async function(req, res) {
  242. const userGroupId = req.params.id;
  243. const userGroup = await UserGroup.findOne({ _id: userGroupId });
  244. if (userGroup == null) {
  245. logger.error('no userGroup is exists. ', userGroupId);
  246. return res.redirect('/admin/user-groups');
  247. }
  248. return res.render('admin/user-group-detail', { userGroup });
  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. return res.download(zipFile);
  300. }
  301. catch (err) {
  302. // TODO: use ApiV3Error
  303. logger.error(err);
  304. return res.json(ApiResponse.error());
  305. }
  306. };
  307. actions.api = {};
  308. /**
  309. * save esa settings, update config cache, and response json
  310. *
  311. * @param {*} req
  312. * @param {*} res
  313. */
  314. actions.api.importerSettingEsa = async(req, res) => {
  315. const form = req.body;
  316. const { validationResult } = require('express-validator');
  317. const errors = validationResult(req);
  318. if (!errors.isEmpty()) {
  319. return res.json(ApiResponse.error('esa.io form is blank'));
  320. }
  321. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  322. importer.initializeEsaClient(); // let it run in the back aftert res
  323. return res.json(ApiResponse.success());
  324. };
  325. /**
  326. * save qiita settings, update config cache, and response json
  327. *
  328. * @param {*} req
  329. * @param {*} res
  330. */
  331. actions.api.importerSettingQiita = async(req, res) => {
  332. const form = req.body;
  333. const { validationResult } = require('express-validator');
  334. const errors = validationResult(req);
  335. if (!errors.isEmpty()) {
  336. return res.json(ApiResponse.error('Qiita form is blank'));
  337. }
  338. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  339. importer.initializeQiitaClient(); // let it run in the back aftert res
  340. return res.json(ApiResponse.success());
  341. };
  342. /**
  343. * Import all posts from esa
  344. *
  345. * @param {*} req
  346. * @param {*} res
  347. */
  348. actions.api.importDataFromEsa = async(req, res) => {
  349. const user = req.user;
  350. let errors;
  351. try {
  352. errors = await importer.importDataFromEsa(user);
  353. }
  354. catch (err) {
  355. errors = [err];
  356. }
  357. if (errors.length > 0) {
  358. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  359. }
  360. return res.json(ApiResponse.success());
  361. };
  362. /**
  363. * Import all posts from qiita
  364. *
  365. * @param {*} req
  366. * @param {*} res
  367. */
  368. actions.api.importDataFromQiita = async(req, res) => {
  369. const user = req.user;
  370. let errors;
  371. try {
  372. errors = await importer.importDataFromQiita(user);
  373. }
  374. catch (err) {
  375. errors = [err];
  376. }
  377. if (errors.length > 0) {
  378. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  379. }
  380. return res.json(ApiResponse.success());
  381. };
  382. /**
  383. * Test connection to esa and response result with json
  384. *
  385. * @param {*} req
  386. * @param {*} res
  387. */
  388. actions.api.testEsaAPI = async(req, res) => {
  389. try {
  390. await importer.testConnectionToEsa();
  391. return res.json(ApiResponse.success());
  392. }
  393. catch (err) {
  394. return res.json(ApiResponse.error(err));
  395. }
  396. };
  397. /**
  398. * Test connection to qiita and response result with json
  399. *
  400. * @param {*} req
  401. * @param {*} res
  402. */
  403. actions.api.testQiitaAPI = async(req, res) => {
  404. try {
  405. await importer.testConnectionToQiita();
  406. return res.json(ApiResponse.success());
  407. }
  408. catch (err) {
  409. return res.json(ApiResponse.error(err));
  410. }
  411. };
  412. actions.api.searchBuildIndex = async function(req, res) {
  413. const search = crowi.getSearcher();
  414. if (!search) {
  415. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  416. }
  417. try {
  418. search.buildIndex();
  419. }
  420. catch (err) {
  421. return res.json(ApiResponse.error(err));
  422. }
  423. return res.json(ApiResponse.success());
  424. };
  425. actions.notFound = {};
  426. actions.notFound.index = function(req, res) {
  427. return res.render('admin/not_found');
  428. };
  429. return actions;
  430. };