UserMembershipHandler.test.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. import { vi, expect } from 'vitest'
  2. import mongodb from 'mongodb-legacy'
  3. import EntityConfigs from '../../../../app/src/Features/UserMembership/UserMembershipEntityConfigs.mjs'
  4. import UserMembershipErrors from '../../../../app/src/Features/UserMembership/UserMembershipErrors.mjs'
  5. const { ObjectId } = mongodb
  6. const modulePath =
  7. '../../../../app/src/Features/UserMembership/UserMembershipHandler'
  8. const serializeIds = ids =>
  9. ids.map(id => (id instanceof ObjectId ? `objectId-${id.toString()}` : id))
  10. vi.mock(
  11. '../../../../app/src/Features/UserMembership/UserMembershipErrors.mjs',
  12. () =>
  13. vi.importActual(
  14. '../../../../app/src/Features/UserMembership/UserMembershipErrors.mjs'
  15. )
  16. )
  17. describe('UserMembershipHandler', function () {
  18. beforeEach(async function (ctx) {
  19. ctx.user = { _id: new ObjectId() }
  20. ctx.newUser = { _id: new ObjectId(), email: 'new-user-email@foo.bar' }
  21. ctx.fakeEntityId = new ObjectId()
  22. ctx.subscription = {
  23. _id: 'mock-subscription-id',
  24. groupPlan: true,
  25. membersLimit: 10,
  26. member_ids: [new ObjectId(), new ObjectId()],
  27. manager_ids: [new ObjectId()],
  28. invited_emails: ['mock-email-1@foo.com'],
  29. teamInvites: [{ email: 'mock-email-1@bar.com' }],
  30. update: vi.fn().mockReturnValue({
  31. exec: vi.fn().mockResolvedValue(),
  32. }),
  33. updateOne: vi.fn().mockReturnValue({
  34. exec: vi.fn().mockResolvedValue(),
  35. }),
  36. }
  37. ctx.institution = {
  38. _id: 'mock-institution-id',
  39. v1Id: 123,
  40. managerIds: [new ObjectId(), new ObjectId(), new ObjectId()],
  41. updateOne: vi.fn().mockReturnValue({
  42. exec: vi.fn().mockResolvedValue(),
  43. }),
  44. }
  45. ctx.publisher = {
  46. _id: 'mock-publisher-id',
  47. slug: 'slug',
  48. managerIds: [new ObjectId(), new ObjectId()],
  49. updateOne: vi.fn().mockReturnValue({
  50. exec: vi.fn().mockResolvedValue(),
  51. }),
  52. }
  53. ctx.UserMembershipViewModel = {
  54. promises: {
  55. buildAsync: vi.fn().mockResolvedValue([{ _id: 'mock-member-id' }]),
  56. },
  57. build: vi.fn().mockReturnValue(ctx.newUser),
  58. }
  59. ctx.UserGetter = {
  60. promises: {
  61. getUserByAnyEmail: vi.fn().mockResolvedValue(ctx.newUser),
  62. },
  63. }
  64. ctx.Institution = {
  65. findOne: vi.fn().mockReturnValue({
  66. exec: vi.fn().mockResolvedValue(ctx.institution),
  67. }),
  68. }
  69. ctx.Subscription = {
  70. findOne: vi.fn().mockReturnValue({
  71. exec: vi.fn().mockResolvedValue(ctx.subscription),
  72. }),
  73. }
  74. ctx.Publisher = {
  75. findOne: vi.fn().mockReturnValue({
  76. exec: vi.fn().mockResolvedValue(ctx.publisher),
  77. }),
  78. create: vi.fn().mockReturnValue({
  79. exec: vi.fn().mockResolvedValue(ctx.publisher),
  80. }),
  81. }
  82. ctx.Modules = {
  83. promises: {
  84. hooks: {
  85. fire: vi.fn().mockResolvedValue(),
  86. },
  87. },
  88. }
  89. ctx.mongoose = {
  90. startSession: vi.fn().mockResolvedValue({
  91. withTransaction: vi.fn(async callback => await callback()),
  92. endSession: vi.fn().mockResolvedValue(),
  93. }),
  94. }
  95. vi.doMock('mongodb-legacy', () => ({
  96. default: { ObjectId },
  97. }))
  98. vi.doMock(
  99. '../../../../app/src/Features/UserMembership/UserMembershipViewModel',
  100. () => ({
  101. default: ctx.UserMembershipViewModel,
  102. })
  103. )
  104. vi.doMock('../../../../app/src/Features/User/UserGetter', () => ({
  105. default: ctx.UserGetter,
  106. }))
  107. vi.doMock('../../../../app/src/models/Institution', () => ({
  108. Institution: ctx.Institution,
  109. }))
  110. vi.doMock('../../../../app/src/models/Subscription', () => ({
  111. Subscription: ctx.Subscription,
  112. }))
  113. vi.doMock('../../../../app/src/models/Publisher', () => ({
  114. Publisher: ctx.Publisher,
  115. }))
  116. vi.doMock('../../../../app/src/infrastructure/Modules', () => ({
  117. default: ctx.Modules,
  118. }))
  119. vi.doMock('../../../../app/src/infrastructure/Mongoose', () => ({
  120. default: ctx.mongoose,
  121. }))
  122. ctx.UserMembershipHandler = (await import(modulePath)).default
  123. })
  124. describe('getEntityWithoutAuthorizationCheck', function () {
  125. it('get publisher', async function (ctx) {
  126. const subscription =
  127. await ctx.UserMembershipHandler.promises.getEntityWithoutAuthorizationCheck(
  128. ctx.fakeEntityId,
  129. EntityConfigs.publisher
  130. )
  131. const expectedQuery = { slug: ctx.fakeEntityId }
  132. expect(ctx.Publisher.findOne).toHaveBeenCalledWith(expectedQuery)
  133. expect(subscription).to.equal(ctx.publisher)
  134. })
  135. })
  136. describe('getUsers', function () {
  137. describe('group', function () {
  138. it('build view model for all users', async function (ctx) {
  139. await ctx.UserMembershipHandler.promises.getUsers(
  140. ctx.subscription,
  141. EntityConfigs.group
  142. )
  143. expect(
  144. serializeIds(
  145. ctx.UserMembershipViewModel.promises.buildAsync.mock.calls[0][0]
  146. )
  147. ).toEqual(
  148. serializeIds(
  149. ctx.subscription.invited_emails.concat(
  150. ctx.subscription.teamInvites[0].email,
  151. ctx.subscription.member_ids
  152. )
  153. )
  154. )
  155. })
  156. })
  157. describe('group managers', function () {
  158. it('build view model for all managers', async function (ctx) {
  159. await ctx.UserMembershipHandler.promises.getUsers(
  160. ctx.subscription,
  161. EntityConfigs.groupManagers
  162. )
  163. expect(
  164. serializeIds(
  165. ctx.UserMembershipViewModel.promises.buildAsync.mock.calls[0][0]
  166. )
  167. ).toEqual(serializeIds(ctx.subscription.manager_ids))
  168. })
  169. })
  170. describe('institution', function () {
  171. it('build view model for all managers', async function (ctx) {
  172. await ctx.UserMembershipHandler.promises.getUsers(
  173. ctx.institution,
  174. EntityConfigs.institution
  175. )
  176. expect(
  177. serializeIds(
  178. ctx.UserMembershipViewModel.promises.buildAsync.mock.calls[0][0]
  179. )
  180. ).toEqual(serializeIds(ctx.institution.managerIds))
  181. })
  182. })
  183. })
  184. describe('createEntity', function () {
  185. it('creates publisher', async function (ctx) {
  186. await ctx.UserMembershipHandler.promises.createEntity(
  187. ctx.fakeEntityId,
  188. EntityConfigs.publisher
  189. )
  190. expect(ctx.Publisher.create).toHaveBeenCalledWith({
  191. slug: ctx.fakeEntityId,
  192. })
  193. })
  194. })
  195. describe('addUser', function () {
  196. beforeEach(function (ctx) {
  197. ctx.email = ctx.newUser.email
  198. })
  199. describe('institution', function () {
  200. it('get user', async function (ctx) {
  201. await ctx.UserMembershipHandler.promises.addUser(
  202. ctx.institution,
  203. EntityConfigs.institution,
  204. ctx.email
  205. )
  206. expect(ctx.UserGetter.promises.getUserByAnyEmail).toHaveBeenCalledWith(
  207. ctx.email
  208. )
  209. })
  210. it('handle user not found', async function (ctx) {
  211. ctx.UserGetter.promises.getUserByAnyEmail.mockResolvedValue(null)
  212. try {
  213. await ctx.UserMembershipHandler.promises.addUser(
  214. ctx.institution,
  215. EntityConfigs.institution,
  216. ctx.email
  217. )
  218. expect.fail('Expected addUser to throw')
  219. } catch (err) {
  220. expect(err).toBeInstanceOf(UserMembershipErrors.UserNotFoundError)
  221. }
  222. })
  223. it('handle user already added', async function (ctx) {
  224. ctx.institution.managerIds.push(ctx.newUser._id)
  225. try {
  226. await ctx.UserMembershipHandler.promises.addUser(
  227. ctx.institution,
  228. EntityConfigs.institution,
  229. ctx.email
  230. )
  231. expect.fail('Expected addUser to throw')
  232. } catch (err) {
  233. expect(err).toBeInstanceOf(UserMembershipErrors.UserAlreadyAddedError)
  234. }
  235. })
  236. it('add user to institution', async function (ctx) {
  237. await ctx.UserMembershipHandler.promises.addUser(
  238. ctx.institution,
  239. EntityConfigs.institution,
  240. ctx.email
  241. )
  242. expect(ctx.institution.updateOne).toHaveBeenCalledWith({
  243. $addToSet: { managerIds: ctx.newUser._id },
  244. })
  245. })
  246. it('return user view', async function (ctx) {
  247. const user = await ctx.UserMembershipHandler.promises.addUser(
  248. ctx.institution,
  249. EntityConfigs.institution,
  250. ctx.email
  251. )
  252. expect(user).to.equal(ctx.newUser)
  253. })
  254. })
  255. describe('group managers', function () {
  256. it('add user to group managers', async function (ctx) {
  257. await ctx.UserMembershipHandler.promises.addUser(
  258. ctx.subscription,
  259. EntityConfigs.groupManagers,
  260. ctx.email
  261. )
  262. expect(ctx.subscription.updateOne).toHaveBeenCalledWith({
  263. $addToSet: { manager_ids: ctx.newUser._id },
  264. })
  265. })
  266. it('should write a group audit log when subscription has managed users enabled', async function (ctx) {
  267. ctx.subscription.managedUsersEnabled = true
  268. const auditInfo = {
  269. initiatorId: new ObjectId(),
  270. ipAddress: '192.168.1.1',
  271. }
  272. await ctx.UserMembershipHandler.promises.addUser(
  273. ctx.subscription,
  274. EntityConfigs.groupManagers,
  275. ctx.email,
  276. auditInfo
  277. )
  278. expect(ctx.Modules.promises.hooks.fire).toHaveBeenCalledWith(
  279. 'addGroupAuditLogEntry',
  280. {
  281. groupId: ctx.subscription._id,
  282. operation: 'group-role-changed',
  283. initiatorId: auditInfo.initiatorId,
  284. ipAddress: auditInfo.ipAddress,
  285. info: {
  286. userId: ctx.newUser._id,
  287. role: 'manager',
  288. },
  289. },
  290. expect.anything() // session object
  291. )
  292. })
  293. it('should not write a group audit log when subscription does not have managed users enabled', async function (ctx) {
  294. ctx.subscription.managedUsersEnabled = false
  295. const auditInfo = {
  296. initiatorId: new ObjectId(),
  297. ipAddress: '192.168.1.1',
  298. }
  299. await ctx.UserMembershipHandler.promises.addUser(
  300. ctx.subscription,
  301. EntityConfigs.groupManagers,
  302. ctx.email,
  303. auditInfo
  304. )
  305. expect(ctx.Modules.promises.hooks.fire).not.toHaveBeenCalled()
  306. })
  307. })
  308. })
  309. describe('removeUser', function () {
  310. describe('institution', function () {
  311. it('remove user from institution', async function (ctx) {
  312. await ctx.UserMembershipHandler.promises.removeUser(
  313. ctx.institution,
  314. EntityConfigs.institution,
  315. ctx.newUser._id
  316. )
  317. expect(ctx.institution.updateOne).toHaveBeenCalledWith({
  318. $pull: { managerIds: ctx.newUser._id },
  319. })
  320. })
  321. it('handle admin', async function (ctx) {
  322. ctx.subscription.admin_id = ctx.newUser._id
  323. try {
  324. await ctx.UserMembershipHandler.promises.removeUser(
  325. ctx.subscription,
  326. EntityConfigs.groupManagers,
  327. ctx.newUser._id
  328. )
  329. expect.fail('Expected removeUser to throw')
  330. } catch (err) {
  331. expect(err).toBeInstanceOf(UserMembershipErrors.UserIsManagerError)
  332. }
  333. })
  334. })
  335. describe('group managers', function () {
  336. it('remove user from group managers', async function (ctx) {
  337. await ctx.UserMembershipHandler.promises.removeUser(
  338. ctx.subscription,
  339. EntityConfigs.groupManagers,
  340. ctx.newUser._id
  341. )
  342. expect(ctx.subscription.updateOne).toHaveBeenCalledWith({
  343. $pull: { manager_ids: ctx.newUser._id },
  344. })
  345. })
  346. it('should write a group audit log when subscription has managed users enabled', async function (ctx) {
  347. ctx.subscription.managedUsersEnabled = true
  348. const auditInfo = {
  349. initiatorId: new ObjectId(),
  350. ipAddress: '192.168.1.1',
  351. }
  352. await ctx.UserMembershipHandler.promises.removeUser(
  353. ctx.subscription,
  354. EntityConfigs.groupManagers,
  355. ctx.newUser._id,
  356. auditInfo
  357. )
  358. expect(ctx.Modules.promises.hooks.fire).toHaveBeenCalledWith(
  359. 'addGroupAuditLogEntry',
  360. {
  361. groupId: ctx.subscription._id,
  362. operation: 'group-role-changed',
  363. initiatorId: auditInfo.initiatorId,
  364. ipAddress: auditInfo.ipAddress,
  365. info: {
  366. userId: ctx.newUser._id,
  367. role: 'member',
  368. },
  369. }
  370. )
  371. })
  372. it('should not write a group audit log when subscription does not have managed users enabled', async function (ctx) {
  373. ctx.subscription.managedUsersEnabled = false
  374. const auditInfo = {
  375. initiatorId: new ObjectId(),
  376. ipAddress: '192.168.1.1',
  377. }
  378. await ctx.UserMembershipHandler.promises.removeUser(
  379. ctx.subscription,
  380. EntityConfigs.groupManagers,
  381. ctx.newUser._id,
  382. auditInfo
  383. )
  384. expect(ctx.Modules.promises.hooks.fire).not.toHaveBeenCalled()
  385. })
  386. })
  387. })
  388. })