admin.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  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. const page = parseInt(req.query.page) || 1;
  406. ExternalAccount.findAllWithPagination({ page })
  407. .then((result) => {
  408. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  409. return res.render('admin/external-accounts', {
  410. accounts: result.docs,
  411. pager,
  412. });
  413. });
  414. };
  415. actions.externalAccount.remove = async function(req, res) {
  416. const id = req.params.id;
  417. let account = null;
  418. try {
  419. account = await ExternalAccount.findByIdAndRemove(id);
  420. if (account == null) {
  421. throw new Error('削除に失敗しました。');
  422. }
  423. }
  424. catch (err) {
  425. req.flash('errorMessage', err.message);
  426. return res.redirect('/admin/users/external-accounts');
  427. }
  428. req.flash('successMessage', `外部アカウント '${account.providerType}/${account.accountId}' を削除しました`);
  429. return res.redirect('/admin/users/external-accounts');
  430. };
  431. actions.userGroup = {};
  432. actions.userGroup.index = function(req, res) {
  433. const page = parseInt(req.query.page) || 1;
  434. const isAclEnabled = aclService.isAclEnabled();
  435. const renderVar = {
  436. userGroups: [],
  437. userGroupRelations: new Map(),
  438. pager: null,
  439. isAclEnabled,
  440. };
  441. UserGroup.findUserGroupsWithPagination({ page })
  442. .then((result) => {
  443. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  444. const userGroups = result.docs;
  445. renderVar.userGroups = userGroups;
  446. renderVar.pager = pager;
  447. return userGroups.map((userGroup) => {
  448. return new Promise((resolve, reject) => {
  449. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  450. .then((relations) => {
  451. return resolve({
  452. id: userGroup._id,
  453. relatedUsers: relations.map((relation) => {
  454. return relation.relatedUser;
  455. }),
  456. });
  457. });
  458. });
  459. });
  460. })
  461. .then((allRelationsPromise) => {
  462. return Promise.all(allRelationsPromise);
  463. })
  464. .then((relations) => {
  465. for (const relation of relations) {
  466. renderVar.userGroupRelations[relation.id] = relation.relatedUsers;
  467. }
  468. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  469. return res.render('admin/user-groups', renderVar);
  470. })
  471. .catch((err) => {
  472. debug('Error on find all relations', err);
  473. return res.json(ApiResponse.error('Error'));
  474. });
  475. };
  476. // グループ詳細
  477. actions.userGroup.detail = async function(req, res) {
  478. const userGroupId = req.params.id;
  479. const userGroup = await UserGroup.findOne({ _id: userGroupId });
  480. if (userGroup == null) {
  481. logger.error('no userGroup is exists. ', userGroupId);
  482. return res.redirect('/admin/user-groups');
  483. }
  484. return res.render('admin/user-group-detail', { userGroup });
  485. };
  486. // Importer management
  487. actions.importer = {};
  488. actions.importer.api = api;
  489. api.validators = {};
  490. api.validators.importer = {};
  491. actions.importer.index = function(req, res) {
  492. const settingForm = configManager.getConfigByPrefix('crowi', 'importer:');
  493. return res.render('admin/importer', {
  494. settingForm,
  495. });
  496. };
  497. api.validators.importer.esa = function() {
  498. const validator = [
  499. check('importer:esa:team_name').not().isEmpty().withMessage('Error. Empty esa:team_name'),
  500. check('importer:esa:access_token').not().isEmpty().withMessage('Error. Empty esa:access_token'),
  501. ];
  502. return validator;
  503. };
  504. api.validators.importer.qiita = function() {
  505. const validator = [
  506. check('importer:qiita:team_name').not().isEmpty().withMessage('Error. Empty qiita:team_name'),
  507. check('importer:qiita:access_token').not().isEmpty().withMessage('Error. Empty qiita:access_token'),
  508. ];
  509. return validator;
  510. };
  511. // Export management
  512. actions.export = {};
  513. actions.export.index = (req, res) => {
  514. return res.render('admin/export');
  515. };
  516. actions.export.download = (req, res) => {
  517. // TODO: add express validator
  518. const { fileName } = req.params;
  519. try {
  520. const zipFile = exportService.getFile(fileName);
  521. return res.download(zipFile);
  522. }
  523. catch (err) {
  524. // TODO: use ApiV3Error
  525. logger.error(err);
  526. return res.json(ApiResponse.error());
  527. }
  528. };
  529. actions.api = {};
  530. actions.api.appSetting = async function(req, res) {
  531. const form = req.form.settingForm;
  532. if (req.form.isValid) {
  533. debug('form content', form);
  534. // mail setting ならここで validation
  535. if (form['mail:from']) {
  536. validateMailSetting(req, form, async(err, data) => {
  537. debug('Error validate mail setting: ', err, data);
  538. if (err) {
  539. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  540. return res.json({ status: false, message: req.form.errors.join('\n') });
  541. }
  542. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  543. return res.json({ status: true });
  544. });
  545. }
  546. else {
  547. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  548. return res.json({ status: true });
  549. }
  550. }
  551. else {
  552. return res.json({ status: false, message: req.form.errors.join('\n') });
  553. }
  554. };
  555. actions.api.asyncAppSetting = async(req, res) => {
  556. const form = req.form.settingForm;
  557. if (!req.form.isValid) {
  558. return res.json({ status: false, message: req.form.errors.join('\n') });
  559. }
  560. debug('form content', form);
  561. try {
  562. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  563. return res.json({ status: true });
  564. }
  565. catch (err) {
  566. logger.error(err);
  567. return res.json({ status: false });
  568. }
  569. };
  570. actions.api.securitySetting = async function(req, res) {
  571. if (!req.form.isValid) {
  572. return res.json({ status: false, message: req.form.errors.join('\n') });
  573. }
  574. const form = req.form.settingForm;
  575. if (aclService.isWikiModeForced()) {
  576. logger.debug('security:restrictGuestMode will not be changed because wiki mode is forced to set');
  577. delete form['security:restrictGuestMode'];
  578. }
  579. try {
  580. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  581. return res.json({ status: true });
  582. }
  583. catch (err) {
  584. logger.error(err);
  585. return res.json({ status: false });
  586. }
  587. };
  588. actions.api.securityPassportLocalSetting = 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.resetLocalStrategy();
  598. // setup strategy
  599. if (configManager.getConfig('crowi', 'security:passport-local:isEnabled')) {
  600. crowi.passportService.setupLocalStrategy(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.securityPassportLdapSetting = async function(req, res) {
  610. const form = req.form.settingForm;
  611. if (!req.form.isValid) {
  612. return res.json({ status: false, message: req.form.errors.join('\n') });
  613. }
  614. debug('form content', form);
  615. try {
  616. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  617. // reset strategy
  618. crowi.passportService.resetLdapStrategy();
  619. // setup strategy
  620. if (configManager.getConfig('crowi', 'security:passport-ldap:isEnabled')) {
  621. crowi.passportService.setupLdapStrategy(true);
  622. }
  623. }
  624. catch (err) {
  625. logger.error(err);
  626. return res.json({ status: false, message: err.message });
  627. }
  628. return res.json({ status: true });
  629. };
  630. actions.api.securityPassportSamlSetting = async(req, res) => {
  631. const form = req.form.settingForm;
  632. validateSamlSettingForm(req.form, req.t);
  633. if (!req.form.isValid) {
  634. return res.json({ status: false, message: req.form.errors.join('\n') });
  635. }
  636. debug('form content', form);
  637. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  638. // reset strategy
  639. await crowi.passportService.resetSamlStrategy();
  640. // setup strategy
  641. if (configManager.getConfig('crowi', 'security:passport-saml:isEnabled')) {
  642. try {
  643. await crowi.passportService.setupSamlStrategy(true);
  644. }
  645. catch (err) {
  646. // reset
  647. await crowi.passportService.resetSamlStrategy();
  648. return res.json({ status: false, message: err.message });
  649. }
  650. }
  651. return res.json({ status: true });
  652. };
  653. actions.api.securityPassportBasicSetting = async(req, res) => {
  654. const form = req.form.settingForm;
  655. if (!req.form.isValid) {
  656. return res.json({ status: false, message: req.form.errors.join('\n') });
  657. }
  658. debug('form content', form);
  659. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  660. // reset strategy
  661. await crowi.passportService.resetBasicStrategy();
  662. // setup strategy
  663. if (configManager.getConfig('crowi', 'security:passport-basic:isEnabled')) {
  664. try {
  665. await crowi.passportService.setupBasicStrategy(true);
  666. }
  667. catch (err) {
  668. // reset
  669. await crowi.passportService.resetBasicStrategy();
  670. return res.json({ status: false, message: err.message });
  671. }
  672. }
  673. return res.json({ status: true });
  674. };
  675. actions.api.securityPassportGoogleSetting = async(req, res) => {
  676. const form = req.form.settingForm;
  677. if (!req.form.isValid) {
  678. return res.json({ status: false, message: req.form.errors.join('\n') });
  679. }
  680. debug('form content', form);
  681. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  682. // reset strategy
  683. await crowi.passportService.resetGoogleStrategy();
  684. // setup strategy
  685. if (configManager.getConfig('crowi', 'security:passport-google:isEnabled')) {
  686. try {
  687. await crowi.passportService.setupGoogleStrategy(true);
  688. }
  689. catch (err) {
  690. // reset
  691. await crowi.passportService.resetGoogleStrategy();
  692. return res.json({ status: false, message: err.message });
  693. }
  694. }
  695. return res.json({ status: true });
  696. };
  697. actions.api.securityPassportGitHubSetting = async(req, res) => {
  698. const form = req.form.settingForm;
  699. if (!req.form.isValid) {
  700. return res.json({ status: false, message: req.form.errors.join('\n') });
  701. }
  702. debug('form content', form);
  703. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  704. // reset strategy
  705. await crowi.passportService.resetGitHubStrategy();
  706. // setup strategy
  707. if (configManager.getConfig('crowi', 'security:passport-github:isEnabled')) {
  708. try {
  709. await crowi.passportService.setupGitHubStrategy(true);
  710. }
  711. catch (err) {
  712. // reset
  713. await crowi.passportService.resetGitHubStrategy();
  714. return res.json({ status: false, message: err.message });
  715. }
  716. }
  717. return res.json({ status: true });
  718. };
  719. actions.api.securityPassportTwitterSetting = async(req, res) => {
  720. const form = req.form.settingForm;
  721. if (!req.form.isValid) {
  722. return res.json({ status: false, message: req.form.errors.join('\n') });
  723. }
  724. debug('form content', form);
  725. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  726. // reset strategy
  727. await crowi.passportService.resetTwitterStrategy();
  728. // setup strategy
  729. if (configManager.getConfig('crowi', 'security:passport-twitter:isEnabled')) {
  730. try {
  731. await crowi.passportService.setupTwitterStrategy(true);
  732. }
  733. catch (err) {
  734. // reset
  735. await crowi.passportService.resetTwitterStrategy();
  736. return res.json({ status: false, message: err.message });
  737. }
  738. }
  739. return res.json({ status: true });
  740. };
  741. actions.api.securityPassportOidcSetting = async(req, res) => {
  742. const form = req.form.settingForm;
  743. if (!req.form.isValid) {
  744. return res.json({ status: false, message: req.form.errors.join('\n') });
  745. }
  746. debug('form content', form);
  747. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  748. // reset strategy
  749. await crowi.passportService.resetOidcStrategy();
  750. // setup strategy
  751. if (configManager.getConfig('crowi', 'security:passport-oidc:isEnabled')) {
  752. try {
  753. await crowi.passportService.setupOidcStrategy(true);
  754. }
  755. catch (err) {
  756. // reset
  757. await crowi.passportService.resetOidcStrategy();
  758. return res.json({ status: false, message: err.message });
  759. }
  760. }
  761. return res.json({ status: true });
  762. };
  763. actions.api.customizeSetting = async function(req, res) {
  764. const form = req.form.settingForm;
  765. if (req.form.isValid) {
  766. debug('form content', form);
  767. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  768. customizeService.initCustomCss();
  769. customizeService.initCustomTitle();
  770. return res.json({ status: true });
  771. }
  772. return res.json({ status: false, message: req.form.errors.join('\n') });
  773. };
  774. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  775. actions.api.notificationAdd = function(req, res) {
  776. const UpdatePost = crowi.model('UpdatePost');
  777. const pathPattern = req.body.pathPattern;
  778. const channel = req.body.channel;
  779. debug('notification.add', pathPattern, channel);
  780. UpdatePost.create(pathPattern, channel, req.user)
  781. .then((doc) => {
  782. debug('Successfully save updatePost', doc);
  783. // fixme: うーん
  784. doc.creator = doc.creator._id.toString();
  785. return res.json(ApiResponse.success({ updatePost: doc }));
  786. })
  787. .catch((err) => {
  788. debug('Failed to save updatePost', err);
  789. return res.json(ApiResponse.error());
  790. });
  791. };
  792. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  793. actions.api.notificationRemove = function(req, res) {
  794. const UpdatePost = crowi.model('UpdatePost');
  795. const id = req.body.id;
  796. UpdatePost.remove(id)
  797. .then(() => {
  798. debug('Successfully remove updatePost');
  799. return res.json(ApiResponse.success({}));
  800. })
  801. .catch((err) => {
  802. debug('Failed to remove updatePost', err);
  803. return res.json(ApiResponse.error());
  804. });
  805. };
  806. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  807. actions.api.usersSearch = function(req, res) {
  808. const User = crowi.model('User');
  809. const email = req.query.email;
  810. User.findUsersByPartOfEmail(email, {})
  811. .then((users) => {
  812. const result = {
  813. data: users,
  814. };
  815. return res.json(ApiResponse.success(result));
  816. })
  817. .catch((err) => {
  818. return res.json(ApiResponse.error());
  819. });
  820. };
  821. actions.api.toggleIsEnabledForGlobalNotification = async(req, res) => {
  822. const id = req.query.id;
  823. const isEnabled = (req.query.isEnabled === 'true');
  824. try {
  825. if (isEnabled) {
  826. await GlobalNotificationSetting.enable(id);
  827. }
  828. else {
  829. await GlobalNotificationSetting.disable(id);
  830. }
  831. return res.json(ApiResponse.success());
  832. }
  833. catch (err) {
  834. return res.json(ApiResponse.error());
  835. }
  836. };
  837. /**
  838. * save esa settings, update config cache, and response json
  839. *
  840. * @param {*} req
  841. * @param {*} res
  842. */
  843. actions.api.importerSettingEsa = async(req, res) => {
  844. const form = req.body;
  845. const { validationResult } = require('express-validator');
  846. const errors = validationResult(req);
  847. if (!errors.isEmpty()) {
  848. return res.json(ApiResponse.error('esa.io form is blank'));
  849. }
  850. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  851. importer.initializeEsaClient(); // let it run in the back aftert res
  852. return res.json(ApiResponse.success());
  853. };
  854. /**
  855. * save qiita settings, update config cache, and response json
  856. *
  857. * @param {*} req
  858. * @param {*} res
  859. */
  860. actions.api.importerSettingQiita = async(req, res) => {
  861. const form = req.body;
  862. const { validationResult } = require('express-validator');
  863. const errors = validationResult(req);
  864. if (!errors.isEmpty()) {
  865. return res.json(ApiResponse.error('Qiita form is blank'));
  866. }
  867. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  868. importer.initializeQiitaClient(); // let it run in the back aftert res
  869. return res.json(ApiResponse.success());
  870. };
  871. /**
  872. * Import all posts from esa
  873. *
  874. * @param {*} req
  875. * @param {*} res
  876. */
  877. actions.api.importDataFromEsa = async(req, res) => {
  878. const user = req.user;
  879. let errors;
  880. try {
  881. errors = await importer.importDataFromEsa(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. * Import all posts from qiita
  893. *
  894. * @param {*} req
  895. * @param {*} res
  896. */
  897. actions.api.importDataFromQiita = async(req, res) => {
  898. const user = req.user;
  899. let errors;
  900. try {
  901. errors = await importer.importDataFromQiita(user);
  902. }
  903. catch (err) {
  904. errors = [err];
  905. }
  906. if (errors.length > 0) {
  907. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  908. }
  909. return res.json(ApiResponse.success());
  910. };
  911. /**
  912. * Test connection to esa and response result with json
  913. *
  914. * @param {*} req
  915. * @param {*} res
  916. */
  917. actions.api.testEsaAPI = async(req, res) => {
  918. try {
  919. await importer.testConnectionToEsa();
  920. return res.json(ApiResponse.success());
  921. }
  922. catch (err) {
  923. return res.json(ApiResponse.error(err));
  924. }
  925. };
  926. /**
  927. * Test connection to qiita and response result with json
  928. *
  929. * @param {*} req
  930. * @param {*} res
  931. */
  932. actions.api.testQiitaAPI = async(req, res) => {
  933. try {
  934. await importer.testConnectionToQiita();
  935. return res.json(ApiResponse.success());
  936. }
  937. catch (err) {
  938. return res.json(ApiResponse.error(err));
  939. }
  940. };
  941. actions.api.searchBuildIndex = async function(req, res) {
  942. const search = crowi.getSearcher();
  943. if (!search) {
  944. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  945. }
  946. try {
  947. search.buildIndex();
  948. }
  949. catch (err) {
  950. return res.json(ApiResponse.error(err));
  951. }
  952. return res.json(ApiResponse.success());
  953. };
  954. function validateMailSetting(req, form, callback) {
  955. const mailer = crowi.mailer;
  956. const option = {
  957. host: form['mail:smtpHost'],
  958. port: form['mail:smtpPort'],
  959. };
  960. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  961. option.auth = {
  962. user: form['mail:smtpUser'],
  963. pass: form['mail:smtpPassword'],
  964. };
  965. }
  966. if (option.port === 465) {
  967. option.secure = true;
  968. }
  969. const smtpClient = mailer.createSMTPClient(option);
  970. debug('mailer setup for validate SMTP setting', smtpClient);
  971. smtpClient.sendMail({
  972. from: form['mail:from'],
  973. to: req.user.email,
  974. subject: 'Wiki管理設定のアップデートによるメール通知',
  975. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。',
  976. }, callback);
  977. }
  978. /**
  979. * validate setting form values for SAML
  980. *
  981. * This validation checks, for the value of each mandatory items,
  982. * whether it from the environment variables is empty and form value to update it is empty.
  983. */
  984. function validateSamlSettingForm(form, t) {
  985. for (const key of crowi.passportService.mandatoryConfigKeysForSaml) {
  986. const formValue = form.settingForm[key];
  987. if (configManager.getConfigFromEnvVars('crowi', key) === null && formValue === '') {
  988. const formItemName = t(`security_setting.form_item_name.${key}`);
  989. form.errors.push(t('form_validation.required', formItemName));
  990. }
  991. }
  992. }
  993. return actions;
  994. };