admin.js 42 KB

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