ManagedUsersHandler.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const { callbackify } = require('util')
  2. const { Subscription } = require('../../models/Subscription')
  3. const { GroupPolicy } = require('../../models/GroupPolicy')
  4. const ManagedUsersPolicy = require('./ManagedUsersPolicy')
  5. /**
  6. * This module contains functions for handling managed users in a
  7. * group subscription.
  8. */
  9. /**
  10. * Enables managed users for a given subscription by creating a new
  11. * group policy with default settings for managed users and updating
  12. * the subscription to use the new policy.
  13. * @async
  14. * @function
  15. * @param {string} subscriptionId - The ID of the subscription to enable
  16. * managed users for.
  17. * @returns {Promise<void>} - A Promise that resolves when the subscription
  18. * has been updated with the new group policy.
  19. */
  20. async function enableManagedUsers(subscriptionId) {
  21. const subscription = await Subscription.findById(subscriptionId).exec()
  22. // create a new Group policy with the default settings for managed users
  23. const policy = ManagedUsersPolicy.getDefaultPolicy()
  24. const groupPolicy = new GroupPolicy(policy)
  25. await groupPolicy.save()
  26. // update the subscription to use the new policy
  27. subscription.groupPolicy = groupPolicy._id
  28. await subscription.save()
  29. }
  30. /**
  31. * Retrieves the group policy for a user enrolled in a managed group.
  32. * @async
  33. * @function
  34. * @param {Object} user - The user object to retrieve the group policy for.
  35. * @returns {Promise<Object>} - A Promise that resolves with the group policy
  36. * object for the user's enrollment, or undefined if it does not exist.
  37. */
  38. async function getGroupPolicyForUser(user) {
  39. if (user.enrollment?.managedBy == null) {
  40. return
  41. }
  42. const subscription = await Subscription.findById(user.enrollment.managedBy)
  43. .populate('groupPolicy', '-_id')
  44. .exec()
  45. // return the group policy as a plain object without the _id and __v field
  46. const groupPolicy = subscription?.groupPolicy.toObject({
  47. versionKey: false,
  48. })
  49. return groupPolicy
  50. }
  51. module.exports = {
  52. promises: {
  53. enableManagedUsers,
  54. getGroupPolicyForUser,
  55. },
  56. enableManagedUsers: callbackify(enableManagedUsers),
  57. getGroupPolicyForUser: callbackify(getGroupPolicyForUser),
  58. }