admin.js 39 KB

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