admin.js 35 KB

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