UserMembershipControllerTests.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import sinon from 'sinon'
  2. import { expect } from 'chai'
  3. import esmock from 'esmock'
  4. import MockRequest from '../helpers/MockRequest.js'
  5. import MockResponse from '../helpers/MockResponse.js'
  6. import EntityConfigs from '../../../../app/src/Features/UserMembership/UserMembershipEntityConfigs.js'
  7. import Errors from '../../../../app/src/Features/Errors/Errors.js'
  8. import {
  9. UserIsManagerError,
  10. UserNotFoundError,
  11. UserAlreadyAddedError,
  12. } from '../../../../app/src/Features/UserMembership/UserMembershipErrors.js'
  13. const assertCalledWith = sinon.assert.calledWith
  14. const modulePath =
  15. '../../../../app/src/Features/UserMembership/UserMembershipController.mjs'
  16. describe('UserMembershipController', function () {
  17. beforeEach(async function () {
  18. this.req = new MockRequest()
  19. this.req.params.id = 'mock-entity-id'
  20. this.user = { _id: 'mock-user-id' }
  21. this.newUser = { _id: 'mock-new-user-id', email: 'new-user-email@foo.bar' }
  22. this.subscription = {
  23. _id: 'mock-subscription-id',
  24. admin_id: 'mock-admin-id',
  25. fetchV1Data: callback => callback(null, this.subscription),
  26. }
  27. this.institution = {
  28. _id: 'mock-institution-id',
  29. v1Id: 123,
  30. fetchV1Data: callback => {
  31. const institution = Object.assign({}, this.institution)
  32. institution.name = 'Test Institution Name'
  33. callback(null, institution)
  34. },
  35. }
  36. this.users = [
  37. {
  38. _id: 'mock-member-id-1',
  39. email: 'mock-email-1@foo.com',
  40. last_logged_in_at: '2020-08-09T12:43:11.467Z',
  41. last_active_at: '2021-08-09T12:43:11.467Z',
  42. },
  43. {
  44. _id: 'mock-member-id-2',
  45. email: 'mock-email-2@foo.com',
  46. last_logged_in_at: '2020-05-20T10:41:11.407Z',
  47. last_active_at: '2021-05-20T10:41:11.407Z',
  48. },
  49. ]
  50. this.Settings = {
  51. managedUsers: {
  52. enabled: false,
  53. },
  54. }
  55. this.SessionManager = {
  56. getSessionUser: sinon.stub().returns(this.user),
  57. getLoggedInUserId: sinon.stub().returns(this.user._id),
  58. }
  59. this.SSOConfig = {
  60. findById: sinon
  61. .stub()
  62. .returns({ exec: sinon.stub().resolves({ enabled: true }) }),
  63. }
  64. this.UserMembershipHandler = {
  65. getEntity: sinon.stub().yields(null, this.subscription),
  66. createEntity: sinon.stub().yields(null, this.institution),
  67. getUsers: sinon.stub().yields(null, this.users),
  68. addUser: sinon.stub().yields(null, this.newUser),
  69. removeUser: sinon.stub().yields(null),
  70. promises: {
  71. getUsers: sinon.stub().resolves(this.users),
  72. },
  73. }
  74. this.SplitTestHandler = {
  75. promises: {
  76. getAssignment: sinon.stub().resolves({ variant: 'default' }),
  77. },
  78. getAssignment: sinon.stub().yields(null, { variant: 'default' }),
  79. }
  80. this.RecurlyClient = {
  81. promises: {
  82. getSubscription: sinon.stub().resolves({}),
  83. },
  84. }
  85. this.UserMembershipController = await esmock.strict(modulePath, {
  86. '../../../../app/src/Features/UserMembership/UserMembershipErrors': {
  87. UserIsManagerError,
  88. UserNotFoundError,
  89. UserAlreadyAddedError,
  90. },
  91. '../../../../app/src/Features/Authentication/SessionManager':
  92. this.SessionManager,
  93. '../../../../app/src/Features/SplitTests/SplitTestHandler':
  94. this.SplitTestHandler,
  95. '../../../../app/src/Features/UserMembership/UserMembershipHandler':
  96. this.UserMembershipHandler,
  97. '../../../../app/src/Features/Subscription/RecurlyClient':
  98. this.RecurlyClient,
  99. '@overleaf/settings': this.Settings,
  100. '../../../../app/src/models/SSOConfig': { SSOConfig: this.SSOConfig },
  101. })
  102. })
  103. describe('index', function () {
  104. beforeEach(function () {
  105. this.req.entity = this.subscription
  106. this.req.entityConfig = EntityConfigs.group
  107. })
  108. it('get users', async function () {
  109. await this.UserMembershipController.manageGroupMembers(this.req, {
  110. render: () => {
  111. sinon.assert.calledWithMatch(
  112. this.UserMembershipHandler.promises.getUsers,
  113. this.subscription,
  114. { modelName: 'Subscription' }
  115. )
  116. },
  117. })
  118. })
  119. it('render group view', async function () {
  120. this.subscription.managedUsersEnabled = false
  121. await this.UserMembershipController.manageGroupMembers(this.req, {
  122. render: (viewPath, viewParams) => {
  123. expect(viewPath).to.equal('user_membership/group-members-react')
  124. expect(viewParams.users).to.deep.equal(this.users)
  125. expect(viewParams.groupSize).to.equal(this.subscription.membersLimit)
  126. expect(viewParams.managedUsersActive).to.equal(false)
  127. },
  128. })
  129. })
  130. it('render group view with managed users', async function () {
  131. this.subscription.managedUsersEnabled = true
  132. await this.UserMembershipController.manageGroupMembers(this.req, {
  133. render: (viewPath, viewParams) => {
  134. expect(viewPath).to.equal('user_membership/group-members-react')
  135. expect(viewParams.users).to.deep.equal(this.users)
  136. expect(viewParams.groupSize).to.equal(this.subscription.membersLimit)
  137. expect(viewParams.managedUsersActive).to.equal(true)
  138. },
  139. })
  140. })
  141. it('render group managers view', async function () {
  142. this.req.entityConfig = EntityConfigs.groupManagers
  143. await this.UserMembershipController.manageGroupManagers(this.req, {
  144. render: (viewPath, viewParams) => {
  145. expect(viewPath).to.equal('user_membership/group-managers-react')
  146. expect(viewParams.groupSize).to.equal(undefined)
  147. },
  148. })
  149. })
  150. it('render institution view', async function () {
  151. this.req.entity = this.institution
  152. this.req.entityConfig = EntityConfigs.institution
  153. await this.UserMembershipController.manageInstitutionManagers(this.req, {
  154. render: (viewPath, viewParams) => {
  155. expect(viewPath).to.equal(
  156. 'user_membership/institution-managers-react'
  157. )
  158. expect(viewParams.name).to.equal('Test Institution Name')
  159. expect(viewParams.groupSize).to.equal(undefined)
  160. },
  161. })
  162. })
  163. })
  164. describe('add', function () {
  165. beforeEach(function () {
  166. this.req.body.email = this.newUser.email
  167. this.req.entity = this.subscription
  168. this.req.entityConfig = EntityConfigs.groupManagers
  169. })
  170. it('add user', function (done) {
  171. this.UserMembershipController.add(this.req, {
  172. json: () => {
  173. sinon.assert.calledWithMatch(
  174. this.UserMembershipHandler.addUser,
  175. this.subscription,
  176. { modelName: 'Subscription' },
  177. this.newUser.email
  178. )
  179. done()
  180. },
  181. })
  182. })
  183. it('return user object', function (done) {
  184. this.UserMembershipController.add(this.req, {
  185. json: payload => {
  186. payload.user.should.equal(this.newUser)
  187. done()
  188. },
  189. })
  190. })
  191. it('handle readOnly entity', function (done) {
  192. this.req.entityConfig = EntityConfigs.group
  193. this.UserMembershipController.add(this.req, null, error => {
  194. expect(error).to.exist
  195. expect(error).to.be.an.instanceof(Errors.NotFoundError)
  196. done()
  197. })
  198. })
  199. it('handle user already added', function (done) {
  200. this.UserMembershipHandler.addUser.yields(new UserAlreadyAddedError())
  201. this.UserMembershipController.add(this.req, {
  202. status: () => ({
  203. json: payload => {
  204. expect(payload.error.code).to.equal('user_already_added')
  205. done()
  206. },
  207. }),
  208. })
  209. })
  210. it('handle user not found', function (done) {
  211. this.UserMembershipHandler.addUser.yields(new UserNotFoundError())
  212. this.UserMembershipController.add(this.req, {
  213. status: () => ({
  214. json: payload => {
  215. expect(payload.error.code).to.equal('user_not_found')
  216. done()
  217. },
  218. }),
  219. })
  220. })
  221. it('handle invalid email', function (done) {
  222. this.req.body.email = 'not_valid_email'
  223. this.UserMembershipController.add(this.req, {
  224. status: () => ({
  225. json: payload => {
  226. expect(payload.error.code).to.equal('invalid_email')
  227. done()
  228. },
  229. }),
  230. })
  231. })
  232. })
  233. describe('remove', function () {
  234. beforeEach(function () {
  235. this.req.params.userId = this.newUser._id
  236. this.req.entity = this.subscription
  237. this.req.entityConfig = EntityConfigs.groupManagers
  238. })
  239. it('remove user', function (done) {
  240. this.UserMembershipController.remove(this.req, {
  241. sendStatus: () => {
  242. sinon.assert.calledWithMatch(
  243. this.UserMembershipHandler.removeUser,
  244. this.subscription,
  245. { modelName: 'Subscription' },
  246. this.newUser._id
  247. )
  248. done()
  249. },
  250. })
  251. })
  252. it('handle readOnly entity', function (done) {
  253. this.req.entityConfig = EntityConfigs.group
  254. this.UserMembershipController.remove(this.req, null, error => {
  255. expect(error).to.exist
  256. expect(error).to.be.an.instanceof(Errors.NotFoundError)
  257. done()
  258. })
  259. })
  260. it('prevent self removal', function (done) {
  261. this.req.params.userId = this.user._id
  262. this.UserMembershipController.remove(this.req, {
  263. status: () => ({
  264. json: payload => {
  265. expect(payload.error.code).to.equal('managers_cannot_remove_self')
  266. done()
  267. },
  268. }),
  269. })
  270. })
  271. it('prevent admin removal', function (done) {
  272. this.UserMembershipHandler.removeUser.yields(new UserIsManagerError())
  273. this.UserMembershipController.remove(this.req, {
  274. status: () => ({
  275. json: payload => {
  276. expect(payload.error.code).to.equal('managers_cannot_remove_admin')
  277. done()
  278. },
  279. }),
  280. })
  281. })
  282. })
  283. describe('exportCsv', function () {
  284. beforeEach(function () {
  285. this.req.entity = this.subscription
  286. this.req.entityConfig = EntityConfigs.groupManagers
  287. this.res = new MockResponse()
  288. this.UserMembershipController.exportCsv(this.req, this.res)
  289. })
  290. it('get users', function () {
  291. sinon.assert.calledWithMatch(
  292. this.UserMembershipHandler.getUsers,
  293. this.subscription,
  294. { modelName: 'Subscription' }
  295. )
  296. })
  297. it('should set the correct content type on the request', function () {
  298. assertCalledWith(this.res.contentType, 'text/csv; charset=utf-8')
  299. })
  300. it('should name the exported csv file', function () {
  301. assertCalledWith(
  302. this.res.header,
  303. 'Content-Disposition',
  304. 'attachment; filename="Group.csv"'
  305. )
  306. })
  307. it('should export the correct csv', function () {
  308. assertCalledWith(
  309. this.res.send,
  310. '"email","last_logged_in_at","last_active_at"\n"mock-email-1@foo.com","2020-08-09T12:43:11.467Z","2021-08-09T12:43:11.467Z"\n"mock-email-2@foo.com","2020-05-20T10:41:11.407Z","2021-05-20T10:41:11.407Z"'
  311. )
  312. })
  313. })
  314. describe('new', function () {
  315. beforeEach(function () {
  316. this.req.params.name = 'publisher'
  317. this.req.params.id = 'abc'
  318. })
  319. it('renders view', function (done) {
  320. this.UserMembershipController.new(this.req, {
  321. render: (viewPath, data) => {
  322. expect(data.entityName).to.eq('publisher')
  323. expect(data.entityId).to.eq('abc')
  324. done()
  325. },
  326. })
  327. })
  328. })
  329. describe('create', function () {
  330. beforeEach(function () {
  331. this.req.params.name = 'institution'
  332. this.req.entityConfig = EntityConfigs.institution
  333. this.req.params.id = 123
  334. })
  335. it('creates institution', function (done) {
  336. this.UserMembershipController.create(this.req, {
  337. redirect: path => {
  338. expect(path).to.eq(EntityConfigs.institution.pathsFor(123).index)
  339. sinon.assert.calledWithMatch(
  340. this.UserMembershipHandler.createEntity,
  341. 123,
  342. { modelName: 'Institution' }
  343. )
  344. done()
  345. },
  346. })
  347. })
  348. })
  349. })