refactor to use config file

This commit is contained in:
Tim Alby 2018-10-11 18:56:14 +01:00
parent 1256d29af9
commit e646c5c42a
11 changed files with 205 additions and 190 deletions

View file

@ -1,9 +0,0 @@
Institution = require('../../models/Institution').Institution
logger = require("logger-sharelatex")
ObjectId = require('mongoose').Types.ObjectId
module.exports = InstitutionLocator =
findManagedInstitution: (managerId, callback)->
logger.log managerId: managerId, "finding managed Institution"
Institution.findOne managerIds: managerId, callback

View file

@ -70,6 +70,14 @@ module.exports =
res.contentType('text/csv')
res.send(groupCsv)
# legacy route
redirectToSubscriptionGroupAdminPage: (req, res) ->
user_id = AuthenticationController.getLoggedInUserId(req)
getManagedSubscription user_id, (error, subscription) ->
return next(error) if error?
if !subscription?.groupPlan
return res.redirect("/user/subscription")
res.redirect("/manage/groups/#{subscription._id}/members")
getManagedSubscription = (managerId, callback) ->
SubscriptionLocator.findManagedSubscription managerId, (err, subscription)->

View file

@ -20,8 +20,7 @@ module.exports =
webRouter.get '/user/subscription/thank-you', AuthenticationController.requireLogin(), SubscriptionController.successful_subscription
webRouter.get '/subscription/group', AuthenticationController.requireLogin(), (req, res, next) ->
res.redirect('/manage/group/members') # legacy route
webRouter.get '/subscription/group', AuthenticationController.requireLogin(), SubscriptionGroupController.redirectToSubscriptionGroupAdminPage
webRouter.post '/subscription/group/user', AuthenticationController.requireLogin(), SubscriptionGroupController.addUserToGroup
webRouter.get '/subscription/group/export', AuthenticationController.requireLogin(), SubscriptionGroupController.exportGroupCsv
webRouter.delete '/subscription/group/user/:user_id', AuthenticationController.requireLogin(), SubscriptionGroupController.removeUserFromGroup

View file

@ -1,65 +1,54 @@
AuthenticationController = require('../Authentication/AuthenticationController')
UserMembershipHandler = require('./UserMembershipHandler')
EntityConfigs = require('./UserMembershipEntityConfigs')
Errors = require('../Errors/Errors')
logger = require("logger-sharelatex")
module.exports =
index: (entityName, req, res, next)->
userId = AuthenticationController.getLoggedInUserId(req)
UserMembershipHandler.getEntity entityName, userId, (error, entity)->
getEntity entityName, req, (error, entity, entityConfig) ->
return next(error) if error?
UserMembershipHandler.getUsers entityName, entity, (error, users)->
UserMembershipHandler.getUsers entity, entityConfig, (error, users)->
return next(error) if error?
res.render "user_membership/index",
users: users
entity: entity
translations: getTranslationsFor(entityName)
paths: getPathsFor(entityName)
groupSize: entity.membersLimit if entityConfig.hasMembersLimit
translations: entityConfig.translations
paths: entityConfig.pathsFor(entity._id.toString())
add: (entityName, req, res, next)->
userId = AuthenticationController.getLoggedInUserId(req)
email = req.body.email
return res.sendStatus 422 unless email
UserMembershipHandler.getEntity entityName, userId, (error, entity)->
getEntity entityName, req, (error, entity, entityConfig) ->
return next(error) if error?
UserMembershipHandler.addUser entityName, entity, email, (error, user)->
if entityConfig.readOnly
return next(new Errors.NotFoundError("Cannot add users to entity"))
UserMembershipHandler.addUser entity, entityConfig, email, (error, user)->
return next(error) if error?
res.json(user: user)
remove: (entityName, req, res, next)->
loggedInUserId = AuthenticationController.getLoggedInUserId(req)
userId = req.params.userId
UserMembershipHandler.getEntity entityName, loggedInUserId, (error, entity)->
getEntity entityName, req, (error, entity, entityConfig) ->
return next(error) if error?
UserMembershipHandler.removeUser entityName, entity, userId, (error, user)->
if entityConfig.readOnly
return next(new Errors.NotFoundError("Cannot remove users from entity"))
UserMembershipHandler.removeUser entity, entityConfig, userId, (error, user)->
return next(error) if error?
res.send()
getTranslationsFor = (entityName) ->
switch entityName
when 'group'
title: 'group_account'
remove: 'remove_from_group'
when 'groupManagers'
title: 'group_managers'
remove: 'remove_manager'
when 'institution'
title: 'institution_managers'
remove: 'remove_manager'
getEntity = (entityName, req, callback) ->
entityConfig = EntityConfigs[entityName]
unless entityConfig
return callback(new Errors.NotFoundError("No such entity: #{entityName}"))
getPathsFor = (entityName) ->
switch entityName
when 'group'
addMember: '/subscription/invites'
removeMember: '/subscription/group/user'
removeInvite: '/subscription/invites'
exportMembers: '/subscription/group/export'
when 'groupManagers'
addMember: "/manage/group/managers"
removeMember: "/manage/group/managers"
when 'institution'
addMember: "/manage/institution/managers"
removeMember: "/manage/institution/managers"
loggedInUser = AuthenticationController.getSessionUser(req)
entityId = req.params.id
UserMembershipHandler.getEntity entityId, entityConfig, loggedInUser, (error, entity)->
return callback(error) if error?
return callback(new Errors.NotFoundError()) unless entity?
callback(null, entity, entityConfig)

