admin.js 45 KB

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