admin.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. if (!code || !slackNotificationService.hasSlackConfig()) {
  143. return res.redirect('/admin/notification');
  144. }
  145. const slack = crowi.slack;
  146. slack.getOauthAccessToken(code)
  147. .then(async(data) => {
  148. debug('oauth response', data);
  149. try {
  150. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': data.access_token });
  151. req.flash('successMessage', ['Successfully Connected!']);
  152. }
  153. catch (err) {
  154. req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
  155. }
  156. return res.redirect('/admin/notification');
  157. })
  158. .catch((err) => {
  159. debug('oauth response ERROR', err);
  160. req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
  161. return res.redirect('/admin/notification');
  162. });
  163. };
  164. // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
  165. actions.notification.disconnectFromSlack = async function(req, res) {
  166. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': '' });
  167. req.flash('successMessage', ['Successfully Disconnected!']);
  168. return res.redirect('/admin/notification');
  169. };
  170. actions.globalNotification = {};
  171. actions.globalNotification.detail = async(req, res) => {
  172. const notificationSettingId = req.params.id;
  173. let globalNotification;
  174. if (notificationSettingId) {
  175. try {
  176. globalNotification = await GlobalNotificationSetting.findOne({ _id: notificationSettingId });
  177. }
  178. catch (err) {
  179. logger.error(`Error in finding a global notification setting with {_id: ${notificationSettingId}}`);
  180. }
  181. }
  182. return res.render('admin/global-notification-detail', { globalNotification });
  183. };
  184. actions.search = {};
  185. actions.search.index = function(req, res) {
  186. return res.render('admin/search', {});
  187. };
  188. actions.user = {};
  189. actions.user.index = async function(req, res) {
  190. return res.render('admin/users');
  191. };
  192. actions.externalAccount = {};
  193. actions.externalAccount.index = function(req, res) {
  194. return res.render('admin/external-accounts');
  195. };
  196. actions.userGroup = {};
  197. actions.userGroup.index = function(req, res) {
  198. const page = parseInt(req.query.page) || 1;
  199. const isAclEnabled = aclService.isAclEnabled();
  200. const renderVar = {
  201. userGroups: [],
  202. userGroupRelations: new Map(),
  203. pager: null,
  204. isAclEnabled,
  205. };
  206. UserGroup.findUserGroupsWithPagination({ page })
  207. .then((result) => {
  208. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  209. const userGroups = result.docs;
  210. renderVar.userGroups = userGroups;
  211. renderVar.pager = pager;
  212. return userGroups.map((userGroup) => {
  213. return new Promise((resolve, reject) => {
  214. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  215. .then((relations) => {
  216. return resolve({
  217. id: userGroup._id,
  218. relatedUsers: relations.map((relation) => {
  219. return relation.relatedUser;
  220. }),
  221. });
  222. });
  223. });
  224. });
  225. })
  226. .then((allRelationsPromise) => {
  227. return Promise.all(allRelationsPromise);
  228. })
  229. .then((relations) => {
  230. for (const relation of relations) {
  231. renderVar.userGroupRelations[relation.id] = relation.relatedUsers;
  232. }
  233. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  234. return res.render('admin/user-groups', renderVar);
  235. })
  236. .catch((err) => {
  237. debug('Error on find all relations', err);
  238. return res.json(ApiResponse.error('Error'));
  239. });
  240. };
  241. // グループ詳細
  242. actions.userGroup.detail = async function(req, res) {
  243. const userGroupId = req.params.id;
  244. const userGroup = await UserGroup.findOne({ _id: userGroupId });
  245. if (userGroup == null) {
  246. logger.error('no userGroup is exists. ', userGroupId);
  247. return res.redirect('/admin/user-groups');
  248. }
  249. return res.render('admin/user-group-detail', { userGroup });
  250. };
  251. // Importer management
  252. actions.importer = {};
  253. actions.importer.api = api;
  254. api.validators = {};
  255. api.validators.importer = {};
  256. actions.importer.index = function(req, res) {
  257. const settingForm = configManager.getConfigByPrefix('crowi', 'importer:');
  258. return res.render('admin/importer', {
  259. settingForm,
  260. });
  261. };
  262. api.validators.importer.esa = function() {
  263. const validator = [
  264. check('importer:esa:team_name').not().isEmpty().withMessage('Error. Empty esa:team_name'),
  265. check('importer:esa:access_token').not().isEmpty().withMessage('Error. Empty esa:access_token'),
  266. ];
  267. return validator;
  268. };
  269. api.validators.importer.qiita = function() {
  270. const validator = [
  271. check('importer:qiita:team_name').not().isEmpty().withMessage('Error. Empty qiita:team_name'),
  272. check('importer:qiita:access_token').not().isEmpty().withMessage('Error. Empty qiita:access_token'),
  273. ];
  274. return validator;
  275. };
  276. // Export management
  277. actions.export = {};
  278. actions.export.index = (req, res) => {
  279. return res.render('admin/export');
  280. };
  281. actions.export.download = (req, res) => {
  282. // TODO: add express validator
  283. const { fileName } = req.params;
  284. try {
  285. const zipFile = exportService.getFile(fileName);
  286. return res.download(zipFile);
  287. }
  288. catch (err) {
  289. // TODO: use ApiV3Error
  290. logger.error(err);
  291. return res.json(ApiResponse.error());
  292. }
  293. };
  294. actions.api = {};
  295. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  296. actions.api.usersSearch = function(req, res) {
  297. const User = crowi.model('User');
  298. const email = req.query.email;
  299. User.findUsersByPartOfEmail(email, {})
  300. .then((users) => {
  301. const result = {
  302. data: users,
  303. };
  304. return res.json(ApiResponse.success(result));
  305. })
  306. .catch((err) => {
  307. return res.json(ApiResponse.error());
  308. });
  309. };
  310. /**
  311. * save esa settings, update config cache, and response json
  312. *
  313. * @param {*} req
  314. * @param {*} res
  315. */
  316. actions.api.importerSettingEsa = async(req, res) => {
  317. const form = req.body;
  318. const { validationResult } = require('express-validator');
  319. const errors = validationResult(req);
  320. if (!errors.isEmpty()) {
  321. return res.json(ApiResponse.error('esa.io form is blank'));
  322. }
  323. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  324. importer.initializeEsaClient(); // let it run in the back aftert res
  325. return res.json(ApiResponse.success());
  326. };
  327. /**
  328. * save qiita settings, update config cache, and response json
  329. *
  330. * @param {*} req
  331. * @param {*} res
  332. */
  333. actions.api.importerSettingQiita = async(req, res) => {
  334. const form = req.body;
  335. const { validationResult } = require('express-validator');
  336. const errors = validationResult(req);
  337. if (!errors.isEmpty()) {
  338. return res.json(ApiResponse.error('Qiita form is blank'));
  339. }
  340. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  341. importer.initializeQiitaClient(); // let it run in the back aftert res
  342. return res.json(ApiResponse.success());
  343. };
  344. /**
  345. * Import all posts from esa
  346. *
  347. * @param {*} req
  348. * @param {*} res
  349. */
  350. actions.api.importDataFromEsa = async(req, res) => {
  351. const user = req.user;
  352. let errors;
  353. try {
  354. errors = await importer.importDataFromEsa(user);
  355. }
  356. catch (err) {
  357. errors = [err];
  358. }
  359. if (errors.length > 0) {
  360. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  361. }
  362. return res.json(ApiResponse.success());
  363. };
  364. /**
  365. * Import all posts from qiita
  366. *
  367. * @param {*} req
  368. * @param {*} res
  369. */
  370. actions.api.importDataFromQiita = async(req, res) => {
  371. const user = req.user;
  372. let errors;
  373. try {
  374. errors = await importer.importDataFromQiita(user);
  375. }
  376. catch (err) {
  377. errors = [err];
  378. }
  379. if (errors.length > 0) {
  380. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  381. }
  382. return res.json(ApiResponse.success());
  383. };
  384. /**
  385. * Test connection to esa and response result with json
  386. *
  387. * @param {*} req
  388. * @param {*} res
  389. */
  390. actions.api.testEsaAPI = async(req, res) => {
  391. try {
  392. await importer.testConnectionToEsa();
  393. return res.json(ApiResponse.success());
  394. }
  395. catch (err) {
  396. return res.json(ApiResponse.error(err));
  397. }
  398. };
  399. /**
  400. * Test connection to qiita and response result with json
  401. *
  402. * @param {*} req
  403. * @param {*} res
  404. */
  405. actions.api.testQiitaAPI = async(req, res) => {
  406. try {
  407. await importer.testConnectionToQiita();
  408. return res.json(ApiResponse.success());
  409. }
  410. catch (err) {
  411. return res.json(ApiResponse.error(err));
  412. }
  413. };
  414. actions.api.searchBuildIndex = async function(req, res) {
  415. const search = crowi.getSearcher();
  416. if (!search) {
  417. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  418. }
  419. try {
  420. search.buildIndex();
  421. }
  422. catch (err) {
  423. return res.json(ApiResponse.error(err));
  424. }
  425. return res.json(ApiResponse.success());
  426. };
  427. return actions;
  428. };