admin.js 14 KB

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