View file

@ -0,0 +1,47 @@
module.exports =
group:
modelName: 'Subscription'
readOnly: true
hasMembersLimit: true
fields:
read: ['invited_emails', 'teamInvites', 'member_ids']
write: null
access: 'manager_ids'
baseQuery:
groupPlan: true
translations:
title: 'group_account'
remove: 'remove_from_group'
pathsFor: () ->
addMember: '/subscription/invites'
removeMember: '/subscription/group/user'
removeInvite: '/subscription/invites'
exportMembers: '/subscription/group/export'
groupManagers:
modelName: 'Subscription'
fields:
read: ['manager_ids']
write: 'manager_ids'
access: 'manager_ids'
baseQuery:
groupPlan: true
translations:
title: 'group_managers'
remove: 'remove_manager'
pathsFor: (id) ->
addMember: "/manage/groups/#{id}/managers"
removeMember: "/manage/groups/#{id}/managers"
institution:
modelName: 'Institution'
fields:
read: ['managerIds']
write: 'managerIds'
access: 'managerIds'
translations:
title: 'institution_managers'
remove: 'remove_manager'
pathsFor: (id) ->
addMember: "/manage/institutions/#{id}/managers"
removeMember: "/manage/institutions/#{id}/managers"

View file

@ -1,66 +1,37 @@
ObjectId = require('mongoose').Types.ObjectId
async = require("async")
Errors = require('../Errors/Errors')
SubscriptionLocator = require('../Subscription/SubscriptionLocator')
InstitutionsLocator = require('../Institutions/InstitutionsLocator')
EntityModels =
Institution: require('../../models/Institution').Institution
Subscription: require('../../models/Subscription').Subscription
UserMembershipViewModel = require('./UserMembershipViewModel')
UserGetter = require('../User/UserGetter')
logger = require('logger-sharelatex')
module.exports =
getEntity: (entityName, userId, callback = (error, entity) ->) ->
switch entityName
when 'group' then getGroupSubscription(userId, callback)
when 'groupManagers'
getGroupSubscription userId, (error, subscription) ->
subscription.membersLimit = null if subscription # managers are unlimited
callback(error, subscription)
when 'institution' then getInstitution(userId, callback)
else callback(new Errors.NotFoundError("No such entity: #{entityName}"))
getEntity: (entityId, entityConfig, loggedInUser, callback = (error, entity) ->) ->
query = Object.assign({}, entityConfig.baseQuery)
query._id = ObjectId(entityId)
unless loggedInUser.isAdmin
query[entityConfig.fields.access] = ObjectId(loggedInUser._id)
EntityModels[entityConfig.modelName].findOne query, callback
getUsers: (entityName, entity, callback = (error, users) ->) ->
attributes = switch entityName
when 'group' then ['invited_emails', 'teamInvites', 'member_ids']
when 'groupManagers' then ['manager_ids']
when 'institution' then ['managerIds']
getUsers: (entity, entityConfig, callback = (error, users) ->) ->
attributes = entityConfig.fields.read
getPopulatedListOfMembers(entity, attributes, callback)
addUser: (entityName, entity, email, callback = (error, user) ->) ->
attribute = switch entityName
when 'groupManagers' then 'manager_ids'
when 'institution' then 'managerIds'
unless attribute
return callback(new Errors.NotFoundError("Cannot add user to entity: #{entityName}"))
addUser: (entity, entityConfig, email, callback = (error, user) ->) ->
attribute = entityConfig.fields.write
UserGetter.getUserByAnyEmail email, (error, user) ->
error ||= new Errors.NotFoundError("No user found with email #{email}") unless user
return callback(error) if error?
addUserToEntity entity, attribute, user, (error) ->
callback(error, UserMembershipViewModel.build(user))
removeUser: (entityName, entity, userId, callback = (error) ->) ->
attribute = switch entityName
when 'groupManagers' then 'manager_ids'
when 'institution' then 'managerIds'
else callback(new Errors.NotFoundError("Cannot remove user from entity: #{entityName}"))
removeUser: (entity, entityConfig, userId, callback = (error) ->) ->
attribute = entityConfig.fields.write
removeUserFromEntity entity, attribute, userId, callback
getGroupSubscription = (managerId, callback = (error, subscription) ->) ->
SubscriptionLocator.findManagedSubscription managerId, (err, subscription)->
if subscription? and subscription.groupPlan
logger.log managerId: managerId, 'got managed subscription'
else
err ||= new Errors.NotFoundError("No subscription found managed by user #{managerId}")
callback(err, subscription)
getInstitution = (managerId, callback = (error, institution) ->) ->
InstitutionsLocator.findManagedInstitution managerId, (err, institution)->
if institution?
logger.log managerId: managerId, 'got managed subscription'
else
err ||= new Errors.NotFoundError("No institution found managed by user #{managerId}")
callback(err, institution)
getPopulatedListOfMembers = (entity, attributes, callback = (error, users)->)->
userObjects = []

