admin.js 45 KB

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