admin.js 43 KB

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