admin.js 43 KB

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