admin.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. 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 renderVar = {
  199. userGroups: [],
  200. userGroupRelations: new Map(),
  201. pager: null,
  202. };
  203. UserGroup.findUserGroupsWithPagination({ page })
  204. .then((result) => {
  205. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  206. const userGroups = result.docs;
  207. renderVar.userGroups = userGroups;
  208. renderVar.pager = pager;
  209. return userGroups.map((userGroup) => {
  210. return new Promise((resolve, reject) => {
  211. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  212. .then((relations) => {
  213. return resolve({
  214. id: userGroup._id,
  215. relatedUsers: relations.map((relation) => {
  216. return relation.relatedUser;
  217. }),
  218. });
  219. });
  220. });
  221. });
  222. })
  223. .then((allRelationsPromise) => {
  224. return Promise.all(allRelationsPromise);
  225. })
  226. .then((relations) => {
  227. for (const relation of relations) {
  228. renderVar.userGroupRelations[relation.id] = relation.relatedUsers;
  229. }
  230. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  231. return res.render('admin/user-groups', renderVar);
  232. })
  233. .catch((err) => {
  234. debug('Error on find all relations', err);
  235. return res.json(ApiResponse.error('Error'));
  236. });
  237. };
  238. // グループ詳細
  239. actions.userGroup.detail = async function(req, res) {
  240. const userGroupId = req.params.id;
  241. const userGroup = await UserGroup.findOne({ _id: userGroupId });
  242. if (userGroup == null) {
  243. logger.error('no userGroup is exists. ', userGroupId);
  244. return res.redirect('/admin/user-groups');
  245. }
  246. return res.render('admin/user-group-detail', { userGroup });
  247. };
  248. // Importer management
  249. actions.importer = {};
  250. actions.importer.api = api;
  251. api.validators = {};
  252. api.validators.importer = {};
  253. actions.importer.index = function(req, res) {
  254. const settingForm = configManager.getConfigByPrefix('crowi', 'importer:');
  255. return res.render('admin/importer', {
  256. settingForm,
  257. });
  258. };
  259. api.validators.importer.esa = function() {
  260. const validator = [
  261. check('importer:esa:team_name').not().isEmpty().withMessage('Error. Empty esa:team_name'),
  262. check('importer:esa:access_token').not().isEmpty().withMessage('Error. Empty esa:access_token'),
  263. ];
  264. return validator;
  265. };
  266. api.validators.importer.qiita = function() {
  267. const validator = [
  268. check('importer:qiita:team_name').not().isEmpty().withMessage('Error. Empty qiita:team_name'),
  269. check('importer:qiita:access_token').not().isEmpty().withMessage('Error. Empty qiita:access_token'),
  270. ];
  271. return validator;
  272. };
  273. // Export management
  274. actions.export = {};
  275. actions.export.api = api;
  276. api.validators.export = {};
  277. actions.export.index = (req, res) => {
  278. return res.render('admin/export');
  279. };
  280. api.validators.export.download = function() {
  281. const validator = [
  282. // https://regex101.com/r/mD4eZs/6
  283. // prevent from pass traversal attack
  284. param('fileName').not().matches(/(\.\.\/|\.\.\\)/),
  285. ];
  286. return validator;
  287. };
  288. actions.export.download = (req, res) => {
  289. const { fileName } = req.params;
  290. const { validationResult } = require('express-validator');
  291. const errors = validationResult(req);
  292. if (!errors.isEmpty()) {
  293. return res.status(422).json({ errors: `${fileName} is invalid. Do not use path like '../'.` });
  294. }
  295. try {
  296. const zipFile = exportService.getFile(fileName);
  297. return res.download(zipFile);
  298. }
  299. catch (err) {
  300. // TODO: use ApiV3Error
  301. logger.error(err);
  302. return res.json(ApiResponse.error());
  303. }
  304. };
  305. actions.api = {};
  306. /**
  307. * save esa settings, update config cache, and response json
  308. *
  309. * @param {*} req
  310. * @param {*} res
  311. */
  312. actions.api.importerSettingEsa = async(req, res) => {
  313. const form = req.body;
  314. const { validationResult } = require('express-validator');
  315. const errors = validationResult(req);
  316. if (!errors.isEmpty()) {
  317. return res.json(ApiResponse.error('esa.io form is blank'));
  318. }
  319. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  320. importer.initializeEsaClient(); // let it run in the back aftert res
  321. return res.json(ApiResponse.success());
  322. };
  323. /**
  324. * save qiita settings, update config cache, and response json
  325. *
  326. * @param {*} req
  327. * @param {*} res
  328. */
  329. actions.api.importerSettingQiita = async(req, res) => {
  330. const form = req.body;
  331. const { validationResult } = require('express-validator');
  332. const errors = validationResult(req);
  333. if (!errors.isEmpty()) {
  334. return res.json(ApiResponse.error('Qiita form is blank'));
  335. }
  336. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  337. importer.initializeQiitaClient(); // let it run in the back aftert res
  338. return res.json(ApiResponse.success());
  339. };
  340. /**
  341. * Import all posts from esa
  342. *
  343. * @param {*} req
  344. * @param {*} res
  345. */
  346. actions.api.importDataFromEsa = async(req, res) => {
  347. const user = req.user;
  348. let errors;
  349. try {
  350. errors = await importer.importDataFromEsa(user);
  351. }
  352. catch (err) {
  353. errors = [err];
  354. }
  355. if (errors.length > 0) {
  356. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  357. }
  358. return res.json(ApiResponse.success());
  359. };
  360. /**
  361. * Import all posts from qiita
  362. *
  363. * @param {*} req
  364. * @param {*} res
  365. */
  366. actions.api.importDataFromQiita = async(req, res) => {
  367. const user = req.user;
  368. let errors;
  369. try {
  370. errors = await importer.importDataFromQiita(user);
  371. }
  372. catch (err) {
  373. errors = [err];
  374. }
  375. if (errors.length > 0) {
  376. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  377. }
  378. return res.json(ApiResponse.success());
  379. };
  380. /**
  381. * Test connection to esa and response result with json
  382. *
  383. * @param {*} req
  384. * @param {*} res
  385. */
  386. actions.api.testEsaAPI = async(req, res) => {
  387. try {
  388. await importer.testConnectionToEsa();
  389. return res.json(ApiResponse.success());
  390. }
  391. catch (err) {
  392. return res.json(ApiResponse.error(err));
  393. }
  394. };
  395. /**
  396. * Test connection to qiita and response result with json
  397. *
  398. * @param {*} req
  399. * @param {*} res
  400. */
  401. actions.api.testQiitaAPI = async(req, res) => {
  402. try {
  403. await importer.testConnectionToQiita();
  404. return res.json(ApiResponse.success());
  405. }
  406. catch (err) {
  407. return res.json(ApiResponse.error(err));
  408. }
  409. };
  410. actions.api.searchBuildIndex = async function(req, res) {
  411. const search = crowi.getSearcher();
  412. if (!search) {
  413. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  414. }
  415. try {
  416. search.buildIndex();
  417. }
  418. catch (err) {
  419. return res.json(ApiResponse.error(err));
  420. }
  421. return res.json(ApiResponse.success());
  422. };
  423. actions.notFound = {};
  424. actions.notFound.index = function(req, res) {
  425. return res.render('admin/not_found');
  426. };
  427. return actions;
  428. };