admin.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  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 User = models.User;
  7. const ExternalAccount = models.ExternalAccount;
  8. const UserGroup = models.UserGroup;
  9. const UserGroupRelation = models.UserGroupRelation;
  10. const GlobalNotificationSetting = models.GlobalNotificationSetting;
  11. const GlobalNotificationMailSetting = models.GlobalNotificationMailSetting;
  12. const GlobalNotificationSlackSetting = models.GlobalNotificationSlackSetting; // eslint-disable-line no-unused-vars
  13. const {
  14. configManager,
  15. aclService,
  16. slackNotificationService,
  17. customizeService,
  18. exportService,
  19. } = crowi;
  20. const recommendedWhitelist = require('@commons/service/xss/recommended-whitelist');
  21. const PluginUtils = require('../plugins/plugin-utils');
  22. const ApiResponse = require('../util/apiResponse');
  23. const importer = require('../util/importer')(crowi);
  24. const searchEvent = crowi.event('search');
  25. const pluginUtils = new PluginUtils();
  26. const MAX_PAGE_LIST = 50;
  27. const actions = {};
  28. const { check } = require('express-validator/check');
  29. const api = {};
  30. function createPager(total, limit, page, pagesCount, maxPageList) {
  31. const pager = {
  32. page,
  33. pagesCount,
  34. pages: [],
  35. total,
  36. previous: null,
  37. previousDots: false,
  38. next: null,
  39. nextDots: false,
  40. };
  41. if (page > 1) {
  42. pager.previous = page - 1;
  43. }
  44. if (page < pagesCount) {
  45. pager.next = page + 1;
  46. }
  47. let pagerMin = Math.max(1, Math.ceil(page - maxPageList / 2));
  48. let pagerMax = Math.min(pagesCount, Math.floor(page + maxPageList / 2));
  49. if (pagerMin === 1) {
  50. if (MAX_PAGE_LIST < pagesCount) {
  51. pagerMax = MAX_PAGE_LIST;
  52. }
  53. else {
  54. pagerMax = pagesCount;
  55. }
  56. }
  57. if (pagerMax === pagesCount) {
  58. if ((pagerMax - MAX_PAGE_LIST) < 1) {
  59. pagerMin = 1;
  60. }
  61. else {
  62. pagerMin = pagerMax - MAX_PAGE_LIST;
  63. }
  64. }
  65. pager.previousDots = null;
  66. if (pagerMin > 1) {
  67. pager.previousDots = true;
  68. }
  69. pager.nextDots = null;
  70. if (pagerMax < pagesCount) {
  71. pager.nextDots = true;
  72. }
  73. for (let i = pagerMin; i <= pagerMax; i++) {
  74. pager.pages.push(i);
  75. }
  76. return pager;
  77. }
  78. actions.index = function(req, res) {
  79. return res.render('admin/index', {
  80. plugins: pluginUtils.listPlugins(crowi.rootDir),
  81. });
  82. };
  83. // app.get('/admin/app' , admin.app.index);
  84. actions.app = {};
  85. actions.app.index = function(req, res) {
  86. return res.render('admin/app');
  87. };
  88. actions.app.settingUpdate = function(req, res) {
  89. };
  90. // app.get('/admin/security' , admin.security.index);
  91. actions.security = {};
  92. actions.security.index = function(req, res) {
  93. const isWikiModeForced = aclService.isWikiModeForced();
  94. const guestModeValue = aclService.getGuestModeValue();
  95. return res.render('admin/security', {
  96. isWikiModeForced,
  97. guestModeValue,
  98. });
  99. };
  100. // app.get('/admin/markdown' , admin.markdown.index);
  101. actions.markdown = {};
  102. actions.markdown.index = function(req, res) {
  103. const markdownSetting = configManager.getConfigByPrefix('markdown', 'markdown:');
  104. return res.render('admin/markdown', {
  105. markdownSetting,
  106. recommendedWhitelist,
  107. });
  108. };
  109. // app.post('/admin/markdown/lineBreaksSetting' , admin.markdown.lineBreaksSetting);
  110. actions.markdown.lineBreaksSetting = async function(req, res) {
  111. const array = req.body.params;
  112. try {
  113. await configManager.updateConfigsInTheSameNamespace('markdown', array);
  114. return res.json(ApiResponse.success());
  115. }
  116. catch (err) {
  117. return res.json(ApiResponse.error(err));
  118. }
  119. };
  120. // app.post('/admin/markdown/presentationSetting' , admin.markdown.presentationSetting);
  121. actions.markdown.presentationSetting = async function(req, res) {
  122. const markdownSetting = req.form.markdownSetting;
  123. if (req.form.isValid) {
  124. await configManager.updateConfigsInTheSameNamespace('markdown', markdownSetting);
  125. req.flash('successMessage', ['Successfully updated!']);
  126. }
  127. else {
  128. req.flash('errorMessage', req.form.errors);
  129. }
  130. return res.redirect('/admin/markdown');
  131. };
  132. // app.post('/admin/markdown/xss-setting' , admin.markdown.xssSetting);
  133. actions.markdown.xssSetting = async function(req, res) {
  134. const xssSetting = req.form.markdownSetting;
  135. xssSetting['markdown:xss:tagWhiteList'] = csvToArray(xssSetting['markdown:xss:tagWhiteList']);
  136. xssSetting['markdown:xss:attrWhiteList'] = csvToArray(xssSetting['markdown:xss:attrWhiteList']);
  137. if (req.form.isValid) {
  138. await configManager.updateConfigsInTheSameNamespace('markdown', xssSetting);
  139. req.flash('successMessage', ['Successfully updated!']);
  140. }
  141. else {
  142. req.flash('errorMessage', req.form.errors);
  143. }
  144. return res.redirect('/admin/markdown');
  145. };
  146. const csvToArray = (string) => {
  147. const array = string.split(',');
  148. return array.map((item) => { return item.trim() });
  149. };
  150. // app.get('/admin/customize' , admin.customize.index);
  151. actions.customize = {};
  152. actions.customize.index = function(req, res) {
  153. const settingForm = configManager.getConfigByPrefix('crowi', 'customize:');
  154. /* eslint-disable quote-props, no-multi-spaces */
  155. const highlightJsCssSelectorOptions = {
  156. 'github': { name: '[Light] GitHub', border: false },
  157. 'github-gist': { name: '[Light] GitHub Gist', border: true },
  158. 'atom-one-light': { name: '[Light] Atom One Light', border: true },
  159. 'xcode': { name: '[Light] Xcode', border: true },
  160. 'vs': { name: '[Light] Vs', border: true },
  161. 'atom-one-dark': { name: '[Dark] Atom One Dark', border: false },
  162. 'hybrid': { name: '[Dark] Hybrid', border: false },
  163. 'monokai': { name: '[Dark] Monokai', border: false },
  164. 'tomorrow-night': { name: '[Dark] Tomorrow Night', border: false },
  165. 'vs2015': { name: '[Dark] Vs 2015', border: false },
  166. };
  167. /* eslint-enable quote-props, no-multi-spaces */
  168. return res.render('admin/customize', {
  169. settingForm,
  170. highlightJsCssSelectorOptions,
  171. });
  172. };
  173. // app.get('/admin/notification' , admin.notification.index);
  174. actions.notification = {};
  175. actions.notification.index = async(req, res) => {
  176. const UpdatePost = crowi.model('UpdatePost');
  177. let slackSetting = configManager.getConfigByPrefix('notification', 'slack:');
  178. const hasSlackIwhUrl = !!configManager.getConfig('notification', 'slack:incomingWebhookUrl');
  179. const hasSlackToken = !!configManager.getConfig('notification', 'slack:token');
  180. if (!hasSlackIwhUrl) {
  181. slackSetting['slack:incomingWebhookUrl'] = '';
  182. }
  183. if (req.session.slackSetting) {
  184. slackSetting = req.session.slackSetting;
  185. req.session.slackSetting = null;
  186. }
  187. const globalNotifications = await GlobalNotificationSetting.findAll();
  188. const userNotifications = await UpdatePost.findAll();
  189. return res.render('admin/notification', {
  190. userNotifications,
  191. slackSetting,
  192. hasSlackIwhUrl,
  193. hasSlackToken,
  194. globalNotifications,
  195. });
  196. };
  197. // app.post('/admin/notification/slackSetting' , admin.notification.slackauth);
  198. actions.notification.slackSetting = async function(req, res) {
  199. const slackSetting = req.form.slackSetting;
  200. if (req.form.isValid) {
  201. await configManager.updateConfigsInTheSameNamespace('notification', slackSetting);
  202. req.flash('successMessage', ['Successfully Updated!']);
  203. // Re-setup
  204. crowi.setupSlack().then(() => {
  205. });
  206. }
  207. else {
  208. req.flash('errorMessage', req.form.errors);
  209. }
  210. return res.redirect('/admin/notification');
  211. };
  212. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  213. actions.notification.slackAuth = function(req, res) {
  214. const code = req.query.code;
  215. if (!code || !slackNotificationService.hasSlackConfig()) {
  216. return res.redirect('/admin/notification');
  217. }
  218. const slack = crowi.slack;
  219. slack.getOauthAccessToken(code)
  220. .then(async(data) => {
  221. debug('oauth response', data);
  222. try {
  223. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': data.access_token });
  224. req.flash('successMessage', ['Successfully Connected!']);
  225. }
  226. catch (err) {
  227. req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
  228. }
  229. return res.redirect('/admin/notification');
  230. })
  231. .catch((err) => {
  232. debug('oauth response ERROR', err);
  233. req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
  234. return res.redirect('/admin/notification');
  235. });
  236. };
  237. // app.post('/admin/notification/slackIwhSetting' , admin.notification.slackIwhSetting);
  238. actions.notification.slackIwhSetting = async function(req, res) {
  239. const slackIwhSetting = req.form.slackIwhSetting;
  240. if (req.form.isValid) {
  241. await configManager.updateConfigsInTheSameNamespace('notification', slackIwhSetting);
  242. req.flash('successMessage', ['Successfully Updated!']);
  243. // Re-setup
  244. crowi.setupSlack().then(() => {
  245. return res.redirect('/admin/notification#slack-incoming-webhooks');
  246. });
  247. }
  248. else {
  249. req.flash('errorMessage', req.form.errors);
  250. return res.redirect('/admin/notification#slack-incoming-webhooks');
  251. }
  252. };
  253. // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
  254. actions.notification.disconnectFromSlack = async function(req, res) {
  255. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': '' });
  256. req.flash('successMessage', ['Successfully Disconnected!']);
  257. return res.redirect('/admin/notification');
  258. };
  259. actions.globalNotification = {};
  260. actions.globalNotification.detail = async(req, res) => {
  261. const notificationSettingId = req.params.id;
  262. const renderVars = {};
  263. if (notificationSettingId) {
  264. try {
  265. renderVars.setting = await GlobalNotificationSetting.findOne({ _id: notificationSettingId });
  266. }
  267. catch (err) {
  268. logger.error(`Error in finding a global notification setting with {_id: ${notificationSettingId}}`);
  269. }
  270. }
  271. return res.render('admin/global-notification-detail', renderVars);
  272. };
  273. actions.globalNotification.create = (req, res) => {
  274. const form = req.form.notificationGlobal;
  275. let setting;
  276. switch (form.notifyToType) {
  277. case GlobalNotificationSetting.TYPE.MAIL:
  278. setting = new GlobalNotificationMailSetting(crowi);
  279. setting.toEmail = form.toEmail;
  280. break;
  281. case GlobalNotificationSetting.TYPE.SLACK:
  282. setting = new GlobalNotificationSlackSetting(crowi);
  283. setting.slackChannels = form.slackChannels;
  284. break;
  285. default:
  286. logger.error('GlobalNotificationSetting Type Error: undefined type');
  287. req.flash('errorMessage', 'Error occurred in creating a new global notification setting: undefined notification type');
  288. return res.redirect('/admin/notification#global-notification');
  289. }
  290. setting.triggerPath = form.triggerPath;
  291. setting.triggerEvents = getNotificationEvents(form);
  292. setting.save();
  293. return res.redirect('/admin/notification#global-notification');
  294. };
  295. actions.globalNotification.update = async(req, res) => {
  296. const form = req.form.notificationGlobal;
  297. const models = {
  298. [GlobalNotificationSetting.TYPE.MAIL]: GlobalNotificationMailSetting,
  299. [GlobalNotificationSetting.TYPE.SLACK]: GlobalNotificationSlackSetting,
  300. };
  301. let setting = await GlobalNotificationSetting.findOne({ _id: form.id });
  302. setting = setting.toObject();
  303. // when switching from one type to another,
  304. // remove toEmail from slack setting and slackChannels from mail setting
  305. if (setting.__t !== form.notifyToType) {
  306. setting = models[setting.__t].hydrate(setting);
  307. setting.toEmail = undefined;
  308. setting.slackChannels = undefined;
  309. await setting.save();
  310. setting = setting.toObject();
  311. }
  312. switch (form.notifyToType) {
  313. case GlobalNotificationSetting.TYPE.MAIL:
  314. setting = GlobalNotificationMailSetting.hydrate(setting);
  315. setting.toEmail = form.toEmail;
  316. break;
  317. case GlobalNotificationSetting.TYPE.SLACK:
  318. setting = GlobalNotificationSlackSetting.hydrate(setting);
  319. setting.slackChannels = form.slackChannels;
  320. break;
  321. default:
  322. logger.error('GlobalNotificationSetting Type Error: undefined type');
  323. req.flash('errorMessage', 'Error occurred in updating the global notification setting: undefined notification type');
  324. return res.redirect('/admin/notification#global-notification');
  325. }
  326. setting.__t = form.notifyToType;
  327. setting.triggerPath = form.triggerPath;
  328. setting.triggerEvents = getNotificationEvents(form);
  329. await setting.save();
  330. return res.redirect('/admin/notification#global-notification');
  331. };
  332. actions.globalNotification.remove = async(req, res) => {
  333. const id = req.params.id;
  334. try {
  335. await GlobalNotificationSetting.findOneAndRemove({ _id: id });
  336. return res.redirect('/admin/notification#global-notification');
  337. }
  338. catch (err) {
  339. req.flash('errorMessage', 'Error in deleting global notification setting');
  340. return res.redirect('/admin/notification#global-notification');
  341. }
  342. };
  343. const getNotificationEvents = (form) => {
  344. const triggerEvents = [];
  345. const triggerEventKeys = Object.keys(form).filter((key) => { return key.match(/^triggerEvent/) });
  346. triggerEventKeys.forEach((key) => {
  347. if (form[key]) {
  348. triggerEvents.push(form[key]);
  349. }
  350. });
  351. return triggerEvents;
  352. };
  353. actions.search = {};
  354. actions.search.index = function(req, res) {
  355. const search = crowi.getSearcher();
  356. if (!search) {
  357. return res.redirect('/admin');
  358. }
  359. return res.render('admin/search', {});
  360. };
  361. actions.user = {};
  362. actions.user.index = async function(req, res) {
  363. const activeUsers = await User.countListByStatus(User.STATUS_ACTIVE);
  364. const userUpperLimit = aclService.userUpperLimit();
  365. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  366. const page = parseInt(req.query.page) || 1;
  367. const result = await User.findUsersWithPagination({
  368. page,
  369. select: `${User.USER_PUBLIC_FIELDS} lastLoginAt`,
  370. populate: User.IMAGE_POPULATION,
  371. });
  372. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  373. return res.render('admin/users', {
  374. users: result.docs,
  375. pager,
  376. activeUsers,
  377. userUpperLimit,
  378. isUserCountExceedsUpperLimit,
  379. });
  380. };
  381. actions.user.makeAdmin = function(req, res) {
  382. const id = req.params.id;
  383. User.findById(id, (err, userData) => {
  384. userData.makeAdmin((err, userData) => {
  385. if (err === null) {
  386. req.flash('successMessage', `${userData.name}さんのアカウントを管理者に設定しました。`);
  387. }
  388. else {
  389. req.flash('errorMessage', '更新に失敗しました。');
  390. debug(err, userData);
  391. }
  392. return res.redirect('/admin/users');
  393. });
  394. });
  395. };
  396. actions.user.removeFromAdmin = function(req, res) {
  397. const id = req.params.id;
  398. User.findById(id, (err, userData) => {
  399. userData.removeFromAdmin((err, userData) => {
  400. if (err === null) {
  401. req.flash('successMessage', `${userData.name}さんのアカウントを管理者から外しました。`);
  402. }
  403. else {
  404. req.flash('errorMessage', '更新に失敗しました。');
  405. debug(err, userData);
  406. }
  407. return res.redirect('/admin/users');
  408. });
  409. });
  410. };
  411. // TODO delete
  412. actions.user.suspend = function(req, res) {
  413. const id = req.params.id;
  414. User.findById(id, (err, userData) => {
  415. userData.statusSuspend((err, userData) => {
  416. if (err === null) {
  417. req.flash('successMessage', `${userData.name}さんのアカウントを利用停止にしました`);
  418. }
  419. else {
  420. req.flash('errorMessage', '更新に失敗しました。');
  421. debug(err, userData);
  422. }
  423. return res.redirect('/admin/users');
  424. });
  425. });
  426. };
  427. // これやったときの relation の挙動未確認
  428. actions.user.removeCompletely = function(req, res) {
  429. // ユーザーの物理削除
  430. const id = req.params.id;
  431. User.removeCompletelyById(id, (err, removed) => {
  432. if (err) {
  433. debug('Error while removing user.', err, id);
  434. req.flash('errorMessage', '完全な削除に失敗しました。');
  435. }
  436. else {
  437. req.flash('successMessage', '削除しました');
  438. }
  439. return res.redirect('/admin/users');
  440. });
  441. };
  442. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  443. actions.user.resetPassword = async function(req, res) {
  444. const id = req.body.user_id;
  445. const User = crowi.model('User');
  446. try {
  447. const newPassword = await User.resetPasswordByRandomString(id);
  448. const user = await User.findById(id);
  449. const result = { user: user.toObject(), newPassword };
  450. return res.json(ApiResponse.success(result));
  451. }
  452. catch (err) {
  453. debug('Error on reseting password', err);
  454. return res.json(ApiResponse.error(err));
  455. }
  456. };
  457. actions.externalAccount = {};
  458. actions.externalAccount.index = function(req, res) {
  459. const page = parseInt(req.query.page) || 1;
  460. ExternalAccount.findAllWithPagination({ page })
  461. .then((result) => {
  462. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  463. return res.render('admin/external-accounts', {
  464. accounts: result.docs,
  465. pager,
  466. });
  467. });
  468. };
  469. actions.externalAccount.remove = async function(req, res) {
  470. const id = req.params.id;
  471. let account = null;
  472. try {
  473. account = await ExternalAccount.findByIdAndRemove(id);
  474. if (account == null) {
  475. throw new Error('削除に失敗しました。');
  476. }
  477. }
  478. catch (err) {
  479. req.flash('errorMessage', err.message);
  480. return res.redirect('/admin/users/external-accounts');
  481. }
  482. req.flash('successMessage', `外部アカウント '${account.providerType}/${account.accountId}' を削除しました`);
  483. return res.redirect('/admin/users/external-accounts');
  484. };
  485. actions.userGroup = {};
  486. actions.userGroup.index = function(req, res) {
  487. const page = parseInt(req.query.page) || 1;
  488. const isAclEnabled = aclService.isAclEnabled();
  489. const renderVar = {
  490. userGroups: [],
  491. userGroupRelations: new Map(),
  492. pager: null,
  493. isAclEnabled,
  494. };
  495. UserGroup.findUserGroupsWithPagination({ page })
  496. .then((result) => {
  497. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  498. const userGroups = result.docs;
  499. renderVar.userGroups = userGroups;
  500. renderVar.pager = pager;
  501. return userGroups.map((userGroup) => {
  502. return new Promise((resolve, reject) => {
  503. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  504. .then((relations) => {
  505. return resolve({
  506. id: userGroup._id,
  507. relatedUsers: relations.map((relation) => {
  508. return relation.relatedUser;
  509. }),
  510. });
  511. });
  512. });
  513. });
  514. })
  515. .then((allRelationsPromise) => {
  516. return Promise.all(allRelationsPromise);
  517. })
  518. .then((relations) => {
  519. for (const relation of relations) {
  520. renderVar.userGroupRelations[relation.id] = relation.relatedUsers;
  521. }
  522. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  523. return res.render('admin/user-groups', renderVar);
  524. })
  525. .catch((err) => {
  526. debug('Error on find all relations', err);
  527. return res.json(ApiResponse.error('Error'));
  528. });
  529. };
  530. // グループ詳細
  531. actions.userGroup.detail = async function(req, res) {
  532. const userGroupId = req.params.id;
  533. const userGroup = await UserGroup.findOne({ _id: userGroupId });
  534. if (userGroup == null) {
  535. logger.error('no userGroup is exists. ', userGroupId);
  536. return res.redirect('/admin/user-groups');
  537. }
  538. return res.render('admin/user-group-detail', { userGroup });
  539. };
  540. // Importer management
  541. actions.importer = {};
  542. actions.importer.api = api;
  543. api.validators = {};
  544. api.validators.importer = {};
  545. actions.importer.index = function(req, res) {
  546. const settingForm = configManager.getConfigByPrefix('crowi', 'importer:');
  547. return res.render('admin/importer', {
  548. settingForm,
  549. });
  550. };
  551. api.validators.importer.esa = function() {
  552. const validator = [
  553. check('importer:esa:team_name').not().isEmpty().withMessage('Error. Empty esa:team_name'),
  554. check('importer:esa:access_token').not().isEmpty().withMessage('Error. Empty esa:access_token'),
  555. ];
  556. return validator;
  557. };
  558. api.validators.importer.qiita = function() {
  559. const validator = [
  560. check('importer:qiita:team_name').not().isEmpty().withMessage('Error. Empty qiita:team_name'),
  561. check('importer:qiita:access_token').not().isEmpty().withMessage('Error. Empty qiita:access_token'),
  562. ];
  563. return validator;
  564. };
  565. // Export management
  566. actions.export = {};
  567. actions.export.index = (req, res) => {
  568. return res.render('admin/export');
  569. };
  570. actions.export.download = (req, res) => {
  571. // TODO: add express validator
  572. const { fileName } = req.params;
  573. try {
  574. const zipFile = exportService.getFile(fileName);
  575. return res.download(zipFile);
  576. }
  577. catch (err) {
  578. // TODO: use ApiV3Error
  579. logger.error(err);
  580. return res.json(ApiResponse.error());
  581. }
  582. };
  583. actions.api = {};
  584. actions.api.appSetting = async function(req, res) {
  585. const form = req.form.settingForm;
  586. if (req.form.isValid) {
  587. debug('form content', form);
  588. // mail setting ならここで validation
  589. if (form['mail:from']) {
  590. validateMailSetting(req, form, async(err, data) => {
  591. debug('Error validate mail setting: ', err, data);
  592. if (err) {
  593. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  594. return res.json({ status: false, message: req.form.errors.join('\n') });
  595. }
  596. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  597. return res.json({ status: true });
  598. });
  599. }
  600. else {
  601. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  602. return res.json({ status: true });
  603. }
  604. }
  605. else {
  606. return res.json({ status: false, message: req.form.errors.join('\n') });
  607. }
  608. };
  609. actions.api.asyncAppSetting = async(req, res) => {
  610. const form = req.form.settingForm;
  611. if (!req.form.isValid) {
  612. return res.json({ status: false, message: req.form.errors.join('\n') });
  613. }
  614. debug('form content', form);
  615. try {
  616. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  617. return res.json({ status: true });
  618. }
  619. catch (err) {
  620. logger.error(err);
  621. return res.json({ status: false });
  622. }
  623. };
  624. actions.api.securitySetting = async function(req, res) {
  625. if (!req.form.isValid) {
  626. return res.json({ status: false, message: req.form.errors.join('\n') });
  627. }
  628. const form = req.form.settingForm;
  629. if (aclService.isWikiModeForced()) {
  630. logger.debug('security:restrictGuestMode will not be changed because wiki mode is forced to set');
  631. delete form['security:restrictGuestMode'];
  632. }
  633. try {
  634. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  635. return res.json({ status: true });
  636. }
  637. catch (err) {
  638. logger.error(err);
  639. return res.json({ status: false });
  640. }
  641. };
  642. actions.api.securityPassportLocalSetting = async function(req, res) {
  643. const form = req.form.settingForm;
  644. if (!req.form.isValid) {
  645. return res.json({ status: false, message: req.form.errors.join('\n') });
  646. }
  647. debug('form content', form);
  648. try {
  649. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  650. // reset strategy
  651. crowi.passportService.resetLocalStrategy();
  652. // setup strategy
  653. if (configManager.getConfig('crowi', 'security:passport-local:isEnabled')) {
  654. crowi.passportService.setupLocalStrategy(true);
  655. }
  656. }
  657. catch (err) {
  658. logger.error(err);
  659. return res.json({ status: false, message: err.message });
  660. }
  661. return res.json({ status: true });
  662. };
  663. actions.api.securityPassportLdapSetting = async function(req, res) {
  664. const form = req.form.settingForm;
  665. if (!req.form.isValid) {
  666. return res.json({ status: false, message: req.form.errors.join('\n') });
  667. }
  668. debug('form content', form);
  669. try {
  670. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  671. // reset strategy
  672. crowi.passportService.resetLdapStrategy();
  673. // setup strategy
  674. if (configManager.getConfig('crowi', 'security:passport-ldap:isEnabled')) {
  675. crowi.passportService.setupLdapStrategy(true);
  676. }
  677. }
  678. catch (err) {
  679. logger.error(err);
  680. return res.json({ status: false, message: err.message });
  681. }
  682. return res.json({ status: true });
  683. };
  684. actions.api.securityPassportSamlSetting = async(req, res) => {
  685. const form = req.form.settingForm;
  686. validateSamlSettingForm(req.form, req.t);
  687. if (!req.form.isValid) {
  688. return res.json({ status: false, message: req.form.errors.join('\n') });
  689. }
  690. debug('form content', form);
  691. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  692. // reset strategy
  693. await crowi.passportService.resetSamlStrategy();
  694. // setup strategy
  695. if (configManager.getConfig('crowi', 'security:passport-saml:isEnabled')) {
  696. try {
  697. await crowi.passportService.setupSamlStrategy(true);
  698. }
  699. catch (err) {
  700. // reset
  701. await crowi.passportService.resetSamlStrategy();
  702. return res.json({ status: false, message: err.message });
  703. }
  704. }
  705. return res.json({ status: true });
  706. };
  707. actions.api.securityPassportBasicSetting = async(req, res) => {
  708. const form = req.form.settingForm;
  709. if (!req.form.isValid) {
  710. return res.json({ status: false, message: req.form.errors.join('\n') });
  711. }
  712. debug('form content', form);
  713. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  714. // reset strategy
  715. await crowi.passportService.resetBasicStrategy();
  716. // setup strategy
  717. if (configManager.getConfig('crowi', 'security:passport-basic:isEnabled')) {
  718. try {
  719. await crowi.passportService.setupBasicStrategy(true);
  720. }
  721. catch (err) {
  722. // reset
  723. await crowi.passportService.resetBasicStrategy();
  724. return res.json({ status: false, message: err.message });
  725. }
  726. }
  727. return res.json({ status: true });
  728. };
  729. actions.api.securityPassportGoogleSetting = async(req, res) => {
  730. const form = req.form.settingForm;
  731. if (!req.form.isValid) {
  732. return res.json({ status: false, message: req.form.errors.join('\n') });
  733. }
  734. debug('form content', form);
  735. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  736. // reset strategy
  737. await crowi.passportService.resetGoogleStrategy();
  738. // setup strategy
  739. if (configManager.getConfig('crowi', 'security:passport-google:isEnabled')) {
  740. try {
  741. await crowi.passportService.setupGoogleStrategy(true);
  742. }
  743. catch (err) {
  744. // reset
  745. await crowi.passportService.resetGoogleStrategy();
  746. return res.json({ status: false, message: err.message });
  747. }
  748. }
  749. return res.json({ status: true });
  750. };
  751. actions.api.securityPassportGitHubSetting = async(req, res) => {
  752. const form = req.form.settingForm;
  753. if (!req.form.isValid) {
  754. return res.json({ status: false, message: req.form.errors.join('\n') });
  755. }
  756. debug('form content', form);
  757. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  758. // reset strategy
  759. await crowi.passportService.resetGitHubStrategy();
  760. // setup strategy
  761. if (configManager.getConfig('crowi', 'security:passport-github:isEnabled')) {
  762. try {
  763. await crowi.passportService.setupGitHubStrategy(true);
  764. }
  765. catch (err) {
  766. // reset
  767. await crowi.passportService.resetGitHubStrategy();
  768. return res.json({ status: false, message: err.message });
  769. }
  770. }
  771. return res.json({ status: true });
  772. };
  773. actions.api.securityPassportTwitterSetting = async(req, res) => {
  774. const form = req.form.settingForm;
  775. if (!req.form.isValid) {
  776. return res.json({ status: false, message: req.form.errors.join('\n') });
  777. }
  778. debug('form content', form);
  779. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  780. // reset strategy
  781. await crowi.passportService.resetTwitterStrategy();
  782. // setup strategy
  783. if (configManager.getConfig('crowi', 'security:passport-twitter:isEnabled')) {
  784. try {
  785. await crowi.passportService.setupTwitterStrategy(true);
  786. }
  787. catch (err) {
  788. // reset
  789. await crowi.passportService.resetTwitterStrategy();
  790. return res.json({ status: false, message: err.message });
  791. }
  792. }
  793. return res.json({ status: true });
  794. };
  795. actions.api.securityPassportOidcSetting = async(req, res) => {
  796. const form = req.form.settingForm;
  797. if (!req.form.isValid) {
  798. return res.json({ status: false, message: req.form.errors.join('\n') });
  799. }
  800. debug('form content', form);
  801. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  802. // reset strategy
  803. await crowi.passportService.resetOidcStrategy();
  804. // setup strategy
  805. if (configManager.getConfig('crowi', 'security:passport-oidc:isEnabled')) {
  806. try {
  807. await crowi.passportService.setupOidcStrategy(true);
  808. }
  809. catch (err) {
  810. // reset
  811. await crowi.passportService.resetOidcStrategy();
  812. return res.json({ status: false, message: err.message });
  813. }
  814. }
  815. return res.json({ status: true });
  816. };
  817. actions.api.customizeSetting = async function(req, res) {
  818. const form = req.form.settingForm;
  819. if (req.form.isValid) {
  820. debug('form content', form);
  821. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  822. customizeService.initCustomCss();
  823. customizeService.initCustomTitle();
  824. return res.json({ status: true });
  825. }
  826. return res.json({ status: false, message: req.form.errors.join('\n') });
  827. };
  828. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  829. actions.api.notificationAdd = function(req, res) {
  830. const UpdatePost = crowi.model('UpdatePost');
  831. const pathPattern = req.body.pathPattern;
  832. const channel = req.body.channel;
  833. debug('notification.add', pathPattern, channel);
  834. UpdatePost.create(pathPattern, channel, req.user)
  835. .then((doc) => {
  836. debug('Successfully save updatePost', doc);
  837. // fixme: うーん
  838. doc.creator = doc.creator._id.toString();
  839. return res.json(ApiResponse.success({ updatePost: doc }));
  840. })
  841. .catch((err) => {
  842. debug('Failed to save updatePost', err);
  843. return res.json(ApiResponse.error());
  844. });
  845. };
  846. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  847. actions.api.notificationRemove = function(req, res) {
  848. const UpdatePost = crowi.model('UpdatePost');
  849. const id = req.body.id;
  850. UpdatePost.remove(id)
  851. .then(() => {
  852. debug('Successfully remove updatePost');
  853. return res.json(ApiResponse.success({}));
  854. })
  855. .catch((err) => {
  856. debug('Failed to remove updatePost', err);
  857. return res.json(ApiResponse.error());
  858. });
  859. };
  860. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  861. actions.api.usersSearch = function(req, res) {
  862. const User = crowi.model('User');
  863. const email = req.query.email;
  864. User.findUsersByPartOfEmail(email, {})
  865. .then((users) => {
  866. const result = {
  867. data: users,
  868. };
  869. return res.json(ApiResponse.success(result));
  870. })
  871. .catch((err) => {
  872. return res.json(ApiResponse.error());
  873. });
  874. };
  875. actions.api.toggleIsEnabledForGlobalNotification = async(req, res) => {
  876. const id = req.query.id;
  877. const isEnabled = (req.query.isEnabled === 'true');
  878. try {
  879. if (isEnabled) {
  880. await GlobalNotificationSetting.enable(id);
  881. }
  882. else {
  883. await GlobalNotificationSetting.disable(id);
  884. }
  885. return res.json(ApiResponse.success());
  886. }
  887. catch (err) {
  888. return res.json(ApiResponse.error());
  889. }
  890. };
  891. /**
  892. * save esa settings, update config cache, and response json
  893. *
  894. * @param {*} req
  895. * @param {*} res
  896. */
  897. actions.api.importerSettingEsa = async(req, res) => {
  898. const form = req.body;
  899. const { validationResult } = require('express-validator');
  900. const errors = validationResult(req);
  901. if (!errors.isEmpty()) {
  902. return res.json(ApiResponse.error('esa.io form is blank'));
  903. }
  904. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  905. importer.initializeEsaClient(); // let it run in the back aftert res
  906. return res.json(ApiResponse.success());
  907. };
  908. /**
  909. * save qiita settings, update config cache, and response json
  910. *
  911. * @param {*} req
  912. * @param {*} res
  913. */
  914. actions.api.importerSettingQiita = async(req, res) => {
  915. const form = req.body;
  916. const { validationResult } = require('express-validator');
  917. const errors = validationResult(req);
  918. if (!errors.isEmpty()) {
  919. console.log('validator', errors);
  920. return res.json(ApiResponse.error('Qiita form is blank'));
  921. }
  922. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  923. importer.initializeQiitaClient(); // let it run in the back aftert res
  924. return res.json(ApiResponse.success());
  925. };
  926. /**
  927. * Import all posts from esa
  928. *
  929. * @param {*} req
  930. * @param {*} res
  931. */
  932. actions.api.importDataFromEsa = async(req, res) => {
  933. const user = req.user;
  934. let errors;
  935. try {
  936. errors = await importer.importDataFromEsa(user);
  937. }
  938. catch (err) {
  939. errors = [err];
  940. }
  941. if (errors.length > 0) {
  942. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  943. }
  944. return res.json(ApiResponse.success());
  945. };
  946. /**
  947. * Import all posts from qiita
  948. *
  949. * @param {*} req
  950. * @param {*} res
  951. */
  952. actions.api.importDataFromQiita = async(req, res) => {
  953. const user = req.user;
  954. let errors;
  955. try {
  956. errors = await importer.importDataFromQiita(user);
  957. }
  958. catch (err) {
  959. errors = [err];
  960. }
  961. if (errors.length > 0) {
  962. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  963. }
  964. return res.json(ApiResponse.success());
  965. };
  966. /**
  967. * Test connection to esa and response result with json
  968. *
  969. * @param {*} req
  970. * @param {*} res
  971. */
  972. actions.api.testEsaAPI = async(req, res) => {
  973. try {
  974. await importer.testConnectionToEsa();
  975. return res.json(ApiResponse.success());
  976. }
  977. catch (err) {
  978. return res.json(ApiResponse.error(err));
  979. }
  980. };
  981. /**
  982. * Test connection to qiita and response result with json
  983. *
  984. * @param {*} req
  985. * @param {*} res
  986. */
  987. actions.api.testQiitaAPI = async(req, res) => {
  988. try {
  989. await importer.testConnectionToQiita();
  990. return res.json(ApiResponse.success());
  991. }
  992. catch (err) {
  993. return res.json(ApiResponse.error(err));
  994. }
  995. };
  996. actions.api.searchBuildIndex = async function(req, res) {
  997. const search = crowi.getSearcher();
  998. if (!search) {
  999. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  1000. }
  1001. searchEvent.on('addPageProgress', (total, current, skip) => {
  1002. crowi.getIo().sockets.emit('admin:addPageProgress', { total, current, skip });
  1003. });
  1004. searchEvent.on('finishAddPage', (total, current, skip) => {
  1005. crowi.getIo().sockets.emit('admin:finishAddPage', { total, current, skip });
  1006. });
  1007. await search.buildIndex();
  1008. return res.json(ApiResponse.success());
  1009. };
  1010. function validateMailSetting(req, form, callback) {
  1011. const mailer = crowi.mailer;
  1012. const option = {
  1013. host: form['mail:smtpHost'],
  1014. port: form['mail:smtpPort'],
  1015. };
  1016. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  1017. option.auth = {
  1018. user: form['mail:smtpUser'],
  1019. pass: form['mail:smtpPassword'],
  1020. };
  1021. }
  1022. if (option.port === 465) {
  1023. option.secure = true;
  1024. }
  1025. const smtpClient = mailer.createSMTPClient(option);
  1026. debug('mailer setup for validate SMTP setting', smtpClient);
  1027. smtpClient.sendMail({
  1028. from: form['mail:from'],
  1029. to: req.user.email,
  1030. subject: 'Wiki管理設定のアップデートによるメール通知',
  1031. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。',
  1032. }, callback);
  1033. }
  1034. /**
  1035. * validate setting form values for SAML
  1036. *
  1037. * This validation checks, for the value of each mandatory items,
  1038. * whether it from the environment variables is empty and form value to update it is empty.
  1039. */
  1040. function validateSamlSettingForm(form, t) {
  1041. for (const key of crowi.passportService.mandatoryConfigKeysForSaml) {
  1042. const formValue = form.settingForm[key];
  1043. if (configManager.getConfigFromEnvVars('crowi', key) === null && formValue === '') {
  1044. const formItemName = t(`security_setting.form_item_name.${key}`);
  1045. form.errors.push(t('form_validation.required', formItemName));
  1046. }
  1047. }
  1048. }
  1049. return actions;
  1050. };