View file

@ -3,24 +3,24 @@ UserMembershipController = require './UserMembershipController'
module.exports =
apply: (webRouter) ->
webRouter.get '/manage/group/members',
webRouter.get '/manage/groups/:id/members',
AuthenticationController.requireLogin(),
(req, res, next) -> UserMembershipController.index('group', req, res, next)
regularEntitites =
group: 'groupManagers'
institution: 'institution'
groups: 'groupManagers'
institutions: 'institution'
for pathName, entityName of regularEntitites
do (pathName, entityName) ->
webRouter.get "/manage/#{pathName}/managers",
webRouter.get "/manage/#{pathName}/:id/managers",
AuthenticationController.requireLogin(),
(req, res, next) -> UserMembershipController.index(entityName, req, res, next)
webRouter.post "/manage/#{pathName}/managers",
webRouter.post "/manage/#{pathName}/:id/managers",
AuthenticationController.requireLogin(),
(req, res, next) -> UserMembershipController.add(entityName, req, res, next)
webRouter.delete "/manage/#{pathName}/managers/:userId",
webRouter.delete "/manage/#{pathName}/:id/managers/:userId",
AuthenticationController.requireLogin(),
(req, res, next) -> UserMembershipController.remove(entityName, req, res, next)

View file

@ -86,4 +86,4 @@ block content
script(type="text/javascript").
window.users = !{JSON.stringify(users)};
window.paths = !{JSON.stringify(paths)};
window.groupSize = #{entity.membersLimit || 'null'};
window.groupSize = #{groupSize || 'null'};

