admin.js 31 KB

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