admin.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  1. module.exports = function(crowi, app) {
  2. 'use strict';
  3. const debug = require('debug')('growi:routes:admin');
  4. const logger = require('@alias/logger')('growi:routes:admin');
  5. const fs = require('fs');
  6. const models = crowi.models;
  7. const Page = models.Page;
  8. const PageGroupRelation = models.PageGroupRelation;
  9. const User = models.User;
  10. const ExternalAccount = models.ExternalAccount;
  11. const UserGroup = models.UserGroup;
  12. const UserGroupRelation = models.UserGroupRelation;
  13. const Config = models.Config;
  14. const GlobalNotificationSetting = models.GlobalNotificationSetting;
  15. const GlobalNotificationMailSetting = models.GlobalNotificationMailSetting;
  16. const GlobalNotificationSlackSetting = models.GlobalNotificationSlackSetting; // eslint-disable-line no-unused-vars
  17. const recommendedXssWhiteList = require('@commons/service/xss/recommendedXssWhiteList');
  18. const PluginUtils = require('../plugins/plugin-utils');
  19. const ApiResponse = require('../util/apiResponse');
  20. const importer = require('../util/importer')(crowi);
  21. const searchEvent = crowi.event('search');
  22. const pluginUtils = new PluginUtils();
  23. const MAX_PAGE_LIST = 50;
  24. const actions = {};
  25. function createPager(total, limit, page, pagesCount, maxPageList) {
  26. const pager = {
  27. page: page,
  28. pagesCount: pagesCount,
  29. pages: [],
  30. total: 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. actions.index = function(req, res) {
  74. return res.render('admin/index', {
  75. plugins: pluginUtils.listPlugins(crowi.rootDir),
  76. });
  77. };
  78. // app.get('/admin/app' , admin.app.index);
  79. actions.app = {};
  80. actions.app.index = function(req, res) {
  81. var settingForm;
  82. settingForm = Config.setupConfigFormData('crowi', req.config);
  83. return res.render('admin/app', {
  84. settingForm: settingForm,
  85. });
  86. };
  87. actions.app.settingUpdate = function(req, res) {
  88. };
  89. // app.get('/admin/security' , admin.security.index);
  90. actions.security = {};
  91. actions.security.index = function(req, res) {
  92. const settingForm = Config.setupConfigFormData('crowi', req.config);
  93. const isAclEnabled = !Config.isPublicWikiOnly(req.config);
  94. return res.render('admin/security', { settingForm, isAclEnabled });
  95. };
  96. // app.get('/admin/markdown' , admin.markdown.index);
  97. actions.markdown = {};
  98. actions.markdown.index = function(req, res) {
  99. const config = crowi.getConfig();
  100. const markdownSetting = Config.setupConfigFormData('markdown', config);
  101. return res.render('admin/markdown', {
  102. markdownSetting: markdownSetting,
  103. recommendedXssWhiteList: recommendedXssWhiteList,
  104. });
  105. };
  106. // app.post('/admin/markdown/lineBreaksSetting' , admin.markdown.lineBreaksSetting);
  107. actions.markdown.lineBreaksSetting = function(req, res) {
  108. var markdownSetting = req.form.markdownSetting;
  109. req.session.markdownSetting = markdownSetting;
  110. if (req.form.isValid) {
  111. Config.updateNamespaceByArray('markdown', markdownSetting, function(err, config) {
  112. Config.updateConfigCache('markdown', config);
  113. req.session.markdownSetting = null;
  114. req.flash('successMessage', ['Successfully updated!']);
  115. return res.redirect('/admin/markdown');
  116. });
  117. }
  118. else {
  119. req.flash('errorMessage', req.form.errors);
  120. return res.redirect('/admin/markdown');
  121. }
  122. };
  123. // app.post('/admin/markdown/presentationSetting' , admin.markdown.presentationSetting);
  124. actions.markdown.presentationSetting = function(req, res) {
  125. let presentationSetting = req.form.markdownSetting;
  126. req.session.markdownSetting = presentationSetting;
  127. if (req.form.isValid) {
  128. Config.updateNamespaceByArray('markdown', presentationSetting, function(err, config) {
  129. Config.updateConfigCache('markdown', config);
  130. req.session.markdownSetting = null;
  131. req.flash('successMessage', ['Successfully updated!']);
  132. return res.redirect('/admin/markdown');
  133. });
  134. }
  135. else {
  136. req.flash('errorMessage', req.form.errors);
  137. return res.redirect('/admin/markdown');
  138. }
  139. };
  140. // app.post('/admin/markdown/xss-setting' , admin.markdown.xssSetting);
  141. actions.markdown.xssSetting = function(req, res) {
  142. let xssSetting = req.form.markdownSetting;
  143. xssSetting['markdown:xss:tagWhiteList'] = stringToArray(xssSetting['markdown:xss:tagWhiteList']);
  144. xssSetting['markdown:xss:attrWhiteList'] = stringToArray(xssSetting['markdown:xss:attrWhiteList']);
  145. req.session.markdownSetting = xssSetting;
  146. if (req.form.isValid) {
  147. Config.updateNamespaceByArray('markdown', xssSetting, function(err, config) {
  148. Config.updateConfigCache('markdown', config);
  149. req.session.xssSetting = null;
  150. req.flash('successMessage', ['Successfully updated!']);
  151. return res.redirect('/admin/markdown');
  152. });
  153. }
  154. else {
  155. req.flash('errorMessage', req.form.errors);
  156. return res.redirect('/admin/markdown');
  157. }
  158. };
  159. const stringToArray = (string) => {
  160. const array = string.split(',');
  161. return array.map(item => item.trim());
  162. };
  163. // app.get('/admin/customize' , admin.customize.index);
  164. actions.customize = {};
  165. actions.customize.index = function(req, res) {
  166. var settingForm;
  167. settingForm = Config.setupConfigFormData('crowi', req.config);
  168. const highlightJsCssSelectorOptions = {
  169. 'github': { name: '[Light] GitHub', border: false },
  170. 'github-gist': { name: '[Light] GitHub Gist', border: true },
  171. 'atom-one-light': { name: '[Light] Atom One Light', border: true },
  172. 'xcode': { name: '[Light] Xcode', border: true },
  173. 'vs': { name: '[Light] Vs', border: true },
  174. 'atom-one-dark': { name: '[Dark] Atom One Dark', border: false },
  175. 'hybrid': { name: '[Dark] Hybrid', border: false },
  176. 'monokai': { name: '[Dark] Monokai', border: false },
  177. 'tomorrow-night': { name: '[Dark] Tomorrow Night', border: false },
  178. 'vs2015': { name: '[Dark] Vs 2015', border: false },
  179. };
  180. return res.render('admin/customize', {
  181. settingForm: settingForm,
  182. highlightJsCssSelectorOptions: highlightJsCssSelectorOptions
  183. });
  184. };
  185. // app.get('/admin/notification' , admin.notification.index);
  186. actions.notification = {};
  187. actions.notification.index = async(req, res) => {
  188. const config = crowi.getConfig();
  189. const UpdatePost = crowi.model('UpdatePost');
  190. let slackSetting = Config.setupConfigFormData('notification', config);
  191. const hasSlackIwhUrl = Config.hasSlackIwhUrl(config);
  192. const hasSlackToken = Config.hasSlackToken(config);
  193. if (!Config.hasSlackIwhUrl(req.config)) {
  194. slackSetting['slack:incomingWebhookUrl'] = '';
  195. }
  196. if (req.session.slackSetting) {
  197. slackSetting = req.session.slackSetting;
  198. req.session.slackSetting = null;
  199. }
  200. const globalNotifications = await GlobalNotificationSetting.findAll();
  201. const userNotifications = await UpdatePost.findAll();
  202. return res.render('admin/notification', {
  203. userNotifications,
  204. slackSetting,
  205. hasSlackIwhUrl,
  206. hasSlackToken,
  207. globalNotifications,
  208. });
  209. };
  210. // app.post('/admin/notification/slackSetting' , admin.notification.slackauth);
  211. actions.notification.slackSetting = function(req, res) {
  212. var slackSetting = req.form.slackSetting;
  213. req.session.slackSetting = slackSetting;
  214. if (req.form.isValid) {
  215. Config.updateNamespaceByArray('notification', slackSetting, function(err, config) {
  216. Config.updateConfigCache('notification', config);
  217. req.flash('successMessage', ['Successfully Updated!']);
  218. req.session.slackSetting = null;
  219. // Re-setup
  220. crowi.setupSlack().then(function() {
  221. return res.redirect('/admin/notification');
  222. });
  223. });
  224. }
  225. else {
  226. req.flash('errorMessage', req.form.errors);
  227. return res.redirect('/admin/notification');
  228. }
  229. };
  230. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  231. actions.notification.slackAuth = function(req, res) {
  232. const code = req.query.code;
  233. const config = crowi.getConfig();
  234. if (!code || !Config.hasSlackConfig(req.config)) {
  235. return res.redirect('/admin/notification');
  236. }
  237. const slack = crowi.slack;
  238. slack.getOauthAccessToken(code)
  239. .then(data => {
  240. debug('oauth response', data);
  241. Config.updateNamespaceByArray('notification', {'slack:token': data.access_token}, function(err, config) {
  242. if (err) {
  243. req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
  244. }
  245. else {
  246. Config.updateConfigCache('notification', config);
  247. req.flash('successMessage', ['Successfully Connected!']);
  248. }
  249. return res.redirect('/admin/notification');
  250. });
  251. }).catch(err => {
  252. debug('oauth response ERROR', err);
  253. req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
  254. return res.redirect('/admin/notification');
  255. });
  256. };
  257. // app.post('/admin/notification/slackIwhSetting' , admin.notification.slackIwhSetting);
  258. actions.notification.slackIwhSetting = function(req, res) {
  259. var slackIwhSetting = req.form.slackIwhSetting;
  260. if (req.form.isValid) {
  261. Config.updateNamespaceByArray('notification', slackIwhSetting, function(err, config) {
  262. Config.updateConfigCache('notification', config);
  263. req.flash('successMessage', ['Successfully Updated!']);
  264. // Re-setup
  265. crowi.setupSlack().then(function() {
  266. return res.redirect('/admin/notification#slack-incoming-webhooks');
  267. });
  268. });
  269. }
  270. else {
  271. req.flash('errorMessage', req.form.errors);
  272. return res.redirect('/admin/notification#slack-incoming-webhooks');
  273. }
  274. };
  275. // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
  276. actions.notification.disconnectFromSlack = function(req, res) {
  277. const config = crowi.getConfig();
  278. const slack = crowi.slack;
  279. Config.updateNamespaceByArray('notification', {'slack:token': ''}, function(err, config) {
  280. Config.updateConfigCache('notification', config);
  281. req.flash('successMessage', ['Successfully Disconnected!']);
  282. return res.redirect('/admin/notification');
  283. });
  284. };
  285. actions.globalNotification = {};
  286. actions.globalNotification.detail = async(req, res) => {
  287. const notificationSettingId = req.params.id;
  288. let renderVars = {};
  289. if (notificationSettingId) {
  290. try {
  291. renderVars.setting = await GlobalNotificationSetting.findOne({_id: notificationSettingId});
  292. }
  293. catch (err) {
  294. logger.error(`Error in finding a global notification setting with {_id: ${notificationSettingId}}`);
  295. }
  296. }
  297. return res.render('admin/global-notification-detail', renderVars);
  298. };
  299. actions.globalNotification.create = (req, res) => {
  300. const form = req.form.notificationGlobal;
  301. let setting;
  302. switch (form.notifyToType) {
  303. case 'mail':
  304. setting = new GlobalNotificationMailSetting(crowi);
  305. setting.toEmail = form.toEmail;
  306. break;
  307. // case 'slack':
  308. // setting = new GlobalNotificationSlackSetting(crowi);
  309. // setting.slackChannels = form.slackChannels;
  310. // break;
  311. default:
  312. logger.error('GlobalNotificationSetting Type Error: undefined type');
  313. req.flash('errorMessage', 'Error occurred in creating a new global notification setting: undefined notification type');
  314. return res.redirect('/admin/notification#global-notification');
  315. }
  316. setting.triggerPath = form.triggerPath;
  317. setting.triggerEvents = getNotificationEvents(form);
  318. setting.save();
  319. return res.redirect('/admin/notification#global-notification');
  320. };
  321. actions.globalNotification.update = async(req, res) => {
  322. const form = req.form.notificationGlobal;
  323. const setting = await GlobalNotificationSetting.findOne({_id: form.id});
  324. switch (form.notifyToType) {
  325. case 'mail':
  326. setting.toEmail = form.toEmail;
  327. break;
  328. // case 'slack':
  329. // setting.slackChannels = form.slackChannels;
  330. // break;
  331. default:
  332. logger.error('GlobalNotificationSetting Type Error: undefined type');
  333. req.flash('errorMessage', 'Error occurred in updating the global notification setting: undefined notification type');
  334. return res.redirect('/admin/notification#global-notification');
  335. }
  336. setting.triggerPath = form.triggerPath;
  337. setting.triggerEvents = getNotificationEvents(form);
  338. setting.save();
  339. return res.redirect('/admin/notification#global-notification');
  340. };
  341. actions.globalNotification.remove = async(req, res) => {
  342. const id = req.params.id;
  343. try {
  344. await GlobalNotificationSetting.findOneAndRemove({_id: id});
  345. return res.redirect('/admin/notification#global-notification');
  346. }
  347. catch (err) {
  348. req.flash('errorMessage', 'Error in deleting global notification setting');
  349. return res.redirect('/admin/notification#global-notification');
  350. }
  351. };
  352. const getNotificationEvents = (form) => {
  353. let triggerEvents = [];
  354. const triggerEventKeys = Object.keys(form).filter(key => key.match(/^triggerEvent/));
  355. triggerEventKeys.forEach(key => {
  356. if (form[key]) {
  357. triggerEvents.push(form[key]);
  358. }
  359. });
  360. return triggerEvents;
  361. };
  362. actions.search = {}
  363. actions.search.index = function(req, res) {
  364. const search = crowi.getSearcher();
  365. if (!search) {
  366. return res.redirect('/admin');
  367. }
  368. return res.render('admin/search', {});
  369. };
  370. actions.user = {};
  371. actions.user.index = async function(req, res) {
  372. const activeUsers = await User.countListByStatus(User.STATUS_ACTIVE);
  373. const Config = crowi.model('Config');
  374. const userUpperLimit = Config.userUpperLimit(crowi);
  375. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  376. var page = parseInt(req.query.page) || 1;
  377. const result = await User.findUsersWithPagination({page: page});
  378. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  379. return res.render('admin/users', {
  380. users: result.docs,
  381. pager: pager,
  382. activeUsers: activeUsers,
  383. userUpperLimit: userUpperLimit,
  384. isUserCountExceedsUpperLimit: isUserCountExceedsUpperLimit
  385. });
  386. };
  387. actions.user.invite = function(req, res) {
  388. var form = req.form.inviteForm;
  389. var toSendEmail = form.sendEmail || false;
  390. if (req.form.isValid) {
  391. User.createUsersByInvitation(form.emailList.split('\n'), toSendEmail, function(err, userList) {
  392. if (err) {
  393. req.flash('errorMessage', req.form.errors.join('\n'));
  394. }
  395. else {
  396. req.flash('createdUser', userList);
  397. }
  398. return res.redirect('/admin/users');
  399. });
  400. }
  401. else {
  402. req.flash('errorMessage', req.form.errors.join('\n'));
  403. return res.redirect('/admin/users');
  404. }
  405. };
  406. actions.user.makeAdmin = function(req, res) {
  407. var id = req.params.id;
  408. User.findById(id, function(err, userData) {
  409. userData.makeAdmin(function(err, userData) {
  410. if (err === null) {
  411. req.flash('successMessage', userData.name + 'さんのアカウントを管理者に設定しました。');
  412. }
  413. else {
  414. req.flash('errorMessage', '更新に失敗しました。');
  415. debug(err, userData);
  416. }
  417. return res.redirect('/admin/users');
  418. });
  419. });
  420. };
  421. actions.user.removeFromAdmin = function(req, res) {
  422. var id = req.params.id;
  423. User.findById(id, function(err, userData) {
  424. userData.removeFromAdmin(function(err, userData) {
  425. if (err === null) {
  426. req.flash('successMessage', userData.name + 'さんのアカウントを管理者から外しました。');
  427. }
  428. else {
  429. req.flash('errorMessage', '更新に失敗しました。');
  430. debug(err, userData);
  431. }
  432. return res.redirect('/admin/users');
  433. });
  434. });
  435. };
  436. actions.user.activate = async function(req, res) {
  437. // check user upper limit
  438. const isUserCountExceedsUpperLimit = await User.isUserCountExceedsUpperLimit();
  439. if (isUserCountExceedsUpperLimit) {
  440. req.flash('errorMessage', 'ユーザーが上限に達したため有効化できません。');
  441. return res.redirect('/admin/users');
  442. }
  443. var id = req.params.id;
  444. User.findById(id, function(err, userData) {
  445. userData.statusActivate(function(err, userData) {
  446. if (err === null) {
  447. req.flash('successMessage', userData.name + 'さんのアカウントを有効化しました');
  448. }
  449. else {
  450. req.flash('errorMessage', '更新に失敗しました。');
  451. debug(err, userData);
  452. }
  453. return res.redirect('/admin/users');
  454. });
  455. });
  456. };
  457. actions.user.suspend = function(req, res) {
  458. var id = req.params.id;
  459. User.findById(id, function(err, userData) {
  460. userData.statusSuspend(function(err, userData) {
  461. if (err === null) {
  462. req.flash('successMessage', userData.name + 'さんのアカウントを利用停止にしました');
  463. }
  464. else {
  465. req.flash('errorMessage', '更新に失敗しました。');
  466. debug(err, userData);
  467. }
  468. return res.redirect('/admin/users');
  469. });
  470. });
  471. };
  472. actions.user.remove = function(req, res) {
  473. const id = req.params.id;
  474. let username = '';
  475. return new Promise((resolve, reject) => {
  476. User.findById(id, (err, userData) => {
  477. username = userData.username;
  478. return resolve(userData);
  479. });
  480. })
  481. .then((userData) => {
  482. return new Promise((resolve, reject) => {
  483. userData.statusDelete((err, userData) => {
  484. if (err) {
  485. reject(err);
  486. }
  487. resolve(userData);
  488. });
  489. });
  490. })
  491. .then((userData) => {
  492. // remove all External Accounts
  493. return ExternalAccount.remove({user: userData}).then(() => userData);
  494. })
  495. .then((userData) => {
  496. return Page.removeByPath(`/user/${username}`).then(() => userData);
  497. })
  498. .then((userData) => {
  499. req.flash('successMessage', `${username} さんのアカウントを削除しました`);
  500. return res.redirect('/admin/users');
  501. })
  502. .catch((err) => {
  503. req.flash('errorMessage', '削除に失敗しました。');
  504. return res.redirect('/admin/users');
  505. });
  506. };
  507. // これやったときの relation の挙動未確認
  508. actions.user.removeCompletely = function(req, res) {
  509. // ユーザーの物理削除
  510. var id = req.params.id;
  511. User.removeCompletelyById(id, function(err, removed) {
  512. if (err) {
  513. debug('Error while removing user.', err, id);
  514. req.flash('errorMessage', '完全な削除に失敗しました。');
  515. }
  516. else {
  517. req.flash('successMessage', '削除しました');
  518. }
  519. return res.redirect('/admin/users');
  520. });
  521. };
  522. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  523. actions.user.resetPassword = function(req, res) {
  524. const id = req.body.user_id;
  525. const User = crowi.model('User');
  526. User.resetPasswordByRandomString(id)
  527. .then(function(data) {
  528. data.user = User.filterToPublicFields(data.user);
  529. return res.json(ApiResponse.success(data));
  530. }).catch(function(err) {
  531. debug('Error on reseting password', err);
  532. return res.json(ApiResponse.error('Error'));
  533. });
  534. };
  535. actions.externalAccount = {};
  536. actions.externalAccount.index = function(req, res) {
  537. const page = parseInt(req.query.page) || 1;
  538. ExternalAccount.findAllWithPagination({page})
  539. .then((result) => {
  540. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  541. return res.render('admin/external-accounts', {
  542. accounts: result.docs,
  543. pager: pager
  544. });
  545. });
  546. };
  547. actions.externalAccount.remove = async function(req, res) {
  548. const id = req.params.id;
  549. let account = null;
  550. try {
  551. account = await ExternalAccount.findByIdAndRemove(id);
  552. if (account == null) {
  553. throw new Error('削除に失敗しました。');
  554. }
  555. }
  556. catch (err) {
  557. req.flash('errorMessage', err.message);
  558. return res.redirect('/admin/users/external-accounts');
  559. }
  560. req.flash('successMessage', `外部アカウント '${account.providerType}/${account.accountId}' を削除しました`);
  561. return res.redirect('/admin/users/external-accounts');
  562. };
  563. actions.userGroup = {};
  564. actions.userGroup.index = function(req, res) {
  565. var page = parseInt(req.query.page) || 1;
  566. const isAclEnabled = !Config.isPublicWikiOnly(req.config);
  567. var renderVar = {
  568. userGroups: [],
  569. userGroupRelations: new Map(),
  570. pager: null,
  571. isAclEnabled,
  572. };
  573. UserGroup.findUserGroupsWithPagination({ page: page })
  574. .then((result) => {
  575. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  576. var userGroups = result.docs;
  577. renderVar.userGroups = userGroups;
  578. renderVar.pager = pager;
  579. return userGroups.map((userGroup) => {
  580. return new Promise((resolve, reject) => {
  581. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  582. .then((relations) => {
  583. return resolve([userGroup, relations]);
  584. });
  585. });
  586. });
  587. })
  588. .then((allRelationsPromise) => {
  589. return Promise.all(allRelationsPromise);
  590. })
  591. .then((relations) => {
  592. renderVar.userGroupRelations = new Map(relations);
  593. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  594. return res.render('admin/user-groups', renderVar);
  595. })
  596. .catch( function(err) {
  597. debug('Error on find all relations', err);
  598. return res.json(ApiResponse.error('Error'));
  599. });
  600. };
  601. // グループ詳細
  602. actions.userGroup.detail = async function(req, res) {
  603. const userGroupId = req.params.id;
  604. const renderVar = {
  605. userGroup: null,
  606. userGroupRelations: [],
  607. notRelatedusers: [],
  608. relatedPages: [],
  609. };
  610. const userGroup = await UserGroup.findOne({ _id: userGroupId});
  611. if (userGroup == null) {
  612. logger.error('no userGroup is exists. ', userGroupId);
  613. req.flash('errorMessage', 'グループがありません');
  614. return res.redirect('/admin/user-groups');
  615. }
  616. renderVar.userGroup = userGroup;
  617. const resolves = await Promise.all([
  618. // get all user and group relations
  619. UserGroupRelation.findAllRelationForUserGroup(userGroup),
  620. // get all not related users for group
  621. UserGroupRelation.findUserByNotRelatedGroup(userGroup),
  622. // get all related pages
  623. Page.find({grant: Page.GRANT_USER_GROUP, grantedGroup: { $in: [userGroup] }}),
  624. ]);
  625. renderVar.userGroupRelations = resolves[0];
  626. renderVar.notRelatedusers = resolves[1];
  627. renderVar.relatedPages = resolves[2];
  628. return res.render('admin/user-group-detail', renderVar);
  629. };
  630. //グループの生成
  631. actions.userGroup.create = function(req, res) {
  632. const form = req.form.createGroupForm;
  633. if (req.form.isValid) {
  634. const userGroupName = crowi.xss.process(form.userGroupName);
  635. UserGroup.createGroupByName(userGroupName)
  636. .then((newUserGroup) => {
  637. req.flash('successMessage', newUserGroup.name);
  638. req.flash('createdUserGroup', newUserGroup);
  639. return res.redirect('/admin/user-groups');
  640. })
  641. .catch((err) => {
  642. debug('create userGroup error:', err);
  643. req.flash('errorMessage', '同じグループ名が既に存在します。');
  644. });
  645. }
  646. else {
  647. req.flash('errorMessage', req.form.errors.join('\n'));
  648. return res.redirect('/admin/user-groups');
  649. }
  650. };
  651. //
  652. actions.userGroup.update = function(req, res) {
  653. const userGroupId = req.params.userGroupId;
  654. const name = crowi.xss.process(req.body.name);
  655. UserGroup.findById(userGroupId)
  656. .then((userGroupData) => {
  657. if (userGroupData == null) {
  658. req.flash('errorMessage', 'グループの検索に失敗しました。');
  659. return new Promise();
  660. }
  661. else {
  662. // 名前存在チェック
  663. return UserGroup.isRegisterableName(name)
  664. .then((isRegisterableName) => {
  665. // 既に存在するグループ名に更新しようとした場合はエラー
  666. if (!isRegisterableName) {
  667. req.flash('errorMessage', 'グループ名が既に存在します。');
  668. }
  669. else {
  670. return userGroupData.updateName(name)
  671. .then(() => {
  672. req.flash('successMessage', 'グループ名を更新しました。');
  673. })
  674. .catch((err) => {
  675. req.flash('errorMessage', 'グループ名の更新に失敗しました。');
  676. });
  677. }
  678. });
  679. }
  680. })
  681. .then(() => {
  682. return res.redirect('/admin/user-group-detail/' + userGroupId);
  683. });
  684. };
  685. // app.post('/_api/admin/user-group/delete' , admin.userGroup.removeCompletely);
  686. actions.userGroup.removeCompletely = function(req, res) {
  687. const id = req.body.user_group_id;
  688. UserGroup.removeCompletelyById(id)
  689. .then(() => {
  690. req.flash('successMessage', '削除しました');
  691. return res.redirect('/admin/user-groups');
  692. })
  693. .catch((err) => {
  694. debug('Error while removing userGroup.', err, id);
  695. req.flash('errorMessage', '完全な削除に失敗しました。');
  696. return res.redirect('/admin/user-groups');
  697. });
  698. };
  699. actions.userGroupRelation = {};
  700. actions.userGroupRelation.index = function(req, res) {
  701. };
  702. actions.userGroupRelation.create = function(req, res) {
  703. const User = crowi.model('User');
  704. const UserGroup = crowi.model('UserGroup');
  705. const UserGroupRelation = crowi.model('UserGroupRelation');
  706. // req params
  707. const userName = req.body.user_name;
  708. const userGroupId = req.body.user_group_id;
  709. let user = null;
  710. let userGroup = null;
  711. Promise.all([
  712. // ユーザグループをIDで検索
  713. UserGroup.findById(userGroupId),
  714. // ユーザを名前で検索
  715. User.findUserByUsername(userName),
  716. ])
  717. .then((resolves) => {
  718. userGroup = resolves[0];
  719. user = resolves[1];
  720. // Relation を作成
  721. UserGroupRelation.createRelation(userGroup, user);
  722. })
  723. .then((result) => {
  724. return res.redirect('/admin/user-group-detail/' + userGroup.id);
  725. }).catch((err) => {
  726. debug('Error on create user-group relation', err);
  727. req.flash('errorMessage', 'Error on create user-group relation');
  728. return res.redirect('/admin/user-group-detail/' + userGroup.id);
  729. });
  730. };
  731. actions.userGroupRelation.remove = function(req, res) {
  732. const UserGroupRelation = crowi.model('UserGroupRelation');
  733. const userGroupId = req.params.id;
  734. const relationId = req.params.relationId;
  735. UserGroupRelation.removeById(relationId)
  736. .then(() =>{
  737. return res.redirect('/admin/user-group-detail/' + userGroupId);
  738. })
  739. .catch((err) => {
  740. debug('Error on remove user-group-relation', err);
  741. req.flash('errorMessage', 'グループのユーザ削除に失敗しました。');
  742. });
  743. };
  744. // Importer management
  745. actions.importer = {};
  746. actions.importer.index = function(req, res) {
  747. var settingForm;
  748. settingForm = Config.setupConfigFormData('crowi', req.config);
  749. return res.render('admin/importer', {
  750. settingForm: settingForm,
  751. });
  752. };
  753. actions.api = {};
  754. actions.api.appSetting = function(req, res) {
  755. var form = req.form.settingForm;
  756. if (req.form.isValid) {
  757. debug('form content', form);
  758. // mail setting ならここで validation
  759. if (form['mail:from']) {
  760. validateMailSetting(req, form, function(err, data) {
  761. debug('Error validate mail setting: ', err, data);
  762. if (err) {
  763. req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。');
  764. return res.json({status: false, message: req.form.errors.join('\n')});
  765. }
  766. return saveSetting(req, res, form);
  767. });
  768. }
  769. else {
  770. return saveSetting(req, res, form);
  771. }
  772. }
  773. else {
  774. return res.json({status: false, message: req.form.errors.join('\n')});
  775. }
  776. };
  777. actions.api.asyncAppSetting = async(req, res) => {
  778. const form = req.form.settingForm;
  779. if (!req.form.isValid) {
  780. return res.json({status: false, message: req.form.errors.join('\n')});
  781. }
  782. debug('form content', form);
  783. try {
  784. await crowi.configManager.updateConfigsInTheSameNamespace('crowi', form);
  785. return res.json({status: true});
  786. }
  787. catch (err) {
  788. logger.error(err);
  789. return res.json({status: false});
  790. }
  791. };
  792. actions.api.securitySetting = function(req, res) {
  793. const form = req.form.settingForm;
  794. const config = crowi.getConfig();
  795. const isPublicWikiOnly = Config.isPublicWikiOnly(config);
  796. if (isPublicWikiOnly) {
  797. const basicName = form['security:basicName'];
  798. const basicSecret = form['security:basicSecret'];
  799. if (basicName != '' || basicSecret != '') {
  800. req.form.errors.push('Public Wikiのため、Basic認証は利用できません。');
  801. return res.json({status: false, message: req.form.errors.join('\n')});
  802. }
  803. const guestMode = form['security:restrictGuestMode'];
  804. if ( guestMode == 'Deny' ) {
  805. req.form.errors.push('Private Wikiへの設定変更はできません。');
  806. return res.json({status: false, message: req.form.errors.join('\n')});
  807. }
  808. }
  809. if (req.form.isValid) {
  810. debug('form content', form);
  811. return saveSetting(req, res, form);
  812. }
  813. else {
  814. return res.json({status: false, message: req.form.errors.join('\n')});
  815. }
  816. };
  817. actions.api.securityPassportLdapSetting = function(req, res) {
  818. var form = req.form.settingForm;
  819. if (!req.form.isValid) {
  820. return res.json({status: false, message: req.form.errors.join('\n')});
  821. }
  822. debug('form content', form);
  823. return saveSettingAsync(form)
  824. .then(() => {
  825. const config = crowi.getConfig();
  826. // reset strategy
  827. crowi.passportService.resetLdapStrategy();
  828. // setup strategy
  829. if (Config.isEnabledPassportLdap(config)) {
  830. crowi.passportService.setupLdapStrategy(true);
  831. }
  832. return;
  833. })
  834. .then(() => {
  835. res.json({status: true});
  836. });
  837. };
  838. actions.api.securityPassportSamlSetting = async(req, res) => {
  839. const form = req.form.settingForm;
  840. validateSamlSettingForm(req.form, req.t);
  841. if (!req.form.isValid) {
  842. return res.json({status: false, message: req.form.errors.join('\n')});
  843. }
  844. debug('form content', form);
  845. await crowi.configManager.updateConfigsInTheSameNamespace('crowi', form);
  846. // reset strategy
  847. await crowi.passportService.resetSamlStrategy();
  848. // setup strategy
  849. if (crowi.configManager.getConfig('crowi', 'security:passport-saml:isEnabled')) {
  850. try {
  851. await crowi.passportService.setupSamlStrategy(true);
  852. }
  853. catch (err) {
  854. // reset
  855. await crowi.passportService.resetSamlStrategy();
  856. return res.json({status: false, message: err.message});
  857. }
  858. }
  859. return res.json({status: true});
  860. };
  861. actions.api.securityPassportGoogleSetting = async(req, res) => {
  862. const form = req.form.settingForm;
  863. if (!req.form.isValid) {
  864. return res.json({status: false, message: req.form.errors.join('\n')});
  865. }
  866. debug('form content', form);
  867. await saveSettingAsync(form);
  868. const config = await crowi.getConfig();
  869. // reset strategy
  870. await crowi.passportService.resetGoogleStrategy();
  871. // setup strategy
  872. if (Config.isEnabledPassportGoogle(config)) {
  873. try {
  874. await crowi.passportService.setupGoogleStrategy(true);
  875. }
  876. catch (err) {
  877. // reset
  878. await crowi.passportService.resetGoogleStrategy();
  879. return res.json({status: false, message: err.message});
  880. }
  881. }
  882. return res.json({status: true});
  883. };
  884. actions.api.securityPassportGitHubSetting = async(req, res) => {
  885. const form = req.form.settingForm;
  886. if (!req.form.isValid) {
  887. return res.json({status: false, message: req.form.errors.join('\n')});
  888. }
  889. debug('form content', form);
  890. await saveSettingAsync(form);
  891. const config = await crowi.getConfig();
  892. // reset strategy
  893. await crowi.passportService.resetGitHubStrategy();
  894. // setup strategy
  895. if (Config.isEnabledPassportGitHub(config)) {
  896. try {
  897. await crowi.passportService.setupGitHubStrategy(true);
  898. }
  899. catch (err) {
  900. // reset
  901. await crowi.passportService.resetGitHubStrategy();
  902. return res.json({status: false, message: err.message});
  903. }
  904. }
  905. return res.json({status: true});
  906. };
  907. actions.api.securityPassportTwitterSetting = async(req, res) => {
  908. const form = req.form.settingForm;
  909. if (!req.form.isValid) {
  910. return res.json({status: false, message: req.form.errors.join('\n')});
  911. }
  912. debug('form content', form);
  913. await saveSettingAsync(form);
  914. const config = await crowi.getConfig();
  915. // reset strategy
  916. await crowi.passportService.resetTwitterStrategy();
  917. // setup strategy
  918. if (Config.isEnabledPassportTwitter(config)) {
  919. try {
  920. await crowi.passportService.setupTwitterStrategy(true);
  921. }
  922. catch (err) {
  923. // reset
  924. await crowi.passportService.resetTwitterStrategy();
  925. return res.json({status: false, message: err.message});
  926. }
  927. }
  928. return res.json({status: true});
  929. };
  930. actions.api.customizeSetting = function(req, res) {
  931. const form = req.form.settingForm;
  932. if (req.form.isValid) {
  933. debug('form content', form);
  934. return saveSetting(req, res, form);
  935. }
  936. else {
  937. return res.json({status: false, message: req.form.errors.join('\n')});
  938. }
  939. };
  940. actions.api.customizeSetting = function(req, res) {
  941. const form = req.form.settingForm;
  942. if (req.form.isValid) {
  943. debug('form content', form);
  944. return saveSetting(req, res, form);
  945. }
  946. else {
  947. return res.json({status: false, message: req.form.errors.join('\n')});
  948. }
  949. };
  950. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  951. actions.api.notificationAdd = function(req, res) {
  952. var UpdatePost = crowi.model('UpdatePost');
  953. var pathPattern = req.body.pathPattern;
  954. var channel = req.body.channel;
  955. debug('notification.add', pathPattern, channel);
  956. UpdatePost.create(pathPattern, channel, req.user)
  957. .then(function(doc) {
  958. debug('Successfully save updatePost', doc);
  959. // fixme: うーん
  960. doc.creator = doc.creator._id.toString();
  961. return res.json(ApiResponse.success({updatePost: doc}));
  962. }).catch(function(err) {
  963. debug('Failed to save updatePost', err);
  964. return res.json(ApiResponse.error());
  965. });
  966. };
  967. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  968. actions.api.notificationRemove = function(req, res) {
  969. var UpdatePost = crowi.model('UpdatePost');
  970. var id = req.body.id;
  971. UpdatePost.remove(id)
  972. .then(function() {
  973. debug('Successfully remove updatePost');
  974. return res.json(ApiResponse.success({}));
  975. }).catch(function(err) {
  976. debug('Failed to remove updatePost', err);
  977. return res.json(ApiResponse.error());
  978. });
  979. };
  980. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  981. actions.api.usersSearch = function(req, res) {
  982. const User = crowi.model('User');
  983. const email =req.query.email;
  984. User.findUsersByPartOfEmail(email, {})
  985. .then(users => {
  986. const result = {
  987. data: users
  988. };
  989. return res.json(ApiResponse.success(result));
  990. }).catch(err => {
  991. return res.json(ApiResponse.error());
  992. });
  993. };
  994. actions.api.toggleIsEnabledForGlobalNotification = async(req, res) => {
  995. const id = req.query.id;
  996. const isEnabled = (req.query.isEnabled == 'true');
  997. try {
  998. if (isEnabled) {
  999. await GlobalNotificationSetting.enable(id);
  1000. }
  1001. else {
  1002. await GlobalNotificationSetting.disable(id);
  1003. }
  1004. return res.json(ApiResponse.success());
  1005. }
  1006. catch (err) {
  1007. return res.json(ApiResponse.error());
  1008. }
  1009. };
  1010. /**
  1011. * save esa settings, update config cache, and response json
  1012. *
  1013. * @param {*} req
  1014. * @param {*} res
  1015. */
  1016. actions.api.importerSettingEsa = async(req, res) => {
  1017. const form = req.form.settingForm;
  1018. if (!req.form.isValid) {
  1019. return res.json({status: false, message: req.form.errors.join('\n')});
  1020. }
  1021. await saveSetting(req, res, form);
  1022. await importer.initializeEsaClient();
  1023. };
  1024. /**
  1025. * save qiita settings, update config cache, and response json
  1026. *
  1027. * @param {*} req
  1028. * @param {*} res
  1029. */
  1030. actions.api.importerSettingQiita = async(req, res) => {
  1031. const form = req.form.settingForm;
  1032. if (!req.form.isValid) {
  1033. return res.json({status: false, message: req.form.errors.join('\n')});
  1034. }
  1035. await saveSetting(req, res, form);
  1036. await importer.initializeQiitaClient();
  1037. };
  1038. /**
  1039. * Import all posts from esa
  1040. *
  1041. * @param {*} req
  1042. * @param {*} res
  1043. */
  1044. actions.api.importDataFromEsa = async(req, res) => {
  1045. const user = req.user;
  1046. let errors;
  1047. try {
  1048. errors = await importer.importDataFromEsa(user);
  1049. }
  1050. catch (err) {
  1051. errors = [err];
  1052. }
  1053. if (errors.length > 0) {
  1054. return res.json({ status: false, message: `<br> - ${errors.join('<br> - ')}` });
  1055. }
  1056. return res.json({ status: true });
  1057. };
  1058. /**
  1059. * Import all posts from qiita
  1060. *
  1061. * @param {*} req
  1062. * @param {*} res
  1063. */
  1064. actions.api.importDataFromQiita = async(req, res) => {
  1065. const user = req.user;
  1066. let errors;
  1067. try {
  1068. errors = await importer.importDataFromQiita(user);
  1069. }
  1070. catch (err) {
  1071. errors = [err];
  1072. }
  1073. if (errors.length > 0) {
  1074. return res.json({ status: false, message: `<br> - ${errors.join('<br> - ')}` });
  1075. }
  1076. return res.json({ status: true });
  1077. };
  1078. /**
  1079. * Test connection to esa and response result with json
  1080. *
  1081. * @param {*} req
  1082. * @param {*} res
  1083. */
  1084. actions.api.testEsaAPI = async(req, res) => {
  1085. try {
  1086. await importer.testConnectionToEsa();
  1087. return res.json({ status: true });
  1088. }
  1089. catch (err) {
  1090. return res.json({ status: false, message: `${err}` });
  1091. }
  1092. };
  1093. /**
  1094. * Test connection to qiita and response result with json
  1095. *
  1096. * @param {*} req
  1097. * @param {*} res
  1098. */
  1099. actions.api.testQiitaAPI = async(req, res) => {
  1100. try {
  1101. await importer.testConnectionToQiita();
  1102. return res.json({ status: true });
  1103. }
  1104. catch (err) {
  1105. return res.json({ status: false, message: `${err}` });
  1106. }
  1107. };
  1108. actions.api.searchBuildIndex = async function(req, res) {
  1109. const search = crowi.getSearcher();
  1110. if (!search) {
  1111. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  1112. }
  1113. // first, delete index
  1114. try {
  1115. await search.deleteIndex();
  1116. }
  1117. catch (err) {
  1118. logger.warn('Delete index Error, but if it is initialize, its ok.', err);
  1119. }
  1120. // second, create index
  1121. try {
  1122. await search.buildIndex();
  1123. }
  1124. catch (err) {
  1125. logger.error('Error', err);
  1126. return res.json(ApiResponse.error(err));
  1127. }
  1128. searchEvent.on('addPageProgress', (total, current, skip) => {
  1129. crowi.getIo().sockets.emit('admin:addPageProgress', { total, current, skip });
  1130. });
  1131. searchEvent.on('finishAddPage', (total, current, skip) => {
  1132. crowi.getIo().sockets.emit('admin:finishAddPage', { total, current, skip });
  1133. });
  1134. // add all page
  1135. search
  1136. .addAllPages()
  1137. .then(() => {
  1138. debug('Data is successfully indexed. ------------------ ✧✧');
  1139. })
  1140. .catch(err => {
  1141. logger.error('Error', err);
  1142. });
  1143. return res.json(ApiResponse.success());
  1144. };
  1145. /**
  1146. * save settings, update config cache, and response json
  1147. *
  1148. * @param {any} req
  1149. * @param {any} res
  1150. * @param {any} form
  1151. */
  1152. function saveSetting(req, res, form) {
  1153. Config.updateNamespaceByArray('crowi', form, function(err, config) {
  1154. Config.updateConfigCache('crowi', config);
  1155. return res.json({status: true});
  1156. });
  1157. }
  1158. /**
  1159. * save settings, update config cache ONLY. (this method don't response json)
  1160. *
  1161. * @param {any} form
  1162. * @returns
  1163. */
  1164. function saveSettingAsync(form) {
  1165. return new Promise((resolve, reject) => {
  1166. Config.updateNamespaceByArray('crowi', form, (err, config) => {
  1167. if (err) {
  1168. return reject(err);
  1169. }
  1170. Config.updateConfigCache('crowi', config);
  1171. return resolve();
  1172. });
  1173. });
  1174. }
  1175. function validateMailSetting(req, form, callback) {
  1176. const mailer = crowi.mailer;
  1177. const option = {
  1178. host: form['mail:smtpHost'],
  1179. port: form['mail:smtpPort'],
  1180. };
  1181. if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
  1182. option.auth = {
  1183. user: form['mail:smtpUser'],
  1184. pass: form['mail:smtpPassword'],
  1185. };
  1186. }
  1187. if (option.port === 465) {
  1188. option.secure = true;
  1189. }
  1190. const smtpClient = mailer.createSMTPClient(option);
  1191. debug('mailer setup for validate SMTP setting', smtpClient);
  1192. smtpClient.sendMail({
  1193. from: form['mail:from'],
  1194. to: req.user.email,
  1195. subject: 'Wiki管理設定のアップデートによるメール通知',
  1196. text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。'
  1197. }, callback);
  1198. }
  1199. /**
  1200. * validate setting form values for SAML
  1201. *
  1202. * This validation checks, for the value of each mandatory items,
  1203. * whether it from the environment variables is empty and form value to update it is empty.
  1204. */
  1205. function validateSamlSettingForm(form, t) {
  1206. for (const key of crowi.passportService.mandatoryConfigKeysForSaml) {
  1207. const formValue = form.settingForm[key];
  1208. if (crowi.configManager.getConfigFromEnvVars('crowi', key) === null && formValue === '') {
  1209. const formItemName = t(`security_setting.form_item_name.${key}`);
  1210. form.errors.push(t('form_validation.required', formItemName));
  1211. }
  1212. }
  1213. }
  1214. return actions;
  1215. };