admin.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  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. function createPager(total, limit, page, pagesCount, maxPageList) {
  29. const pager = {
  30. page,
  31. pagesCount,
  32. pages: [],
  33. total,
  34. previous: null,
  35. previousDots: false,
  36. next: null,
  37. nextDots: false,
  38. };
  39. if (page > 1) {
  40. pager.previous = page - 1;
  41. }
  42. if (page < pagesCount) {
  43. pager.next = page + 1;
  44. }
  45. let pagerMin = Math.max(1, Math.ceil(page - maxPageList / 2));
  46. let pagerMax = Math.min(pagesCount, Math.floor(page + maxPageList / 2));
  47. if (pagerMin === 1) {
  48. if (MAX_PAGE_LIST < pagesCount) {
  49. pagerMax = MAX_PAGE_LIST;
  50. }
  51. else {
  52. pagerMax = pagesCount;
  53. }
  54. }
  55. if (pagerMax === pagesCount) {
  56. if ((pagerMax - MAX_PAGE_LIST) < 1) {
  57. pagerMin = 1;
  58. }
  59. else {
  60. pagerMin = pagerMax - MAX_PAGE_LIST;
  61. }
  62. }
  63. pager.previousDots = null;
  64. if (pagerMin > 1) {
  65. pager.previousDots = true;
  66. }
  67. pager.nextDots = null;
  68. if (pagerMax < pagesCount) {
  69. pager.nextDots = true;
  70. }
  71. for (let i = pagerMin; i <= pagerMax; i++) {
  72. pager.pages.push(i);
  73. }
  74. return pager;
  75. }
  76. actions.index = function(req, res) {
  77. return res.render('admin/index', {
  78. plugins: pluginUtils.listPlugins(crowi.rootDir),
  79. });
  80. };
  81. // app.get('/admin/app' , admin.app.index);
  82. actions.app = {};
  83. actions.app.index = function(req, res) {
  84. return res.render('admin/app');
  85. };
  86. actions.app.settingUpdate = function(req, res) {
  87. };
  88. // app.get('/admin/security' , admin.security.index);
  89. actions.security = {};
  90. actions.security.index = function(req, res) {
  91. const isWikiModeForced = aclService.isWikiModeForced();
  92. const guestModeValue = aclService.getGuestModeValue();
  93. return res.render('admin/security', {
  94. isWikiModeForced,
  95. guestModeValue,
  96. });
  97. };
  98. // app.get('/admin/markdown' , admin.markdown.index);
  99. actions.markdown = {};
  100. actions.markdown.index = function(req, res) {
  101. const markdownSetting = configManager.getConfigByPrefix('markdown', 'markdown:');
  102. return res.render('admin/markdown', {
  103. markdownSetting,
  104. recommendedWhitelist,
  105. });
  106. };
  107. // app.post('/admin/markdown/lineBreaksSetting' , admin.markdown.lineBreaksSetting);
  108. actions.markdown.lineBreaksSetting = async function(req, res) {
  109. const markdownSetting = req.form.markdownSetting;
  110. if (req.form.isValid) {
  111. await configManager.updateConfigsInTheSameNamespace('markdown', markdownSetting);
  112. req.flash('successMessage', ['Successfully updated!']);
  113. }
  114. else {
  115. req.flash('errorMessage', req.form.errors);
  116. }
  117. return res.redirect('/admin/markdown');
  118. };
  119. // app.post('/admin/markdown/presentationSetting' , admin.markdown.presentationSetting);
  120. actions.markdown.presentationSetting = async function(req, res) {
  121. const markdownSetting = req.form.markdownSetting;
  122. if (req.form.isValid) {
  123. await configManager.updateConfigsInTheSameNamespace('markdown', markdownSetting);
  124. req.flash('successMessage', ['Successfully updated!']);
  125. }
  126. else {
  127. req.flash('errorMessage', req.form.errors);
  128. }
  129. return res.redirect('/admin/markdown');
  130. };
  131. // app.post('/admin/markdown/xss-setting' , admin.markdown.xssSetting);
  132. actions.markdown.xssSetting = async function(req, res) {
  133. const xssSetting = req.form.markdownSetting;
  134. xssSetting['markdown:xss:tagWhiteList'] = csvToArray(xssSetting['markdown:xss:tagWhiteList']);
  135. xssSetting['markdown:xss:attrWhiteList'] = csvToArray(xssSetting['markdown:xss:attrWhiteList']);
  136. if (req.form.isValid) {
  137. await configManager.updateConfigsInTheSameNamespace('markdown', xssSetting);
  138. req.flash('successMessage', ['Successfully updated!']);
  139. }
  140. else {
  141. req.flash('errorMessage', req.form.errors);
  142. }
  143. return res.redirect('/admin/markdown');
  144. };
  145. const csvToArray = (string) => {
  146. const array = string.split(',');
  147. return array.map((item) => { return item.trim() });
  148. };
  149. // app.get('/admin/customize' , admin.customize.index);
  150. actions.customize = {};
  151. actions.customize.index = function(req, res) {
  152. const settingForm = configManager.getConfigByPrefix('crowi', 'customize:');
  153. /* eslint-disable quote-props, no-multi-spaces */
  154. const highlightJsCssSelectorOptions = {
  155. 'github': { name: '[Light] GitHub', border: false },
  156. 'github-gist': { name: '[Light] GitHub Gist', border: true },
  157. 'atom-one-light': { name: '[Light] Atom One Light', border: true },
  158. 'xcode': { name: '[Light] Xcode', border: true },
  159. 'vs': { name: '[Light] Vs', border: true },
  160. 'atom-one-dark': { name: '[Dark] Atom One Dark', border: false },
  161. 'hybrid': { name: '[Dark] Hybrid', border: false },
  162. 'monokai': { name: '[Dark] Monokai', border: false },
  163. 'tomorrow-night': { name: '[Dark] Tomorrow Night', border: false },
  164. 'vs2015': { name: '[Dark] Vs 2015', border: false },
  165. };
  166. /* eslint-enable quote-props, no-multi-spaces */
  167. return res.render('admin/customize', {
  168. settingForm,
  169. highlightJsCssSelectorOptions,
  170. });
  171. };
  172. // app.get('/admin/notification' , admin.notification.index);
  173. actions.notification = {};
  174. actions.notification.index = async(req, res) => {
  175. const UpdatePost = crowi.model('UpdatePost');
  176. let slackSetting = configManager.getConfigByPrefix('notification', 'slack:');
  177. const hasSlackIwhUrl = !!configManager.getConfig('notification', 'slack:incomingWebhookUrl');
  178. const hasSlackToken = !!configManager.getConfig('notification', 'slack:token');
  179. if (!hasSlackIwhUrl) {
  180. slackSetting['slack:incomingWebhookUrl'] = '';
  181. }
  182. if (req.session.slackSetting) {
  183. slackSetting = req.session.slackSetting;
  184. req.session.slackSetting = null;
  185. }
  186. const globalNotifications = await GlobalNotificationSetting.findAll();
  187. const userNotifications = await UpdatePost.findAll();
  188. return res.render('admin/notification', {
  189. userNotifications,
  190. slackSetting,
  191. hasSlackIwhUrl,
  192. hasSlackToken,
  193. globalNotifications,
  194. });
  195. };
  196. // app.post('/admin/notification/slackSetting' , admin.notification.slackauth);
  197. actions.notification.slackSetting = async function(req, res) {
  198. const slackSetting = req.form.slackSetting;
  199. if (req.form.isValid) {
  200. await configManager.updateConfigsInTheSameNamespace('notification', slackSetting);
  201. req.flash('successMessage', ['Successfully Updated!']);
  202. // Re-setup
  203. crowi.setupSlack().then(() => {
  204. });
  205. }
  206. else {
  207. req.flash('errorMessage', req.form.errors);
  208. }
  209. return res.redirect('/admin/notification');
  210. };
  211. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  212. actions.notification.slackAuth = function(req, res) {
  213. const code = req.query.code;
  214. if (!code || !slackNotificationService.hasSlackConfig()) {
  215. return res.redirect('/admin/notification');
  216. }
  217. const slack = crowi.slack;
  218. slack.getOauthAccessToken(code)
  219. .then(async(data) => {
  220. debug('oauth response', data);
  221. try {
  222. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': data.access_token });
  223. req.flash('successMessage', ['Successfully Connected!']);
  224. }
  225. catch (err) {
  226. req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
  227. }
  228. return res.redirect('/admin/notification');
  229. })
  230. .catch((err) => {
  231. debug('oauth response ERROR', err);
  232. req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
  233. return res.redirect('/admin/notification');
  234. });
  235. };
  236. // app.post('/admin/notification/slackIwhSetting' , admin.notification.slackIwhSetting);
  237. actions.notification.slackIwhSetting = async function(req, res) {
  238. const slackIwhSetting = req.form.slackIwhSetting;
  239. if (req.form.isValid) {
  240. await configManager.updateConfigsInTheSameNamespace('notification', slackIwhSetting);
  241. req.flash('successMessage', ['Successfully Updated!']);
  242. // Re-setup
  243. crowi.setupSlack().then(() => {
  244. return res.redirect('/admin/notification#slack-incoming-webhooks');
  245. });
  246. }
  247. else {
  248. req.flash('errorMessage', req.form.errors);
  249. return res.redirect('/admin/notification#slack-incoming-webhooks');
  250. }
  251. };
  252. // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
  253. actions.notification.disconnectFromSlack = async function(req, res) {
  254. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': '' });
  255. req.flash('successMessage', ['Successfully Disconnected!']);
  256. return res.redirect('/admin/notification');
  257. };
  258. actions.globalNotification = {};
  259. actions.globalNotification.detail = async(req, res) => {
  260. const notificationSettingId = req.params.id;
  261. const renderVars = {};
  262. if (notificationSettingId) {
  263. try {
  264. renderVars.setting = await GlobalNotificationSetting.findOne({ _id: notificationSettingId });
  265. }
  266. catch (err) {
  267. logger.error(`Error in finding a global notification setting with {_id: ${notificationSettingId}}`);
  268. }
  269. }
  270. return res.render('admin/global-notification-detail', renderVars);
  271. };
  272. actions.globalNotification.create = (req, res) => {
  273. const form = req.form.notificationGlobal;
  274. let setting;
  275. switch (form.notifyToType) {
  276. case 'mail':
  277. setting = new GlobalNotificationMailSetting(crowi);
  278. setting.toEmail = form.toEmail;
  279. break;
  280. // case 'slack':
  281. // setting = new GlobalNotificationSlackSetting(crowi);
  282. // setting.slackChannels = form.slackChannels;
  283. // break;
  284. default:
  285. logger.error('GlobalNotificationSetting Type Error: undefined type');
  286. req.flash('errorMessage', 'Error occurred in creating a new global notification setting: undefined notification type');
  287. return res.redirect('/admin/notification#global-notification');
  288. }
  289. setting.triggerPath = form.triggerPath;
  290. setting.triggerEvents = getNotificationEvents(form);
  291. setting.save();
  292. return res.redirect('/admin/notification#global-notification');
  293. };
  294. actions.globalNotification.update = async(req, res) => {
  295. const form = req.form.notificationGlobal;
  296. const setting = await GlobalNotificationSetting.findOne({ _id: form.id });
  297. switch (form.notifyToType) {
  298. case 'mail':
  299. setting.toEmail = form.toEmail;
  300. break;
  301. // case 'slack':
  302. // setting.slackChannels = form.slackChannels;
  303. // break;
  304. default:
  305. logger.error('GlobalNotificationSetting Type Error: undefined type');
  306. req.flash('errorMessage', 'Error occurred in updating the global notification setting: undefined notification type');
  307. return res.redirect('/admin/notification#global-notification');
  308. }
  309. setting.triggerPath = form.triggerPath;
  310. setting.triggerEvents = getNotificationEvents(form);
  311. setting.save();
  312. return res.redirect('/admin/notification#global-notification');
  313. };
  314. actions.globalNotification.remove = async(req, res) => {
  315. const id = req.params.id;
  316. try {
  317. await GlobalNotificationSetting.findOneAndRemove({ _id: id });
  318. return res.redirect('/admin/notification#global-notification');
  319. }
  320. catch (err) {
  321. req.flash('errorMessage', 'Error in deleting global notification setting');
  322. return res.redirect('/admin/notification#global-notification');
  323. }
  324. };
  325. const getNotificationEvents = (form) => {
  326. const triggerEvents = [];
  327. const triggerEventKeys = Object.keys(form).filter((key) => { return key.match(/^triggerEvent/) });
  328. triggerEventKeys.forEach((key) => {
  329. if (form[key]) {
  330. triggerEvents.push(form[key]);
  331. }
  332. });
  333. return triggerEvents;
  334. };
  335. actions.search = {};
  336. actions.search.index = function(req, res) {
  337. const search = crowi.getSearcher();
  338. if (!search) {
  339. return res.redirect('/admin');
  340. }
  341. return res.render('admin/search', {});
  342. };
  343. actions.user = {};
  344. actions.user.index = async function(req, res) {
  345. const activeUsers = await User.countListByStatus(User.STATUS_ACTIVE);
  346. const userUpperLimit = aclService.userUpperLimit();
  347. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  348. const page = parseInt(req.query.page) || 1;
  349. const result = await User.findUsersWithPagination({
  350. page,
  351. select: User.USER_PUBLIC_FIELDS,
  352. populate: User.IMAGE_POPULATION,
  353. });
  354. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  355. return res.render('admin/users', {
  356. users: result.docs,
  357. pager,
  358. activeUsers,
  359. userUpperLimit,
  360. isUserCountExceedsUpperLimit,
  361. });
  362. };
  363. actions.user.invite = function(req, res) {
  364. const form = req.form.inviteForm;
  365. const toSendEmail = form.sendEmail || false;
  366. if (req.form.isValid) {
  367. User.createUsersByInvitation(form.emailList.split('\n'), toSendEmail, (err, userList) => {
  368. if (err) {
  369. req.flash('errorMessage', req.form.errors.join('\n'));
  370. }
  371. else {
  372. req.flash('createdUser', userList);
  373. }
  374. return res.redirect('/admin/users');
  375. });
  376. }
  377. else {
  378. req.flash('errorMessage', req.form.errors.join('\n'));
  379. return res.redirect('/admin/users');
  380. }
  381. };
  382. actions.user.makeAdmin = function(req, res) {
  383. const id = req.params.id;
  384. User.findById(id, (err, userData) => {
  385. userData.makeAdmin((err, userData) => {
  386. if (err === null) {
  387. req.flash('successMessage', `${userData.name}さんのアカウントを管理者に設定しました。`);
  388. }
  389. else {
  390. req.flash('errorMessage', '更新に失敗しました。');
  391. debug(err, userData);
  392. }
  393. return res.redirect('/admin/users');
  394. });
  395. });
  396. };
  397. actions.user.removeFromAdmin = function(req, res) {
  398. const id = req.params.id;
  399. User.findById(id, (err, userData) => {
  400. userData.removeFromAdmin((err, userData) => {
  401. if (err === null) {
  402. req.flash('successMessage', `${userData.name}さんのアカウントを管理者から外しました。`);
  403. }
  404. else {
  405. req.flash('errorMessage', '更新に失敗しました。');
  406. debug(err, userData);
  407. }
  408. return res.redirect('/admin/users');
  409. });
  410. });
  411. };
  412. actions.user.activate = async function(req, res) {
  413. // check user upper limit
  414. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  415. if (isUserCountExceedsUpperLimit) {
  416. req.flash('errorMessage', 'ユーザーが上限に達したため有効化できません。');
  417. return res.redirect('/admin/users');
  418. }
  419. const id = req.params.id;
  420. User.findById(id, (err, userData) => {
  421. userData.statusActivate((err, userData) => {
  422. if (err === null) {
  423. req.flash('successMessage', `${userData.name}さんのアカウントを有効化しました`);
  424. }
  425. else {
  426. req.flash('errorMessage', '更新に失敗しました。');
  427. debug(err, userData);
  428. }
  429. return res.redirect('/admin/users');
  430. });
  431. });
  432. };
  433. actions.user.suspend = function(req, res) {
  434. const id = req.params.id;
  435. User.findById(id, (err, userData) => {
  436. userData.statusSuspend((err, userData) => {
  437. if (err === null) {
  438. req.flash('successMessage', `${userData.name}さんのアカウントを利用停止にしました`);
  439. }
  440. else {
  441. req.flash('errorMessage', '更新に失敗しました。');
  442. debug(err, userData);
  443. }
  444. return res.redirect('/admin/users');
  445. });
  446. });
  447. };
  448. actions.user.remove = function(req, res) {
  449. const id = req.params.id;
  450. let username = '';
  451. return new Promise((resolve, reject) => {
  452. User.findById(id, (err, userData) => {
  453. username = userData.username;
  454. return resolve(userData);
  455. });
  456. })
  457. .then((userData) => {
  458. return new Promise((resolve, reject) => {
  459. userData.statusDelete((err, userData) => {
  460. if (err) {
  461. reject(err);
  462. }
  463. resolve(userData);
  464. });
  465. });
  466. })
  467. .then((userData) => {
  468. // remove all External Accounts
  469. return ExternalAccount.remove({ user: userData }).then(() => { return userData });
  470. })
  471. .then((userData) => {
  472. return Page.removeByPath(`/user/${username}`).then(() => { return userData });
  473. })
  474. .then((userData) => {
  475. req.flash('successMessage', `${username} さんのアカウントを削除しました`);
  476. return res.redirect('/admin/users');
  477. })
  478. .catch((err) => {
  479. req.flash('errorMessage', '削除に失敗しました。');
  480. return res.redirect('/admin/users');
  481. });
  482. };
  483. // これやったときの relation の挙動未確認
  484. actions.user.removeCompletely = function(req, res) {
  485. // ユーザーの物理削除
  486. const id = req.params.id;
  487. User.removeCompletelyById(id, (err, removed) => {
  488. if (err) {
  489. debug('Error while removing user.', err, id);
  490. req.flash('errorMessage', '完全な削除に失敗しました。');
  491. }
  492. else {
  493. req.flash('successMessage', '削除しました');
  494. }
  495. return res.redirect('/admin/users');
  496. });
  497. };
  498. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  499. actions.user.resetPassword = async function(req, res) {
  500. const id = req.body.user_id;
  501. const User = crowi.model('User');
  502. try {
  503. const newPassword = await User.resetPasswordByRandomString(id);
  504. const user = await User.findById(id);
  505. const result = { user: user.toObject(), newPassword };
  506. return res.json(ApiResponse.success(result));
  507. }
  508. catch (err) {
  509. debug('Error on reseting password', err);
  510. return res.json(ApiResponse.error(err));
  511. }
  512. };
  513. actions.externalAccount = {};
  514. actions.externalAccount.index = function(req, res) {
  515. const page = parseInt(req.query.page) || 1;
  516. ExternalAccount.findAllWithPagination({ page })
  517. .then((result) => {
  518. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  519. return res.render('admin/external-accounts', {
  520. accounts: result.docs,
  521. pager,
  522. });
  523. });
  524. };
  525. actions.externalAccount.remove = async function(req, res) {
  526. const id = req.params.id;
  527. let account = null;
  528. try {
  529. account = await ExternalAccount.findByIdAndRemove(id);
  530. if (account == null) {
  531. throw new Error('削除に失敗しました。');
  532. }
  533. }
  534. catch (err) {
  535. req.flash('errorMessage', err.message);
  536. return res.redirect('/admin/users/external-accounts');
  537. }
  538. req.flash('successMessage', `外部アカウント '${account.providerType}/${account.accountId}' を削除しました`);
  539. return res.redirect('/admin/users/external-accounts');
  540. };
  541. actions.userGroup = {};
  542. actions.userGroup.index = function(req, res) {
  543. const page = parseInt(req.query.page) || 1;
  544. const isAclEnabled = aclService.isAclEnabled();
  545. const renderVar = {
  546. userGroups: [],
  547. userGroupRelations: new Map(),
  548. pager: null,
  549. isAclEnabled,
  550. };
  551. UserGroup.findUserGroupsWithPagination({ page })
  552. .then((result) => {
  553. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  554. const userGroups = result.docs;
  555. renderVar.userGroups = userGroups;
  556. renderVar.pager = pager;
  557. return userGroups.map((userGroup) => {
  558. return new Promise((resolve, reject) => {
  559. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  560. .then((relations) => {
  561. return resolve({
  562. id: userGroup._id,
  563. relatedUsers: relations.map((relation) => {
  564. return relation.relatedUser;
  565. }),
  566. });
  567. });
  568. });
  569. });
  570. })
  571. .then((allRelationsPromise) => {
  572. return Promise.all(allRelationsPromise);
  573. })
  574. .then((relations) => {
  575. for (const relation of relations) {
  576. renderVar.userGroupRelations[relation.id] = relation.relatedUsers;
  577. }
  578. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  579. return res.render('admin/user-groups', renderVar);
  580. })
  581. .catch((err) => {
  582. debug('Error on find all relations', err);
  583. return res.json(ApiResponse.error('Error'));
  584. });
  585. };
  586. // グループ詳細
  587. actions.userGroup.detail = async function(req, res) {
  588. const userGroupId = req.params.id;
  589. const userGroup = await UserGroup.findOne({ _id: userGroupId });
  590. if (userGroup == null) {
  591. logger.error('no userGroup is exists. ', userGroupId);
  592. return res.redirect('/admin/user-groups');
  593. }
  594. return res.render('admin/user-group-detail', { userGroup });
  595. };
  596. // Importer management
  597. actions.importer = {};
  598. actions.importer.index = function(req, res) {
  599. const settingForm = configManager.getConfigByPrefix('crowi', 'importer:');
  600. return res.render('admin/importer', {
  601. settingForm,
  602. });
  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. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  899. importer.initializeEsaClient(); // let it run in the back aftert res
  900. return res.json({ status: true });
  901. };
  902. /**
  903. * save qiita settings, update config cache, and response json
  904. *
  905. * @param {*} req
  906. * @param {*} res
  907. */
  908. actions.api.importerSettingQiita = async(req, res) => {
  909. const form = req.form.settingForm;
  910. if (!req.form.isValid) {
  911. return res.json({ status: false, message: req.form.errors.join('\n') });
  912. }
  913. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  914. importer.initializeQiitaClient(); // let it run in the back aftert res
  915. return res.json({ status: true });
  916. };
  917. /**
  918. * Import all posts from esa
  919. *
  920. * @param {*} req
  921. * @param {*} res
  922. */
  923. actions.api.importDataFromEsa = async(req, res) => {
  924. const user = req.user;
  925. let errors;
  926. try {
  927. errors = await importer.importDataFromEsa(user);
  928. }
  929. catch (err) {
  930. errors = [err];
  931. }
  932. if (errors.length > 0) {
  933. return res.json({ status: false, message: `<br> - ${errors.join('<br> - ')}` });
  934. }
  935. return res.json({ status: true });
  936. };
  937. /**
  938. * Import all posts from qiita
  939. *
  940. * @param {*} req
  941. * @param {*} res
  942. */
  943. actions.api.importDataFromQiita = async(req, res) => {
  944. const user = req.user;
  945. let errors;
  946. try {
  947. errors = await importer.importDataFromQiita(user);
  948. }
  949. catch (err) {
  950. errors = [err];
  951. }
  952. if (errors.length > 0) {
  953. return res.json({ status: false, message: `<br> - ${errors.join('<br> - ')}` });
  954. }
  955. return res.json({ status: true });
  956. };
  957. /**
  958. * Test connection to esa and response result with json
  959. *
  960. * @param {*} req
  961. * @param {*} res
  962. */
  963. actions.api.testEsaAPI = async(req, res) => {
  964. try {
  965. await importer.testConnectionToEsa();
  966. return res.json({ status: true });
  967. }
  968. catch (err) {
  969. return res.json({ status: false, message: `${err}` });
  970. }
  971. };
  972. /**
  973. * Test connection to qiita and response result with json
  974. *
  975. * @param {*} req
  976. * @param {*} res
  977. */
  978. actions.api.testQiitaAPI = async(req, res) => {
  979. try {
  980. await importer.testConnectionToQiita();
  981. return res.json({ status: true });
  982. }
  983. catch (err) {
  984. return res.json({ status: false, message: `${err}` });
  985. }
  986. };
  987. actions.api.searchBuildIndex = async function(req, res) {
  988. const search = crowi.getSearcher();
  989. if (!search) {
  990. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  991. }
  992. // first, delete index
  993. try {
  994. await search.deleteIndex();
  995. }
  996. catch (err) {
  997. logger.warn('Delete index Error, but if it is initialize, its ok.', err);
  998. }
  999. // second, create index
  1000. try {
  1001. await search.buildIndex();
  1002. }
  1003. catch (err) {
  1004. logger.error('Error', err);
  1005. return res.json(ApiResponse.error(err));
  1006. }
  1007. searchEvent.on('addPageProgress', (total, current, skip) => {
  1008. crowi.getIo().sockets.emit('admin:addPageProgress', { total, current, skip });
  1009. });
  1010. searchEvent.on('finishAddPage', (total, current, skip) => {
  1011. crowi.getIo().sockets.emit('admin:finishAddPage', { total, current, skip });
  1012. });
  1013. // add all page
  1014. search
  1015. .addAllPages()
  1016. .then(() => {
  1017. debug('Data is successfully indexed. ------------------ ✧✧');
  1018. })
  1019. .catch((err) => {
  1020. logger.error('Error', err);
  1021. });
  1022. return res.json(ApiResponse.success());
  1023. };
  1024. function validateMailSetting(req, form, callback) {
  1025. const mailer = crowi.mailer;
  1026. const option = {
  1027. host: form['mail:smtpHost'],
  1028. port: form['mail:smtpPort'],
  1029. };
  1030. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  1031. option.auth = {
  1032. user: form['mail:smtpUser'],
  1033. pass: form['mail:smtpPassword'],
  1034. };
  1035. }
  1036. if (option.port === 465) {
  1037. option.secure = true;
  1038. }
  1039. const smtpClient = mailer.createSMTPClient(option);
  1040. debug('mailer setup for validate SMTP setting', smtpClient);
  1041. smtpClient.sendMail({
  1042. from: form['mail:from'],
  1043. to: req.user.email,
  1044. subject: 'Wiki管理設定のアップデートによるメール通知',
  1045. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。',
  1046. }, callback);
  1047. }
  1048. /**
  1049. * validate setting form values for SAML
  1050. *
  1051. * This validation checks, for the value of each mandatory items,
  1052. * whether it from the environment variables is empty and form value to update it is empty.
  1053. */
  1054. function validateSamlSettingForm(form, t) {
  1055. for (const key of crowi.passportService.mandatoryConfigKeysForSaml) {
  1056. const formValue = form.settingForm[key];
  1057. if (configManager.getConfigFromEnvVars('crowi', key) === null && formValue === '') {
  1058. const formItemName = t(`security_setting.form_item_name.${key}`);
  1059. form.errors.push(t('form_validation.required', formItemName));
  1060. }
  1061. }
  1062. }
  1063. return actions;
  1064. };