admin.js 34 KB

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