admin.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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 {
  12. configManager,
  13. aclService,
  14. slackNotificationService,
  15. exportService,
  16. } = crowi;
  17. const recommendedWhitelist = require('@commons/service/xss/recommended-whitelist');
  18. const ApiResponse = require('../util/apiResponse');
  19. const importer = require('../util/importer')(crowi);
  20. const searchEvent = crowi.event('search');
  21. const MAX_PAGE_LIST = 50;
  22. const actions = {};
  23. const { check } = require('express-validator/check');
  24. const api = {};
  25. function createPager(total, limit, page, pagesCount, maxPageList) {
  26. const pager = {
  27. page,
  28. pagesCount,
  29. pages: [],
  30. total,
  31. previous: null,
  32. previousDots: false,
  33. next: null,
  34. nextDots: false,
  35. };
  36. if (page > 1) {
  37. pager.previous = page - 1;
  38. }
  39. if (page < pagesCount) {
  40. pager.next = page + 1;
  41. }
  42. let pagerMin = Math.max(1, Math.ceil(page - maxPageList / 2));
  43. let pagerMax = Math.min(pagesCount, Math.floor(page + maxPageList / 2));
  44. if (pagerMin === 1) {
  45. if (MAX_PAGE_LIST < pagesCount) {
  46. pagerMax = MAX_PAGE_LIST;
  47. }
  48. else {
  49. pagerMax = pagesCount;
  50. }
  51. }
  52. if (pagerMax === pagesCount) {
  53. if ((pagerMax - MAX_PAGE_LIST) < 1) {
  54. pagerMin = 1;
  55. }
  56. else {
  57. pagerMin = pagerMax - MAX_PAGE_LIST;
  58. }
  59. }
  60. pager.previousDots = null;
  61. if (pagerMin > 1) {
  62. pager.previousDots = true;
  63. }
  64. pager.nextDots = null;
  65. if (pagerMax < pagesCount) {
  66. pager.nextDots = true;
  67. }
  68. for (let i = pagerMin; i <= pagerMax; i++) {
  69. pager.pages.push(i);
  70. }
  71. return pager;
  72. }
  73. // setup websocket event for rebuild index
  74. searchEvent.on('addPageProgress', (total, current, skip) => {
  75. crowi.getIo().sockets.emit('admin:addPageProgress', { total, current, skip });
  76. });
  77. searchEvent.on('finishAddPage', (total, current, skip) => {
  78. crowi.getIo().sockets.emit('admin:finishAddPage', { total, current, skip });
  79. });
  80. searchEvent.on('rebuildingFailed', (error) => {
  81. crowi.getIo().sockets.emit('admin:rebuildingFailed', { error: error.message });
  82. });
  83. actions.index = function(req, res) {
  84. return res.render('admin/index');
  85. };
  86. // app.get('/admin/app' , admin.app.index);
  87. actions.app = {};
  88. actions.app.index = function(req, res) {
  89. return res.render('admin/app');
  90. };
  91. actions.app.settingUpdate = function(req, res) {
  92. };
  93. // app.get('/admin/security' , admin.security.index);
  94. actions.security = {};
  95. actions.security.index = function(req, res) {
  96. const isWikiModeForced = aclService.isWikiModeForced();
  97. const guestModeValue = aclService.getGuestModeValue();
  98. return res.render('admin/security', {
  99. isWikiModeForced,
  100. guestModeValue,
  101. });
  102. };
  103. // app.get('/admin/markdown' , admin.markdown.index);
  104. actions.markdown = {};
  105. actions.markdown.index = function(req, res) {
  106. const markdownSetting = configManager.getConfigByPrefix('markdown', 'markdown:');
  107. return res.render('admin/markdown', {
  108. markdownSetting,
  109. recommendedWhitelist,
  110. });
  111. };
  112. // app.get('/admin/customize' , admin.customize.index);
  113. actions.customize = {};
  114. actions.customize.index = function(req, res) {
  115. const settingForm = configManager.getConfigByPrefix('crowi', 'customize:');
  116. // TODO delete after apiV3
  117. /* eslint-disable quote-props, no-multi-spaces */
  118. const highlightJsCssSelectorOptions = {
  119. 'github': { name: '[Light] GitHub', border: false },
  120. 'github-gist': { name: '[Light] GitHub Gist', border: true },
  121. 'atom-one-light': { name: '[Light] Atom One Light', border: true },
  122. 'xcode': { name: '[Light] Xcode', border: true },
  123. 'vs': { name: '[Light] Vs', border: true },
  124. 'atom-one-dark': { name: '[Dark] Atom One Dark', border: false },
  125. 'hybrid': { name: '[Dark] Hybrid', border: false },
  126. 'monokai': { name: '[Dark] Monokai', border: false },
  127. 'tomorrow-night': { name: '[Dark] Tomorrow Night', border: false },
  128. 'vs2015': { name: '[Dark] Vs 2015', border: false },
  129. };
  130. /* eslint-enable quote-props, no-multi-spaces */
  131. return res.render('admin/customize', {
  132. settingForm,
  133. highlightJsCssSelectorOptions,
  134. });
  135. };
  136. // app.get('/admin/notification' , admin.notification.index);
  137. actions.notification = {};
  138. actions.notification.index = async(req, res) => {
  139. return res.render('admin/notification');
  140. };
  141. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  142. actions.notification.slackAuth = function(req, res) {
  143. const code = req.query.code;
  144. if (!code || !slackNotificationService.hasSlackConfig()) {
  145. return res.redirect('/admin/notification');
  146. }
  147. const slack = crowi.slack;
  148. slack.getOauthAccessToken(code)
  149. .then(async(data) => {
  150. debug('oauth response', data);
  151. try {
  152. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': data.access_token });
  153. req.flash('successMessage', ['Successfully Connected!']);
  154. }
  155. catch (err) {
  156. req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
  157. }
  158. return res.redirect('/admin/notification');
  159. })
  160. .catch((err) => {
  161. debug('oauth response ERROR', err);
  162. req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
  163. return res.redirect('/admin/notification');
  164. });
  165. };
  166. // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
  167. actions.notification.disconnectFromSlack = async function(req, res) {
  168. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': '' });
  169. req.flash('successMessage', ['Successfully Disconnected!']);
  170. return res.redirect('/admin/notification');
  171. };
  172. actions.globalNotification = {};
  173. actions.globalNotification.detail = async(req, res) => {
  174. const notificationSettingId = req.params.id;
  175. let globalNotification;
  176. if (notificationSettingId) {
  177. try {
  178. globalNotification = await GlobalNotificationSetting.findOne({ _id: notificationSettingId });
  179. }
  180. catch (err) {
  181. logger.error(`Error in finding a global notification setting with {_id: ${notificationSettingId}}`);
  182. }
  183. }
  184. return res.render('admin/global-notification-detail', { globalNotification });
  185. };
  186. actions.search = {};
  187. actions.search.index = function(req, res) {
  188. return res.render('admin/search', {});
  189. };
  190. actions.user = {};
  191. actions.user.index = async function(req, res) {
  192. return res.render('admin/users');
  193. };
  194. // これやったときの relation の挙動未確認
  195. actions.user.removeCompletely = function(req, res) {
  196. // ユーザーの物理削除
  197. const id = req.params.id;
  198. User.removeCompletelyById(id, (err, removed) => {
  199. if (err) {
  200. debug('Error while removing user.', err, id);
  201. req.flash('errorMessage', '完全な削除に失敗しました。');
  202. }
  203. else {
  204. req.flash('successMessage', '削除しました');
  205. }
  206. return res.redirect('/admin/users');
  207. });
  208. };
  209. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  210. actions.user.resetPassword = async function(req, res) {
  211. const id = req.body.user_id;
  212. const User = crowi.model('User');
  213. try {
  214. const newPassword = await User.resetPasswordByRandomString(id);
  215. const user = await User.findById(id);
  216. const result = { user: user.toObject(), newPassword };
  217. return res.json(ApiResponse.success(result));
  218. }
  219. catch (err) {
  220. debug('Error on reseting password', err);
  221. return res.json(ApiResponse.error(err));
  222. }
  223. };
  224. actions.externalAccount = {};
  225. actions.externalAccount.index = function(req, res) {
  226. return res.render('admin/external-accounts');
  227. };
  228. actions.externalAccount.remove = async function(req, res) {
  229. const id = req.params.id;
  230. let account = null;
  231. try {
  232. account = await ExternalAccount.findByIdAndRemove(id);
  233. if (account == null) {
  234. throw new Error('削除に失敗しました。');
  235. }
  236. }
  237. catch (err) {
  238. req.flash('errorMessage', err.message);
  239. return res.redirect('/admin/users/external-accounts');
  240. }
  241. req.flash('successMessage', `外部アカウント '${account.providerType}/${account.accountId}' を削除しました`);
  242. return res.redirect('/admin/users/external-accounts');
  243. };
  244. actions.userGroup = {};
  245. actions.userGroup.index = function(req, res) {
  246. const page = parseInt(req.query.page) || 1;
  247. const isAclEnabled = aclService.isAclEnabled();
  248. const renderVar = {
  249. userGroups: [],
  250. userGroupRelations: new Map(),
  251. pager: null,
  252. isAclEnabled,
  253. };
  254. UserGroup.findUserGroupsWithPagination({ page })
  255. .then((result) => {
  256. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  257. const userGroups = result.docs;
  258. renderVar.userGroups = userGroups;
  259. renderVar.pager = pager;
  260. return userGroups.map((userGroup) => {
  261. return new Promise((resolve, reject) => {
  262. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  263. .then((relations) => {
  264. return resolve({
  265. id: userGroup._id,
  266. relatedUsers: relations.map((relation) => {
  267. return relation.relatedUser;
  268. }),
  269. });
  270. });
  271. });
  272. });
  273. })
  274. .then((allRelationsPromise) => {
  275. return Promise.all(allRelationsPromise);
  276. })
  277. .then((relations) => {
  278. for (const relation of relations) {
  279. renderVar.userGroupRelations[relation.id] = relation.relatedUsers;
  280. }
  281. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  282. return res.render('admin/user-groups', renderVar);
  283. })
  284. .catch((err) => {
  285. debug('Error on find all relations', err);
  286. return res.json(ApiResponse.error('Error'));
  287. });
  288. };
  289. // グループ詳細
  290. actions.userGroup.detail = async function(req, res) {
  291. const userGroupId = req.params.id;
  292. const userGroup = await UserGroup.findOne({ _id: userGroupId });
  293. if (userGroup == null) {
  294. logger.error('no userGroup is exists. ', userGroupId);
  295. return res.redirect('/admin/user-groups');
  296. }
  297. return res.render('admin/user-group-detail', { userGroup });
  298. };
  299. // Importer management
  300. actions.importer = {};
  301. actions.importer.api = api;
  302. api.validators = {};
  303. api.validators.importer = {};
  304. actions.importer.index = function(req, res) {
  305. const settingForm = configManager.getConfigByPrefix('crowi', 'importer:');
  306. return res.render('admin/importer', {
  307. settingForm,
  308. });
  309. };
  310. api.validators.importer.esa = function() {
  311. const validator = [
  312. check('importer:esa:team_name').not().isEmpty().withMessage('Error. Empty esa:team_name'),
  313. check('importer:esa:access_token').not().isEmpty().withMessage('Error. Empty esa:access_token'),
  314. ];
  315. return validator;
  316. };
  317. api.validators.importer.qiita = function() {
  318. const validator = [
  319. check('importer:qiita:team_name').not().isEmpty().withMessage('Error. Empty qiita:team_name'),
  320. check('importer:qiita:access_token').not().isEmpty().withMessage('Error. Empty qiita:access_token'),
  321. ];
  322. return validator;
  323. };
  324. // Export management
  325. actions.export = {};
  326. actions.export.index = (req, res) => {
  327. return res.render('admin/export');
  328. };
  329. actions.export.download = (req, res) => {
  330. // TODO: add express validator
  331. const { fileName } = req.params;
  332. try {
  333. const zipFile = exportService.getFile(fileName);
  334. return res.download(zipFile);
  335. }
  336. catch (err) {
  337. // TODO: use ApiV3Error
  338. logger.error(err);
  339. return res.json(ApiResponse.error());
  340. }
  341. };
  342. actions.api = {};
  343. actions.api.securitySetting = async function(req, res) {
  344. if (!req.form.isValid) {
  345. return res.json({ status: false, message: req.form.errors.join('\n') });
  346. }
  347. const form = req.form.settingForm;
  348. if (aclService.isWikiModeForced()) {
  349. logger.debug('security:restrictGuestMode will not be changed because wiki mode is forced to set');
  350. delete form['security:restrictGuestMode'];
  351. }
  352. try {
  353. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  354. return res.json({ status: true });
  355. }
  356. catch (err) {
  357. logger.error(err);
  358. return res.json({ status: false });
  359. }
  360. };
  361. actions.api.securityPassportLocalSetting = async function(req, res) {
  362. const form = req.form.settingForm;
  363. if (!req.form.isValid) {
  364. return res.json({ status: false, message: req.form.errors.join('\n') });
  365. }
  366. debug('form content', form);
  367. try {
  368. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  369. // reset strategy
  370. crowi.passportService.resetLocalStrategy();
  371. // setup strategy
  372. if (configManager.getConfig('crowi', 'security:passport-local:isEnabled')) {
  373. crowi.passportService.setupLocalStrategy(true);
  374. }
  375. }
  376. catch (err) {
  377. logger.error(err);
  378. return res.json({ status: false, message: err.message });
  379. }
  380. return res.json({ status: true });
  381. };
  382. actions.api.securityPassportLdapSetting = async function(req, res) {
  383. const form = req.form.settingForm;
  384. if (!req.form.isValid) {
  385. return res.json({ status: false, message: req.form.errors.join('\n') });
  386. }
  387. debug('form content', form);
  388. try {
  389. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  390. // reset strategy
  391. crowi.passportService.resetLdapStrategy();
  392. // setup strategy
  393. if (configManager.getConfig('crowi', 'security:passport-ldap:isEnabled')) {
  394. crowi.passportService.setupLdapStrategy(true);
  395. }
  396. }
  397. catch (err) {
  398. logger.error(err);
  399. return res.json({ status: false, message: err.message });
  400. }
  401. return res.json({ status: true });
  402. };
  403. actions.api.securityPassportSamlSetting = async(req, res) => {
  404. const form = req.form.settingForm;
  405. validateSamlSettingForm(req.form, req.t);
  406. if (!req.form.isValid) {
  407. return res.json({ status: false, message: req.form.errors.join('\n') });
  408. }
  409. debug('form content', form);
  410. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  411. // reset strategy
  412. await crowi.passportService.resetSamlStrategy();
  413. // setup strategy
  414. if (configManager.getConfig('crowi', 'security:passport-saml:isEnabled')) {
  415. try {
  416. await crowi.passportService.setupSamlStrategy(true);
  417. }
  418. catch (err) {
  419. // reset
  420. await crowi.passportService.resetSamlStrategy();
  421. return res.json({ status: false, message: err.message });
  422. }
  423. }
  424. return res.json({ status: true });
  425. };
  426. actions.api.securityPassportBasicSetting = async(req, res) => {
  427. const form = req.form.settingForm;
  428. if (!req.form.isValid) {
  429. return res.json({ status: false, message: req.form.errors.join('\n') });
  430. }
  431. debug('form content', form);
  432. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  433. // reset strategy
  434. await crowi.passportService.resetBasicStrategy();
  435. // setup strategy
  436. if (configManager.getConfig('crowi', 'security:passport-basic:isEnabled')) {
  437. try {
  438. await crowi.passportService.setupBasicStrategy(true);
  439. }
  440. catch (err) {
  441. // reset
  442. await crowi.passportService.resetBasicStrategy();
  443. return res.json({ status: false, message: err.message });
  444. }
  445. }
  446. return res.json({ status: true });
  447. };
  448. actions.api.securityPassportGoogleSetting = async(req, res) => {
  449. const form = req.form.settingForm;
  450. if (!req.form.isValid) {
  451. return res.json({ status: false, message: req.form.errors.join('\n') });
  452. }
  453. debug('form content', form);
  454. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  455. // reset strategy
  456. await crowi.passportService.resetGoogleStrategy();
  457. // setup strategy
  458. if (configManager.getConfig('crowi', 'security:passport-google:isEnabled')) {
  459. try {
  460. await crowi.passportService.setupGoogleStrategy(true);
  461. }
  462. catch (err) {
  463. // reset
  464. await crowi.passportService.resetGoogleStrategy();
  465. return res.json({ status: false, message: err.message });
  466. }
  467. }
  468. return res.json({ status: true });
  469. };
  470. actions.api.securityPassportGitHubSetting = async(req, res) => {
  471. const form = req.form.settingForm;
  472. if (!req.form.isValid) {
  473. return res.json({ status: false, message: req.form.errors.join('\n') });
  474. }
  475. debug('form content', form);
  476. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  477. // reset strategy
  478. await crowi.passportService.resetGitHubStrategy();
  479. // setup strategy
  480. if (configManager.getConfig('crowi', 'security:passport-github:isEnabled')) {
  481. try {
  482. await crowi.passportService.setupGitHubStrategy(true);
  483. }
  484. catch (err) {
  485. // reset
  486. await crowi.passportService.resetGitHubStrategy();
  487. return res.json({ status: false, message: err.message });
  488. }
  489. }
  490. return res.json({ status: true });
  491. };
  492. actions.api.securityPassportTwitterSetting = async(req, res) => {
  493. const form = req.form.settingForm;
  494. if (!req.form.isValid) {
  495. return res.json({ status: false, message: req.form.errors.join('\n') });
  496. }
  497. debug('form content', form);
  498. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  499. // reset strategy
  500. await crowi.passportService.resetTwitterStrategy();
  501. // setup strategy
  502. if (configManager.getConfig('crowi', 'security:passport-twitter:isEnabled')) {
  503. try {
  504. await crowi.passportService.setupTwitterStrategy(true);
  505. }
  506. catch (err) {
  507. // reset
  508. await crowi.passportService.resetTwitterStrategy();
  509. return res.json({ status: false, message: err.message });
  510. }
  511. }
  512. return res.json({ status: true });
  513. };
  514. actions.api.securityPassportOidcSetting = async(req, res) => {
  515. const form = req.form.settingForm;
  516. if (!req.form.isValid) {
  517. return res.json({ status: false, message: req.form.errors.join('\n') });
  518. }
  519. debug('form content', form);
  520. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  521. // reset strategy
  522. await crowi.passportService.resetOidcStrategy();
  523. // setup strategy
  524. if (configManager.getConfig('crowi', 'security:passport-oidc:isEnabled')) {
  525. try {
  526. await crowi.passportService.setupOidcStrategy(true);
  527. }
  528. catch (err) {
  529. // reset
  530. await crowi.passportService.resetOidcStrategy();
  531. return res.json({ status: false, message: err.message });
  532. }
  533. }
  534. return res.json({ status: true });
  535. };
  536. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  537. actions.api.usersSearch = function(req, res) {
  538. const User = crowi.model('User');
  539. const email = req.query.email;
  540. User.findUsersByPartOfEmail(email, {})
  541. .then((users) => {
  542. const result = {
  543. data: users,
  544. };
  545. return res.json(ApiResponse.success(result));
  546. })
  547. .catch((err) => {
  548. return res.json(ApiResponse.error());
  549. });
  550. };
  551. /**
  552. * save esa settings, update config cache, and response json
  553. *
  554. * @param {*} req
  555. * @param {*} res
  556. */
  557. actions.api.importerSettingEsa = async(req, res) => {
  558. const form = req.body;
  559. const { validationResult } = require('express-validator');
  560. const errors = validationResult(req);
  561. if (!errors.isEmpty()) {
  562. return res.json(ApiResponse.error('esa.io form is blank'));
  563. }
  564. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  565. importer.initializeEsaClient(); // let it run in the back aftert res
  566. return res.json(ApiResponse.success());
  567. };
  568. /**
  569. * save qiita settings, update config cache, and response json
  570. *
  571. * @param {*} req
  572. * @param {*} res
  573. */
  574. actions.api.importerSettingQiita = async(req, res) => {
  575. const form = req.body;
  576. const { validationResult } = require('express-validator');
  577. const errors = validationResult(req);
  578. if (!errors.isEmpty()) {
  579. return res.json(ApiResponse.error('Qiita form is blank'));
  580. }
  581. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  582. importer.initializeQiitaClient(); // let it run in the back aftert res
  583. return res.json(ApiResponse.success());
  584. };
  585. /**
  586. * Import all posts from esa
  587. *
  588. * @param {*} req
  589. * @param {*} res
  590. */
  591. actions.api.importDataFromEsa = async(req, res) => {
  592. const user = req.user;
  593. let errors;
  594. try {
  595. errors = await importer.importDataFromEsa(user);
  596. }
  597. catch (err) {
  598. errors = [err];
  599. }
  600. if (errors.length > 0) {
  601. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  602. }
  603. return res.json(ApiResponse.success());
  604. };
  605. /**
  606. * Import all posts from qiita
  607. *
  608. * @param {*} req
  609. * @param {*} res
  610. */
  611. actions.api.importDataFromQiita = async(req, res) => {
  612. const user = req.user;
  613. let errors;
  614. try {
  615. errors = await importer.importDataFromQiita(user);
  616. }
  617. catch (err) {
  618. errors = [err];
  619. }
  620. if (errors.length > 0) {
  621. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  622. }
  623. return res.json(ApiResponse.success());
  624. };
  625. /**
  626. * Test connection to esa and response result with json
  627. *
  628. * @param {*} req
  629. * @param {*} res
  630. */
  631. actions.api.testEsaAPI = async(req, res) => {
  632. try {
  633. await importer.testConnectionToEsa();
  634. return res.json(ApiResponse.success());
  635. }
  636. catch (err) {
  637. return res.json(ApiResponse.error(err));
  638. }
  639. };
  640. /**
  641. * Test connection to qiita and response result with json
  642. *
  643. * @param {*} req
  644. * @param {*} res
  645. */
  646. actions.api.testQiitaAPI = async(req, res) => {
  647. try {
  648. await importer.testConnectionToQiita();
  649. return res.json(ApiResponse.success());
  650. }
  651. catch (err) {
  652. return res.json(ApiResponse.error(err));
  653. }
  654. };
  655. /**
  656. * validate setting form values for SAML
  657. *
  658. * This validation checks, for the value of each mandatory items,
  659. * whether it from the environment variables is empty and form value to update it is empty.
  660. */
  661. function validateSamlSettingForm(form, t) {
  662. for (const key of crowi.passportService.mandatoryConfigKeysForSaml) {
  663. const formValue = form.settingForm[key];
  664. if (configManager.getConfigFromEnvVars('crowi', key) === null && formValue === '') {
  665. const formItemName = t(`security_setting.form_item_name.${key}`);
  666. form.errors.push(t('form_validation.required', formItemName));
  667. }
  668. }
  669. }
  670. return actions;
  671. };