admin.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  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.makeAdmin = function(req, res) {
  366. const id = req.params.id;
  367. User.findById(id, (err, userData) => {
  368. userData.makeAdmin((err, userData) => {
  369. if (err === null) {
  370. req.flash('successMessage', `${userData.name}さんのアカウントを管理者に設定しました。`);
  371. }
  372. else {
  373. req.flash('errorMessage', '更新に失敗しました。');
  374. debug(err, userData);
  375. }
  376. return res.redirect('/admin/users');
  377. });
  378. });
  379. };
  380. actions.user.removeFromAdmin = function(req, res) {
  381. const id = req.params.id;
  382. User.findById(id, (err, userData) => {
  383. userData.removeFromAdmin((err, userData) => {
  384. if (err === null) {
  385. req.flash('successMessage', `${userData.name}さんのアカウントを管理者から外しました。`);
  386. }
  387. else {
  388. req.flash('errorMessage', '更新に失敗しました。');
  389. debug(err, userData);
  390. }
  391. return res.redirect('/admin/users');
  392. });
  393. });
  394. };
  395. actions.user.activate = async function(req, res) {
  396. // check user upper limit
  397. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  398. if (isUserCountExceedsUpperLimit) {
  399. req.flash('errorMessage', 'ユーザーが上限に達したため有効化できません。');
  400. return res.redirect('/admin/users');
  401. }
  402. const id = req.params.id;
  403. User.findById(id, (err, userData) => {
  404. userData.statusActivate((err, userData) => {
  405. if (err === null) {
  406. req.flash('successMessage', `${userData.name}さんのアカウントを有効化しました`);
  407. }
  408. else {
  409. req.flash('errorMessage', '更新に失敗しました。');
  410. debug(err, userData);
  411. }
  412. return res.redirect('/admin/users');
  413. });
  414. });
  415. };
  416. actions.user.suspend = function(req, res) {
  417. const id = req.params.id;
  418. User.findById(id, (err, userData) => {
  419. userData.statusSuspend((err, userData) => {
  420. if (err === null) {
  421. req.flash('successMessage', `${userData.name}さんのアカウントを利用停止にしました`);
  422. }
  423. else {
  424. req.flash('errorMessage', '更新に失敗しました。');
  425. debug(err, userData);
  426. }
  427. return res.redirect('/admin/users');
  428. });
  429. });
  430. };
  431. actions.user.remove = function(req, res) {
  432. const id = req.params.id;
  433. let username = '';
  434. return new Promise((resolve, reject) => {
  435. User.findById(id, (err, userData) => {
  436. username = userData.username;
  437. return resolve(userData);
  438. });
  439. })
  440. .then((userData) => {
  441. return new Promise((resolve, reject) => {
  442. userData.statusDelete((err, userData) => {
  443. if (err) {
  444. reject(err);
  445. }
  446. resolve(userData);
  447. });
  448. });
  449. })
  450. .then((userData) => {
  451. // remove all External Accounts
  452. return ExternalAccount.remove({ user: userData }).then(() => { return userData });
  453. })
  454. .then((userData) => {
  455. return Page.removeByPath(`/user/${username}`).then(() => { return userData });
  456. })
  457. .then((userData) => {
  458. req.flash('successMessage', `${username} さんのアカウントを削除しました`);
  459. return res.redirect('/admin/users');
  460. })
  461. .catch((err) => {
  462. req.flash('errorMessage', '削除に失敗しました。');
  463. return res.redirect('/admin/users');
  464. });
  465. };
  466. // これやったときの relation の挙動未確認
  467. actions.user.removeCompletely = function(req, res) {
  468. // ユーザーの物理削除
  469. const id = req.params.id;
  470. User.removeCompletelyById(id, (err, removed) => {
  471. if (err) {
  472. debug('Error while removing user.', err, id);
  473. req.flash('errorMessage', '完全な削除に失敗しました。');
  474. }
  475. else {
  476. req.flash('successMessage', '削除しました');
  477. }
  478. return res.redirect('/admin/users');
  479. });
  480. };
  481. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  482. actions.user.resetPassword = async function(req, res) {
  483. const id = req.body.user_id;
  484. const User = crowi.model('User');
  485. try {
  486. const newPassword = await User.resetPasswordByRandomString(id);
  487. const user = await User.findById(id);
  488. const result = { user: user.toObject(), newPassword };
  489. return res.json(ApiResponse.success(result));
  490. }
  491. catch (err) {
  492. debug('Error on reseting password', err);
  493. return res.json(ApiResponse.error(err));
  494. }
  495. };
  496. actions.externalAccount = {};
  497. actions.externalAccount.index = function(req, res) {
  498. const page = parseInt(req.query.page) || 1;
  499. ExternalAccount.findAllWithPagination({ page })
  500. .then((result) => {
  501. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  502. return res.render('admin/external-accounts', {
  503. accounts: result.docs,
  504. pager,
  505. });
  506. });
  507. };
  508. actions.externalAccount.remove = async function(req, res) {
  509. const id = req.params.id;
  510. let account = null;
  511. try {
  512. account = await ExternalAccount.findByIdAndRemove(id);
  513. if (account == null) {
  514. throw new Error('削除に失敗しました。');
  515. }
  516. }
  517. catch (err) {
  518. req.flash('errorMessage', err.message);
  519. return res.redirect('/admin/users/external-accounts');
  520. }
  521. req.flash('successMessage', `外部アカウント '${account.providerType}/${account.accountId}' を削除しました`);
  522. return res.redirect('/admin/users/external-accounts');
  523. };
  524. actions.userGroup = {};
  525. actions.userGroup.index = function(req, res) {
  526. const page = parseInt(req.query.page) || 1;
  527. const isAclEnabled = aclService.isAclEnabled();
  528. const renderVar = {
  529. userGroups: [],
  530. userGroupRelations: new Map(),
  531. pager: null,
  532. isAclEnabled,
  533. };
  534. UserGroup.findUserGroupsWithPagination({ page })
  535. .then((result) => {
  536. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  537. const userGroups = result.docs;
  538. renderVar.userGroups = userGroups;
  539. renderVar.pager = pager;
  540. return userGroups.map((userGroup) => {
  541. return new Promise((resolve, reject) => {
  542. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  543. .then((relations) => {
  544. return resolve({
  545. id: userGroup._id,
  546. relatedUsers: relations.map((relation) => {
  547. return relation.relatedUser;
  548. }),
  549. });
  550. });
  551. });
  552. });
  553. })
  554. .then((allRelationsPromise) => {
  555. return Promise.all(allRelationsPromise);
  556. })
  557. .then((relations) => {
  558. for (const relation of relations) {
  559. renderVar.userGroupRelations[relation.id] = relation.relatedUsers;
  560. }
  561. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  562. return res.render('admin/user-groups', renderVar);
  563. })
  564. .catch((err) => {
  565. debug('Error on find all relations', err);
  566. return res.json(ApiResponse.error('Error'));
  567. });
  568. };
  569. // グループ詳細
  570. actions.userGroup.detail = async function(req, res) {
  571. const userGroupId = req.params.id;
  572. const userGroup = await UserGroup.findOne({ _id: userGroupId });
  573. if (userGroup == null) {
  574. logger.error('no userGroup is exists. ', userGroupId);
  575. return res.redirect('/admin/user-groups');
  576. }
  577. return res.render('admin/user-group-detail', { userGroup });
  578. };
  579. // Importer management
  580. actions.importer = {};
  581. actions.importer.api = api;
  582. api.validators = {};
  583. api.validators.importer = {};
  584. actions.importer.index = function(req, res) {
  585. const settingForm = configManager.getConfigByPrefix('crowi', 'importer:');
  586. return res.render('admin/importer', {
  587. settingForm,
  588. });
  589. };
  590. api.validators.importer.esa = function() {
  591. const validator = [
  592. check('importer:esa:team_name').not().isEmpty().withMessage('Error. Empty esa:team_name'),
  593. check('importer:esa:access_token').not().isEmpty().withMessage('Error. Empty esa:access_token'),
  594. ];
  595. return validator;
  596. };
  597. api.validators.importer.qiita = function() {
  598. const validator = [
  599. check('importer:qiita:team_name').not().isEmpty().withMessage('Error. Empty qiita:team_name'),
  600. check('importer:qiita:access_token').not().isEmpty().withMessage('Error. Empty qiita:access_token'),
  601. ];
  602. return validator;
  603. };
  604. actions.api = {};
  605. actions.api.appSetting = async function(req, res) {
  606. const form = req.form.settingForm;
  607. if (req.form.isValid) {
  608. debug('form content', form);
  609. // mail setting ならここで validation
  610. if (form['mail:from']) {
  611. validateMailSetting(req, form, async(err, data) => {
  612. debug('Error validate mail setting: ', err, data);
  613. if (err) {
  614. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  615. return res.json({ status: false, message: req.form.errors.join('\n') });
  616. }
  617. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  618. return res.json({ status: true });
  619. });
  620. }
  621. else {
  622. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  623. return res.json({ status: true });
  624. }
  625. }
  626. else {
  627. return res.json({ status: false, message: req.form.errors.join('\n') });
  628. }
  629. };
  630. actions.api.asyncAppSetting = async(req, res) => {
  631. const form = req.form.settingForm;
  632. if (!req.form.isValid) {
  633. return res.json({ status: false, message: req.form.errors.join('\n') });
  634. }
  635. debug('form content', form);
  636. try {
  637. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  638. return res.json({ status: true });
  639. }
  640. catch (err) {
  641. logger.error(err);
  642. return res.json({ status: false });
  643. }
  644. };
  645. actions.api.securitySetting = async function(req, res) {
  646. if (!req.form.isValid) {
  647. return res.json({ status: false, message: req.form.errors.join('\n') });
  648. }
  649. const form = req.form.settingForm;
  650. if (aclService.isWikiModeForced()) {
  651. logger.debug('security:restrictGuestMode will not be changed because wiki mode is forced to set');
  652. delete form['security:restrictGuestMode'];
  653. }
  654. try {
  655. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  656. return res.json({ status: true });
  657. }
  658. catch (err) {
  659. logger.error(err);
  660. return res.json({ status: false });
  661. }
  662. };
  663. actions.api.securityPassportLdapSetting = 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. return configManager.updateConfigsInTheSameNamespace('crowi', form)
  670. .then(() => {
  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. return;
  678. })
  679. .then(() => {
  680. res.json({ status: true });
  681. });
  682. };
  683. actions.api.securityPassportSamlSetting = async(req, res) => {
  684. const form = req.form.settingForm;
  685. validateSamlSettingForm(req.form, req.t);
  686. if (!req.form.isValid) {
  687. return res.json({ status: false, message: req.form.errors.join('\n') });
  688. }
  689. debug('form content', form);
  690. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  691. // reset strategy
  692. await crowi.passportService.resetSamlStrategy();
  693. // setup strategy
  694. if (configManager.getConfig('crowi', 'security:passport-saml:isEnabled')) {
  695. try {
  696. await crowi.passportService.setupSamlStrategy(true);
  697. }
  698. catch (err) {
  699. // reset
  700. await crowi.passportService.resetSamlStrategy();
  701. return res.json({ status: false, message: err.message });
  702. }
  703. }
  704. return res.json({ status: true });
  705. };
  706. actions.api.securityPassportBasicSetting = async(req, res) => {
  707. const form = req.form.settingForm;
  708. if (!req.form.isValid) {
  709. return res.json({ status: false, message: req.form.errors.join('\n') });
  710. }
  711. debug('form content', form);
  712. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  713. // reset strategy
  714. await crowi.passportService.resetBasicStrategy();
  715. // setup strategy
  716. if (configManager.getConfig('crowi', 'security:passport-basic:isEnabled')) {
  717. try {
  718. await crowi.passportService.setupBasicStrategy(true);
  719. }
  720. catch (err) {
  721. // reset
  722. await crowi.passportService.resetBasicStrategy();
  723. return res.json({ status: false, message: err.message });
  724. }
  725. }
  726. return res.json({ status: true });
  727. };
  728. actions.api.securityPassportGoogleSetting = async(req, res) => {
  729. const form = req.form.settingForm;
  730. if (!req.form.isValid) {
  731. return res.json({ status: false, message: req.form.errors.join('\n') });
  732. }
  733. debug('form content', form);
  734. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  735. // reset strategy
  736. await crowi.passportService.resetGoogleStrategy();
  737. // setup strategy
  738. if (configManager.getConfig('crowi', 'security:passport-google:isEnabled')) {
  739. try {
  740. await crowi.passportService.setupGoogleStrategy(true);
  741. }
  742. catch (err) {
  743. // reset
  744. await crowi.passportService.resetGoogleStrategy();
  745. return res.json({ status: false, message: err.message });
  746. }
  747. }
  748. return res.json({ status: true });
  749. };
  750. actions.api.securityPassportGitHubSetting = async(req, res) => {
  751. const form = req.form.settingForm;
  752. if (!req.form.isValid) {
  753. return res.json({ status: false, message: req.form.errors.join('\n') });
  754. }
  755. debug('form content', form);
  756. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  757. // reset strategy
  758. await crowi.passportService.resetGitHubStrategy();
  759. // setup strategy
  760. if (configManager.getConfig('crowi', 'security:passport-github:isEnabled')) {
  761. try {
  762. await crowi.passportService.setupGitHubStrategy(true);
  763. }
  764. catch (err) {
  765. // reset
  766. await crowi.passportService.resetGitHubStrategy();
  767. return res.json({ status: false, message: err.message });
  768. }
  769. }
  770. return res.json({ status: true });
  771. };
  772. actions.api.securityPassportTwitterSetting = async(req, res) => {
  773. const form = req.form.settingForm;
  774. if (!req.form.isValid) {
  775. return res.json({ status: false, message: req.form.errors.join('\n') });
  776. }
  777. debug('form content', form);
  778. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  779. // reset strategy
  780. await crowi.passportService.resetTwitterStrategy();
  781. // setup strategy
  782. if (configManager.getConfig('crowi', 'security:passport-twitter:isEnabled')) {
  783. try {
  784. await crowi.passportService.setupTwitterStrategy(true);
  785. }
  786. catch (err) {
  787. // reset
  788. await crowi.passportService.resetTwitterStrategy();
  789. return res.json({ status: false, message: err.message });
  790. }
  791. }
  792. return res.json({ status: true });
  793. };
  794. actions.api.securityPassportOidcSetting = async(req, res) => {
  795. const form = req.form.settingForm;
  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.resetOidcStrategy();
  803. // setup strategy
  804. if (configManager.getConfig('crowi', 'security:passport-oidc:isEnabled')) {
  805. try {
  806. await crowi.passportService.setupOidcStrategy(true);
  807. }
  808. catch (err) {
  809. // reset
  810. await crowi.passportService.resetOidcStrategy();
  811. return res.json({ status: false, message: err.message });
  812. }
  813. }
  814. return res.json({ status: true });
  815. };
  816. actions.api.customizeSetting = async function(req, res) {
  817. const form = req.form.settingForm;
  818. if (req.form.isValid) {
  819. debug('form content', form);
  820. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  821. customizeService.initCustomCss();
  822. customizeService.initCustomTitle();
  823. return res.json({ status: true });
  824. }
  825. return res.json({ status: false, message: req.form.errors.join('\n') });
  826. };
  827. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  828. actions.api.notificationAdd = function(req, res) {
  829. const UpdatePost = crowi.model('UpdatePost');
  830. const pathPattern = req.body.pathPattern;
  831. const channel = req.body.channel;
  832. debug('notification.add', pathPattern, channel);
  833. UpdatePost.create(pathPattern, channel, req.user)
  834. .then((doc) => {
  835. debug('Successfully save updatePost', doc);
  836. // fixme: うーん
  837. doc.creator = doc.creator._id.toString();
  838. return res.json(ApiResponse.success({ updatePost: doc }));
  839. })
  840. .catch((err) => {
  841. debug('Failed to save updatePost', err);
  842. return res.json(ApiResponse.error());
  843. });
  844. };
  845. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  846. actions.api.notificationRemove = function(req, res) {
  847. const UpdatePost = crowi.model('UpdatePost');
  848. const id = req.body.id;
  849. UpdatePost.remove(id)
  850. .then(() => {
  851. debug('Successfully remove updatePost');
  852. return res.json(ApiResponse.success({}));
  853. })
  854. .catch((err) => {
  855. debug('Failed to remove updatePost', err);
  856. return res.json(ApiResponse.error());
  857. });
  858. };
  859. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  860. actions.api.usersSearch = function(req, res) {
  861. const User = crowi.model('User');
  862. const email = req.query.email;
  863. User.findUsersByPartOfEmail(email, {})
  864. .then((users) => {
  865. const result = {
  866. data: users,
  867. };
  868. return res.json(ApiResponse.success(result));
  869. })
  870. .catch((err) => {
  871. return res.json(ApiResponse.error());
  872. });
  873. };
  874. actions.api.toggleIsEnabledForGlobalNotification = async(req, res) => {
  875. const id = req.query.id;
  876. const isEnabled = (req.query.isEnabled === 'true');
  877. try {
  878. if (isEnabled) {
  879. await GlobalNotificationSetting.enable(id);
  880. }
  881. else {
  882. await GlobalNotificationSetting.disable(id);
  883. }
  884. return res.json(ApiResponse.success());
  885. }
  886. catch (err) {
  887. return res.json(ApiResponse.error());
  888. }
  889. };
  890. /**
  891. * save esa settings, update config cache, and response json
  892. *
  893. * @param {*} req
  894. * @param {*} res
  895. */
  896. actions.api.importerSettingEsa = async(req, res) => {
  897. const form = req.body;
  898. const { validationResult } = require('express-validator');
  899. const errors = validationResult(req);
  900. if (!errors.isEmpty()) {
  901. return res.json(ApiResponse.error('esa.io form is blank'));
  902. }
  903. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  904. importer.initializeEsaClient(); // let it run in the back aftert res
  905. return res.json(ApiResponse.success());
  906. };
  907. /**
  908. * save qiita settings, update config cache, and response json
  909. *
  910. * @param {*} req
  911. * @param {*} res
  912. */
  913. actions.api.importerSettingQiita = async(req, res) => {
  914. const form = req.body;
  915. const { validationResult } = require('express-validator');
  916. const errors = validationResult(req);
  917. if (!errors.isEmpty()) {
  918. console.log('validator', errors);
  919. return res.json(ApiResponse.error('Qiita form is blank'));
  920. }
  921. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  922. importer.initializeQiitaClient(); // let it run in the back aftert res
  923. return res.json(ApiResponse.success());
  924. };
  925. /**
  926. * Import all posts from esa
  927. *
  928. * @param {*} req
  929. * @param {*} res
  930. */
  931. actions.api.importDataFromEsa = async(req, res) => {
  932. const user = req.user;
  933. let errors;
  934. try {
  935. errors = await importer.importDataFromEsa(user);
  936. }
  937. catch (err) {
  938. errors = [err];
  939. }
  940. if (errors.length > 0) {
  941. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  942. }
  943. return res.json(ApiResponse.success());
  944. };
  945. /**
  946. * Import all posts from qiita
  947. *
  948. * @param {*} req
  949. * @param {*} res
  950. */
  951. actions.api.importDataFromQiita = async(req, res) => {
  952. const user = req.user;
  953. let errors;
  954. try {
  955. errors = await importer.importDataFromQiita(user);
  956. }
  957. catch (err) {
  958. errors = [err];
  959. }
  960. if (errors.length > 0) {
  961. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  962. }
  963. return res.json(ApiResponse.success());
  964. };
  965. /**
  966. * Test connection to esa and response result with json
  967. *
  968. * @param {*} req
  969. * @param {*} res
  970. */
  971. actions.api.testEsaAPI = async(req, res) => {
  972. try {
  973. await importer.testConnectionToEsa();
  974. return res.json(ApiResponse.success());
  975. }
  976. catch (err) {
  977. return res.json(ApiResponse.error(err));
  978. }
  979. };
  980. /**
  981. * Test connection to qiita and response result with json
  982. *
  983. * @param {*} req
  984. * @param {*} res
  985. */
  986. actions.api.testQiitaAPI = async(req, res) => {
  987. try {
  988. await importer.testConnectionToQiita();
  989. return res.json(ApiResponse.success());
  990. }
  991. catch (err) {
  992. return res.json(ApiResponse.error(err));
  993. }
  994. };
  995. actions.api.searchBuildIndex = async function(req, res) {
  996. const search = crowi.getSearcher();
  997. if (!search) {
  998. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  999. }
  1000. // first, delete index
  1001. try {
  1002. await search.deleteIndex();
  1003. }
  1004. catch (err) {
  1005. logger.warn('Delete index Error, but if it is initialize, its ok.', err);
  1006. }
  1007. // second, create index
  1008. try {
  1009. await search.buildIndex();
  1010. }
  1011. catch (err) {
  1012. logger.error('Error', err);
  1013. return res.json(ApiResponse.error(err));
  1014. }
  1015. searchEvent.on('addPageProgress', (total, current, skip) => {
  1016. crowi.getIo().sockets.emit('admin:addPageProgress', { total, current, skip });
  1017. });
  1018. searchEvent.on('finishAddPage', (total, current, skip) => {
  1019. crowi.getIo().sockets.emit('admin:finishAddPage', { total, current, skip });
  1020. });
  1021. // add all page
  1022. search
  1023. .addAllPages()
  1024. .then(() => {
  1025. debug('Data is successfully indexed. ------------------ ✧✧');
  1026. })
  1027. .catch((err) => {
  1028. logger.error('Error', err);
  1029. });
  1030. return res.json(ApiResponse.success());
  1031. };
  1032. function validateMailSetting(req, form, callback) {
  1033. const mailer = crowi.mailer;
  1034. const option = {
  1035. host: form['mail:smtpHost'],
  1036. port: form['mail:smtpPort'],
  1037. };
  1038. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  1039. option.auth = {
  1040. user: form['mail:smtpUser'],
  1041. pass: form['mail:smtpPassword'],
  1042. };
  1043. }
  1044. if (option.port === 465) {
  1045. option.secure = true;
  1046. }
  1047. const smtpClient = mailer.createSMTPClient(option);
  1048. debug('mailer setup for validate SMTP setting', smtpClient);
  1049. smtpClient.sendMail({
  1050. from: form['mail:from'],
  1051. to: req.user.email,
  1052. subject: 'Wiki管理設定のアップデートによるメール通知',
  1053. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。',
  1054. }, callback);
  1055. }
  1056. /**
  1057. * validate setting form values for SAML
  1058. *
  1059. * This validation checks, for the value of each mandatory items,
  1060. * whether it from the environment variables is empty and form value to update it is empty.
  1061. */
  1062. function validateSamlSettingForm(form, t) {
  1063. for (const key of crowi.passportService.mandatoryConfigKeysForSaml) {
  1064. const formValue = form.settingForm[key];
  1065. if (configManager.getConfigFromEnvVars('crowi', key) === null && formValue === '') {
  1066. const formItemName = t(`security_setting.form_item_name.${key}`);
  1067. form.errors.push(t('form_validation.required', formItemName));
  1068. }
  1069. }
  1070. }
  1071. return actions;
  1072. };