View file

@ -1,29 +0,0 @@
SandboxedModule = require('sandboxed-module')
should = require('chai').should()
sinon = require('sinon')
assertCalledWith = sinon.assert.calledWith
assertNotCalled = sinon.assert.notCalled
modulePath = "../../../../app/js/Features/Institutions/InstitutionsLocator"
assert = require("chai").assert
ObjectId = require('mongoose').Types.ObjectId
describe 'InstitutionsLocator', ->
beforeEach ->
@user =
_id: "5208dd34438842e2db333333"
@institution =
v1Id: 123
managersIds: [ObjectId(), ObjectId()]
@Institution =
findOne: sinon.stub().yields(null, @institution)
@InstitutionsLocator = SandboxedModule.require modulePath, requires:
'../../models/Institution': Institution: @Institution
"logger-sharelatex": log:->
describe "finding managed institution", ->
it "should query the database", (done) ->
@InstitutionsLocator.findManagedInstitution @user._id, (err, institution)=>
assertCalledWith(@Institution.findOne, { managerIds: @user._id })
institution.should.equal @institution
done()

View file

@ -9,17 +9,20 @@ modulePath = "../../../../app/js/Features/UserMembership/UserMembershipControlle
SandboxedModule = require('sandboxed-module')
MockRequest = require "../helpers/MockRequest"
MockResponse = require "../helpers/MockResponse"
EntityConfigs = require("../../../../app/js/Features/UserMembership/UserMembershipEntityConfigs")
Errors = require("../../../../app/js/Features/Errors/Errors")
describe "UserMembershipController", ->
beforeEach ->
@req = new MockRequest()
@req.params.id = 'mock-entity-id'
@user = _id: 'mock-user-id'
@newUser = _id: 'mock-new-user-id', email: 'new-user-email@foo.bar'
@subscription = { _id: 'mock-subscription-id'}
@users = [{ _id: 'mock-member-id-1' }, { _id: 'mock-member-id-2' }]
@AuthenticationController =
getLoggedInUserId: sinon.stub().returns(@user._id)
getSessionUser: sinon.stub().returns(@user)
@UserMembershipHandler =
getEntity: sinon.stub().yields(null, @subscription)
getUsers: sinon.stub().yields(null, @users)
@ -28,6 +31,7 @@ describe "UserMembershipController", ->
@UserMembershipController = SandboxedModule.require modulePath, requires:
'../Authentication/AuthenticationController': @AuthenticationController
'./UserMembershipHandler': @UserMembershipHandler
'../Errors/Errors': Errors
"logger-sharelatex":
log: ->
err: ->
@ -35,19 +39,28 @@ describe "UserMembershipController", ->
describe 'index', ->
it 'get entity', (done) ->
@UserMembershipController.index 'group', @req, render: () =>
sinon.assert.calledWith(@UserMembershipHandler.getEntity, 'group', @user._id)
sinon.assert.calledWithMatch(
@UserMembershipHandler.getEntity,
@req.params.id,
modelName: 'Subscription',
@user
)
done()
it 'get users', (done) ->
@UserMembershipController.index 'group', @req, render: () =>
sinon.assert.calledWith(@UserMembershipHandler.getUsers, 'group', @subscription)
sinon.assert.calledWithMatch(
@UserMembershipHandler.getUsers,
@subscription,
modelName: 'Subscription',
)
done()
it 'render group view', (done) ->
@UserMembershipController.index 'group', @req, render: (viewPath, viewParams) =>
expect(viewPath).to.equal 'user_membership/index'
expect(viewParams.entity).to.deep.equal @subscription
expect(viewParams.users).to.deep.equal @users
expect(viewParams.groupSize).to.equal @subscription.membersLimit
expect(viewParams.translations.title).to.equal 'group_account'
expect(viewParams.paths.addMember).to.equal '/subscription/invites'
done()
@ -55,6 +68,7 @@ describe "UserMembershipController", ->
it 'render group managers view', (done) ->
@UserMembershipController.index 'groupManagers', @req, render: (viewPath, viewParams) =>
expect(viewPath).to.equal 'user_membership/index'
expect(viewParams.groupSize).to.equal undefined
expect(viewParams.translations.title).to.equal 'group_managers'
expect(viewParams.paths.exportMembers).to.be.undefined
done()
@ -62,22 +76,47 @@ describe "UserMembershipController", ->
it 'render institution view', (done) ->
@UserMembershipController.index 'institution', @req, render: (viewPath, viewParams) =>
expect(viewPath).to.equal 'user_membership/index'
expect(viewParams.groupSize).to.equal undefined
expect(viewParams.translations.title).to.equal 'institution_managers'
expect(viewParams.paths.exportMembers).to.be.undefined
done()
it 'handle unknown entity', (done) ->
@UserMembershipController.index 'foo', @req, null, (error) =>
expect(error).to.extist
expect(error).to.be.an.instanceof(Errors.NotFoundError)
done()
it 'handle entity not found', (done) ->
@UserMembershipHandler.getEntity.yields(null, null)
@UserMembershipController.index 'group', @req, null, (error) =>
expect(error).to.extist
expect(error).to.be.an.instanceof(Errors.NotFoundError)
done()
describe 'add', ->
beforeEach ->
@req.body.email = @newUser.email
it 'get entity', (done) ->
@UserMembershipController.add 'groupManagers', @req, json: () =>
sinon.assert.calledWith(@UserMembershipHandler.getEntity, 'groupManagers', @user._id)
sinon.assert.calledWithMatch(
@UserMembershipHandler.getEntity,
@req.params.id,
modelName: 'Subscription',
@user
)
done()
it 'add user', (done) ->
@UserMembershipController.add 'groupManagers', @req, json: () =>
sinon.assert.calledWith(@UserMembershipHandler.addUser, 'groupManagers', @subscription, @newUser.email)
sinon.assert.calledWithMatch(
@UserMembershipHandler.addUser,
@subscription,
modelName: 'Subscription',
@newUser.email
)
done()
it 'return user object', (done) ->
@ -85,11 +124,28 @@ describe "UserMembershipController", ->
payload.user.should.equal @newUser
done()
it 'handle readOnly entity', (done) ->
@UserMembershipController.add 'group', @req, null, (error) =>
expect(error).to.extist
expect(error).to.be.an.instanceof(Errors.NotFoundError)
done()
describe 'remove', ->
beforeEach ->
@req.params.userId = @newUser._id
it 'remove user', (done) ->
@UserMembershipController.remove 'groupManagers', @req, send: () =>
sinon.assert.calledWith(@UserMembershipHandler.removeUser, 'groupManagers', @subscription, @newUser._id)
sinon.assert.calledWithMatch(
@UserMembershipHandler.removeUser,
@subscription,
modelName: 'Subscription',
@newUser._id
)
done()
it 'handle readOnly entity', (done) ->
@UserMembershipController.remove 'group', @req, null, (error) =>
expect(error).to.extist
expect(error).to.be.an.instanceof(Errors.NotFoundError)
done()

