admin.js 14 KB

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