admin.js 43 KB

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