View file

@ -8,11 +8,13 @@ ObjectId = require("../../../../app/js/infrastructure/mongojs").ObjectId
modulePath = "../../../../app/js/Features/UserMembership/UserMembershipHandler"
SandboxedModule = require("sandboxed-module")
Errors = require("../../../../app/js/Features/Errors/Errors")
EntityConfigs = require("../../../../app/js/Features/UserMembership/UserMembershipEntityConfigs")
describe 'UserMembershipHandler', ->
beforeEach ->
@user = _id: 'mock-user-id'
@newUser = _id: 'mock-new-user-id', email: 'new-user-email@foo.bar'
@fakeEntityId = ObjectId()
@subscription =
_id: 'mock-subscription-id'
groupPlan: true
@ -28,79 +30,66 @@ describe 'UserMembershipHandler', ->
managerIds: [ObjectId(), ObjectId(), ObjectId()]
update: sinon.stub().yields(null)
@SubscriptionLocator =
findManagedSubscription: sinon.stub().yields(null, @subscription)
@InstitutionsLocator =
findManagedInstitution: sinon.stub().yields(null, @institution)
@UserMembershipViewModel =
buildAsync: sinon.stub().yields(null, { _id: 'mock-member-id'})
build: sinon.stub().returns(@newUser)
@UserGetter =
getUserByAnyEmail: sinon.stub().yields(null, @newUser)
@Institution =
findOne: sinon.stub().yields(null, @institution)
@Subscription =
findOne: sinon.stub().yields(null, @subscription)
@UserMembershipHandler = SandboxedModule.require modulePath, requires:
'../Subscription/SubscriptionLocator': @SubscriptionLocator
'../Institutions/InstitutionsLocator': @InstitutionsLocator
'./UserMembershipViewModel': @UserMembershipViewModel
'../User/UserGetter': @UserGetter
'../Errors/Errors': Errors
'../../models/Institution': Institution: @Institution
'../../models/Subscription': Subscription: @Subscription
'logger-sharelatex':
log: ->
err: ->
describe 'getEntty', ->
it 'validate type', (done) ->
@UserMembershipHandler.getEntity 'foo', null, (error) ->
should.exist(error)
expect(error.message).to.match /No such entity/
done()
describe 'group subscriptions', ->
it 'get subscription', (done) ->
@UserMembershipHandler.getEntity 'group', @user._id, (error, subscription) =>
@UserMembershipHandler.getEntity @fakeEntityId, EntityConfigs.group, @user, (error, subscription) =>
should.not.exist(error)
assertCalledWith(@SubscriptionLocator.findManagedSubscription, @user._id)
expectedQuery =
groupPlan: true
_id: @fakeEntityId
manager_ids: ObjectId(@user._id)
assertCalledWith(@Subscription.findOne, expectedQuery)
expect(subscription).to.equal @subscription
expect(subscription.membersLimit).to.equal 10
done()
it 'check subscription is a group', (done) ->
@SubscriptionLocator.findManagedSubscription.yields(null, { groupPlan: false })
@UserMembershipHandler.getEntity 'group', @user._id, (error, subscription) ->
should.exist(error)
it 'get for admin', (done) ->
@UserMembershipHandler.getEntity @fakeEntityId, EntityConfigs.group, { isAdmin: true }, (error, subscription) =>
should.not.exist(error)
expectedQuery =
groupPlan: true
_id: @fakeEntityId
assertCalledWith(@Subscription.findOne, expectedQuery)
done()
it 'handle error', (done) ->
@SubscriptionLocator.findManagedSubscription.yields(new Error('some error'))
@UserMembershipHandler.getEntity 'group', @user._id, (error, subscription) =>
@Subscription.findOne.yields(new Error('some error'))
@UserMembershipHandler.getEntity @fakeEntityId, EntityConfigs.group, @user._id, (error, subscription) =>
should.exist(error)
done()
describe 'group managers', ->
it 'has no members limit', (done) ->
@UserMembershipHandler.getEntity 'groupManagers', @user._id, (error, subscription) =>
should.not.exist(error)
assertCalledWith(@SubscriptionLocator.findManagedSubscription, @user._id)
expect(subscription.membersLimit).to.equal null
done()
describe 'institutions', ->
it 'get institution', (done) ->
@UserMembershipHandler.getEntity 'institution', @user._id, (error, institution) =>
@UserMembershipHandler.getEntity @fakeEntityId, EntityConfigs.institution, @user, (error, institution) =>
should.not.exist(error)
assertCalledWith(@InstitutionsLocator.findManagedInstitution, @user._id)
expectedQuery = _id: @fakeEntityId, managerIds: ObjectId(@user._id)
assertCalledWith(@Institution.findOne, expectedQuery)
expect(institution).to.equal @institution
done()
it 'handle institution not found', (done) ->
@InstitutionsLocator.findManagedInstitution.yields(null, null)
@UserMembershipHandler.getEntity 'institution', @user._id, (error, institution) =>
should.exist(error)
expect(error).to.be.an.instanceof(Errors.NotFoundError)
done()
it 'handle errors', (done) ->
@InstitutionsLocator.findManagedInstitution.yields(new Error('nope'))
@UserMembershipHandler.getEntity 'institution', @user._id, (error, institution) =>
@Institution.findOne.yields(new Error('nope'))
@UserMembershipHandler.getEntity @fakeEntityId, EntityConfigs.institution, @user._id, (error, institution) =>
should.exist(error)
expect(error).to.not.be.an.instanceof(Errors.NotFoundError)
done()
@ -108,7 +97,7 @@ describe 'UserMembershipHandler', ->
describe 'getUsers', ->
describe 'group', ->
it 'build view model for all users', (done) ->
@UserMembershipHandler.getUsers 'group', @subscription, (error, users) =>
@UserMembershipHandler.getUsers @subscription, EntityConfigs.group, (error, users) =>
expectedCallcount =
@subscription.member_ids.length +
@subscription.invited_emails.length +
@ -118,14 +107,14 @@ describe 'UserMembershipHandler', ->
describe 'group mamagers', ->
it 'build view model for all managers', (done) ->
@UserMembershipHandler.getUsers 'groupManagers', @subscription, (error, users) =>
@UserMembershipHandler.getUsers @subscription, EntityConfigs.groupManagers, (error, users) =>
expectedCallcount = @subscription.manager_ids.length
expect(@UserMembershipViewModel.buildAsync.callCount).to.equal expectedCallcount
done()
describe 'institution', ->
it 'build view model for all managers', (done) ->
@UserMembershipHandler.getUsers 'institution', @institution, (error, users) =>
@UserMembershipHandler.getUsers @institution, EntityConfigs.institution, (error, users) =>
expectedCallcount = @institution.managerIds.length
expect(@UserMembershipViewModel.buildAsync.callCount).to.equal expectedCallcount
done()
@ -134,39 +123,33 @@ describe 'UserMembershipHandler', ->
beforeEach ->
@email = @newUser.email
describe 'group', ->
it 'fails', (done) ->
@UserMembershipHandler.addUser 'group', @subscription, @email, (error) =>
expect(error).to.exist
done()
describe 'institution', ->
it 'get user', (done) ->
@UserMembershipHandler.addUser 'institution', @institution, @email, (error, user) =>
@UserMembershipHandler.addUser @institution, EntityConfigs.institution, @email, (error, user) =>
assertCalledWith(@UserGetter.getUserByAnyEmail, @email)
done()
it 'handle user not found', (done) ->
@UserGetter.getUserByAnyEmail.yields(null, null)
@UserMembershipHandler.addUser 'institution', @institution, @email, (error) =>
@UserMembershipHandler.addUser @institution, EntityConfigs.institution, @email, (error) =>
expect(error).to.exist
expect(error).to.be.an.instanceof(Errors.NotFoundError)
done()
it 'add user to institution', (done) ->
@UserMembershipHandler.addUser 'institution', @institution, @email, (error, user) =>
@UserMembershipHandler.addUser @institution, EntityConfigs.institution, @email, (error, user) =>
assertCalledWith(@institution.update, { $addToSet: managerIds: @newUser._id })
done()
it 'return user view', (done) ->
@UserMembershipHandler.addUser 'institution', @institution, @email, (error, user) =>
@UserMembershipHandler.addUser @institution, EntityConfigs.institution, @email, (error, user) =>
user.should.equal @newUser
done()
describe 'removeUser', ->
describe 'institution', ->
it 'remove user from institution', (done) ->
@UserMembershipHandler.removeUser 'institution', @institution, @newUser._id, (error, user) =>
@UserMembershipHandler.removeUser @institution, EntityConfigs.institution, @newUser._id, (error, user) =>
lastCall = @institution.update.lastCall
assertCalledWith(@institution.update, { $pull: managerIds: @newUser._id })
done()