admin.js 35 KB

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