notification-setting.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. import loggerFactory from '~/utils/logger';
  2. import { removeNullPropertyFromObject } from '~/utils/object-utils';
  3. import UpdatePost from '../../models/update-post';
  4. // eslint-disable-next-line no-unused-vars
  5. const logger = loggerFactory('growi:routes:apiv3:notification-setting');
  6. const express = require('express');
  7. const router = express.Router();
  8. const { body } = require('express-validator');
  9. const ErrorV3 = require('../../models/vo/error-apiv3');
  10. const validator = {
  11. userNotification: [
  12. body('pathPattern').isString().trim(),
  13. body('channel').isString().trim(),
  14. ],
  15. globalNotification: [
  16. body('triggerPath').isString().trim().not()
  17. .isEmpty(),
  18. body('notifyToType').isString().trim().isIn(['mail', 'slack']),
  19. body('toEmail').trim().custom((value, { req }) => {
  20. return (req.body.notifyToType === 'mail') ? (!!value && value.match(/.+@.+\..+/)) : true;
  21. }),
  22. body('slackChannels').trim().custom((value, { req }) => {
  23. return (req.body.notifyToType === 'slack') ? !!value : true;
  24. }),
  25. ],
  26. notifyForPageGrant: [
  27. body('isNotificationForOwnerPageEnabled').if(value => value != null).isBoolean(),
  28. body('isNotificationForGroupPageEnabled').if(value => value != null).isBoolean(),
  29. ],
  30. };
  31. /**
  32. * @swagger
  33. * tags:
  34. * name: NotificationSetting
  35. */
  36. /**
  37. * @swagger
  38. *
  39. * components:
  40. * schemas:
  41. * UserNotificationParams:
  42. * type: object
  43. * properties:
  44. * pathPattern:
  45. * type: string
  46. * description: path name of wiki
  47. * channel:
  48. * type: string
  49. * description: slack channel name without '#'
  50. * NotifyForPageGrant:
  51. * type: object
  52. * properties:
  53. * isNotificationForOwnerPageEnabled:
  54. * type: string
  55. * description: Whether to notify on owner page
  56. * isNotificationForGroupPageEnabled:
  57. * type: string
  58. * description: Whether to notify on group page
  59. * GlobalNotificationParams:
  60. * type: object
  61. * properties:
  62. * notifyToType:
  63. * type: string
  64. * description: What is type for notify
  65. * toEmail:
  66. * type: string
  67. * description: email for notify
  68. * slackChannels:
  69. * type: string
  70. * description: channels for notify
  71. * triggerPath:
  72. * type: string
  73. * description: trigger path for notify
  74. * triggerEvents:
  75. * type: array
  76. * items:
  77. * type: string
  78. * description: trigger events for notify
  79. */
  80. module.exports = (crowi) => {
  81. const loginRequiredStrictly = require('../../middlewares/login-required')(crowi);
  82. const adminRequired = require('../../middlewares/admin-required')(crowi);
  83. const csrf = require('../../middlewares/csrf')(crowi);
  84. const apiV3FormValidator = require('../../middlewares/apiv3-form-validator')(crowi);
  85. const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
  86. const GlobalNotificationMailSetting = crowi.models.GlobalNotificationMailSetting;
  87. const GlobalNotificationSlackSetting = crowi.models.GlobalNotificationSlackSetting;
  88. /**
  89. * @swagger
  90. *
  91. * /notification-setting/:
  92. * get:
  93. * tags: [NotificationSetting]
  94. * description: Get notification paramators
  95. * responses:
  96. * 200:
  97. * description: params of notification
  98. * content:
  99. * application/json:
  100. * schema:
  101. * properties:
  102. * notificationParams:
  103. * type: object
  104. * description: notification params
  105. */
  106. router.get('/', loginRequiredStrictly, adminRequired, async(req, res) => {
  107. const notificationParams = {
  108. userNotifications: await UpdatePost.findAll(),
  109. isNotificationForOwnerPageEnabled: await crowi.configManager.getConfig('notification', 'notification:owner-page:isEnabled'),
  110. isNotificationForGroupPageEnabled: await crowi.configManager.getConfig('notification', 'notification:group-page:isEnabled'),
  111. globalNotifications: await GlobalNotificationSetting.findAll(),
  112. };
  113. return res.apiv3({ notificationParams });
  114. });
  115. /**
  116. * @swagger
  117. *
  118. * /notification-setting/user-notification:
  119. * post:
  120. * tags: [NotificationSetting]
  121. * description: add user notification setting
  122. * requestBody:
  123. * required: true
  124. * content:
  125. * application/json:
  126. * schema:
  127. * $ref: '#/components/schemas/UserNotificationParams'
  128. * responses:
  129. * 200:
  130. * description: Succeeded to add user notification setting
  131. * content:
  132. * application/json:
  133. * schema:
  134. * properties:
  135. * createdUser:
  136. * type: object
  137. * description: user who set notification
  138. * userNotifications:
  139. * type: object
  140. * description: user trigger notifications for updated
  141. */
  142. router.post('/user-notification', loginRequiredStrictly, adminRequired, csrf, validator.userNotification, apiV3FormValidator, async(req, res) => {
  143. const { pathPattern, channel } = req.body;
  144. try {
  145. logger.info('notification.add', pathPattern, channel);
  146. const responseParams = {
  147. createdUser: await UpdatePost.createUpdatePost(pathPattern, channel, req.user),
  148. userNotifications: await UpdatePost.findAll(),
  149. };
  150. return res.apiv3({ responseParams }, 201);
  151. }
  152. catch (err) {
  153. const msg = 'Error occurred in updating user notification';
  154. logger.error('Error', err);
  155. return res.apiv3Err(new ErrorV3(msg, 'update-userNotification-failed'));
  156. }
  157. });
  158. /**
  159. * @swagger
  160. *
  161. * /notification-setting/user-notification/{id}:
  162. * delete:
  163. * tags: [NotificationSetting]
  164. * description: delete user trigger notification pattern
  165. * parameters:
  166. * - name: id
  167. * in: path
  168. * required: true
  169. * description: id of user trigger notification
  170. * schema:
  171. * type: string
  172. * responses:
  173. * 200:
  174. * description: Succeeded to delete user trigger notification pattern
  175. * content:
  176. * application/json:
  177. * schema:
  178. * properties:
  179. * deletedNotificaton:
  180. * type: object
  181. * description: deleted notification
  182. */
  183. router.delete('/user-notification/:id', loginRequiredStrictly, adminRequired, csrf, async(req, res) => {
  184. const { id } = req.params;
  185. try {
  186. const deletedNotificaton = await UpdatePost.findOneAndRemove({ _id: id });
  187. return res.apiv3(deletedNotificaton);
  188. }
  189. catch (err) {
  190. const msg = 'Error occurred in delete user trigger notification';
  191. logger.error('Error', err);
  192. return res.apiv3Err(new ErrorV3(msg, 'delete-userTriggerNotification-failed'));
  193. }
  194. });
  195. /**
  196. * @swagger
  197. *
  198. * /notification-setting/global-notification:
  199. * post:
  200. * tags: [NotificationSetting]
  201. * description: add global notification
  202. * requestBody:
  203. * required: true
  204. * content:
  205. * application/json:
  206. * schema:
  207. * $ref: '#/components/schemas/GlobalNotificationParams'
  208. * responses:
  209. * 200:
  210. * description: Succeeded to add global notification
  211. * content:
  212. * application/json:
  213. * schema:
  214. * properties:
  215. * createdNotification:
  216. * type: object
  217. * description: notification param created
  218. */
  219. router.post('/global-notification', loginRequiredStrictly, adminRequired, csrf, validator.globalNotification, apiV3FormValidator, async(req, res) => {
  220. const {
  221. notifyToType, toEmail, slackChannels, triggerPath, triggerEvents,
  222. } = req.body;
  223. let notification;
  224. if (notifyToType === GlobalNotificationSetting.TYPE.MAIL) {
  225. notification = new GlobalNotificationMailSetting(crowi);
  226. notification.toEmail = toEmail;
  227. }
  228. if (notifyToType === GlobalNotificationSetting.TYPE.SLACK) {
  229. notification = new GlobalNotificationSlackSetting(crowi);
  230. notification.slackChannels = slackChannels;
  231. }
  232. notification.triggerPath = triggerPath;
  233. notification.triggerEvents = triggerEvents || [];
  234. try {
  235. const createdNotification = await notification.save();
  236. return res.apiv3({ createdNotification }, 201);
  237. }
  238. catch (err) {
  239. const msg = 'Error occurred in updating global notification';
  240. logger.error('Error', err);
  241. return res.apiv3Err(new ErrorV3(msg, 'post-globalNotification-failed'));
  242. }
  243. });
  244. /**
  245. * @swagger
  246. *
  247. * /notification-setting/global-notification/{id}:
  248. * put:
  249. * tags: [NotificationSetting]
  250. * description: update global notification
  251. * parameters:
  252. * - name: id
  253. * in: path
  254. * required: true
  255. * description: global notification id for updated
  256. * schema:
  257. * type: string
  258. * requestBody:
  259. * required: true
  260. * content:
  261. * application/json:
  262. * schema:
  263. * $ref: '#/components/schemas/GlobalNotificationParams'
  264. * responses:
  265. * 200:
  266. * description: Succeeded to update global notification
  267. * content:
  268. * application/json:
  269. * schema:
  270. * properties:
  271. * createdNotification:
  272. * type: object
  273. * description: notification param updated
  274. */
  275. router.put('/global-notification/:id', loginRequiredStrictly, adminRequired, csrf, validator.globalNotification, apiV3FormValidator, async(req, res) => {
  276. const { id } = req.params;
  277. const {
  278. notifyToType, toEmail, slackChannels, triggerPath, triggerEvents,
  279. } = req.body;
  280. const models = {
  281. [GlobalNotificationSetting.TYPE.MAIL]: GlobalNotificationMailSetting,
  282. [GlobalNotificationSetting.TYPE.SLACK]: GlobalNotificationSlackSetting,
  283. };
  284. try {
  285. let setting = await GlobalNotificationSetting.findOne({ _id: id });
  286. setting = setting.toObject();
  287. // when switching from one type to another,
  288. // remove toEmail from slack setting and slackChannels from mail setting
  289. if (setting.__t !== notifyToType) {
  290. setting = models[setting.__t].hydrate(setting);
  291. setting.toEmail = undefined;
  292. setting.slackChannels = undefined;
  293. await setting.save();
  294. setting = setting.toObject();
  295. }
  296. if (notifyToType === GlobalNotificationSetting.TYPE.MAIL) {
  297. setting = GlobalNotificationMailSetting.hydrate(setting);
  298. setting.toEmail = toEmail;
  299. }
  300. if (notifyToType === GlobalNotificationSetting.TYPE.SLACK) {
  301. setting = GlobalNotificationSlackSetting.hydrate(setting);
  302. setting.slackChannels = slackChannels;
  303. }
  304. setting.__t = notifyToType;
  305. setting.triggerPath = triggerPath;
  306. setting.triggerEvents = triggerEvents || [];
  307. const createdNotification = await setting.save();
  308. return res.apiv3({ createdNotification });
  309. }
  310. catch (err) {
  311. const msg = 'Error occurred in updating global notification';
  312. logger.error('Error', err);
  313. return res.apiv3Err(new ErrorV3(msg, 'post-globalNotification-failed'));
  314. }
  315. });
  316. /**
  317. * @swagger
  318. *
  319. * /notification-setting/notify-for-page-grant:
  320. * put:
  321. * tags: [NotificationSetting]
  322. * description: Update settings for notify for page grant
  323. * requestBody:
  324. * required: true
  325. * content:
  326. * application/json:
  327. * schema:
  328. * $ref: '#/components/schemas/NotifyForPageGrant'
  329. * responses:
  330. * 200:
  331. * description: Succeeded to settings for notify for page grant
  332. * content:
  333. * application/json:
  334. * schema:
  335. * $ref: '#/components/schemas/NotifyForPageGrant'
  336. */
  337. router.put('/notify-for-page-grant', loginRequiredStrictly, adminRequired, csrf, validator.notifyForPageGrant, apiV3FormValidator, async(req, res) => {
  338. let requestParams = {
  339. 'notification:owner-page:isEnabled': req.body.isNotificationForOwnerPageEnabled,
  340. 'notification:group-page:isEnabled': req.body.isNotificationForGroupPageEnabled,
  341. };
  342. requestParams = removeNullPropertyFromObject(requestParams);
  343. try {
  344. await crowi.configManager.updateConfigsInTheSameNamespace('notification', requestParams);
  345. const responseParams = {
  346. isNotificationForOwnerPageEnabled: await crowi.configManager.getConfig('notification', 'notification:owner-page:isEnabled'),
  347. isNotificationForGroupPageEnabled: await crowi.configManager.getConfig('notification', 'notification:group-page:isEnabled'),
  348. };
  349. return res.apiv3({ responseParams });
  350. }
  351. catch (err) {
  352. const msg = 'Error occurred in updating notify for page grant';
  353. logger.error('Error', err);
  354. return res.apiv3Err(new ErrorV3(msg, 'update-notify-for-page-grant-failed'));
  355. }
  356. });
  357. /**
  358. * @swagger
  359. *
  360. * /notification-setting/global-notification/{id}/enabled:
  361. * put:
  362. * tags: [NotificationSetting]
  363. * description: toggle enabled global notification
  364. * parameters:
  365. * - name: id
  366. * in: path
  367. * required: true
  368. * description: notification id for updated
  369. * schema:
  370. * type: string
  371. * requestBody:
  372. * required: true
  373. * content:
  374. * application/json:
  375. * schema:
  376. * properties:
  377. * isEnabled:
  378. * type: boolean
  379. * description: is notification enabled
  380. * responses:
  381. * 200:
  382. * description: Succeeded to delete global notification pattern
  383. * content:
  384. * application/json:
  385. * schema:
  386. * properties:
  387. * deletedNotificaton:
  388. * type: object
  389. * description: notification id for updated
  390. */
  391. router.put('/global-notification/:id/enabled', loginRequiredStrictly, adminRequired, csrf, async(req, res) => {
  392. const { id } = req.params;
  393. const { isEnabled } = req.body;
  394. try {
  395. if (isEnabled) {
  396. await GlobalNotificationSetting.enable(id);
  397. }
  398. else {
  399. await GlobalNotificationSetting.disable(id);
  400. }
  401. return res.apiv3({ id });
  402. }
  403. catch (err) {
  404. const msg = 'Error occurred in toggle of global notification';
  405. logger.error('Error', err);
  406. return res.apiv3Err(new ErrorV3(msg, 'toggle-globalNotification-failed'));
  407. }
  408. });
  409. /**
  410. * @swagger
  411. *
  412. * /notification-setting/global-notification/{id}:
  413. * delete:
  414. * tags: [NotificationSetting]
  415. * description: delete global notification pattern
  416. * parameters:
  417. * - name: id
  418. * in: path
  419. * required: true
  420. * description: id of global notification
  421. * schema:
  422. * type: string
  423. * responses:
  424. * 200:
  425. * description: Succeeded to delete global notification pattern
  426. * content:
  427. * application/json:
  428. * schema:
  429. * properties:
  430. * deletedNotificaton:
  431. * type: object
  432. * description: deleted notification
  433. */
  434. router.delete('/global-notification/:id', loginRequiredStrictly, adminRequired, csrf, async(req, res) => {
  435. const { id } = req.params;
  436. try {
  437. const deletedNotificaton = await GlobalNotificationSetting.findOneAndRemove({ _id: id });
  438. return res.apiv3(deletedNotificaton);
  439. }
  440. catch (err) {
  441. const msg = 'Error occurred in delete global notification';
  442. logger.error('Error', err);
  443. return res.apiv3Err(new ErrorV3(msg, 'delete-globalNotification-failed'));
  444. }
  445. });
  446. return router;
  447. };