コード例 #1
0
def test_accept_invitation(session, auth_mock, keycloak_mock, monkeypatch):  # pylint:disable=unused-argument
    """Accept the invitation and add membership from the invitation to the org."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        with patch.object(auth, 'check_auth', return_value=True):
            with patch.object(InvitationService,
                              'notify_admin',
                              return_value=None):
                user_with_token = TestUserInfo.user_test
                user_with_token[
                    'keycloak_guid'] = TestJwtClaims.public_user_role['sub']
                user = factory_user_model(user_with_token)
                patch_token_info({'sub': user.keycloak_guid}, monkeypatch)

                org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
                org_dictionary = org.as_dict()
                invitation_info = factory_invitation(org_dictionary['id'])
                user_with_token_invitee = TestUserInfo.user1
                user_with_token_invitee[
                    'keycloak_guid'] = TestJwtClaims.edit_role_2['sub']
                user_invitee = factory_user_model(user_with_token_invitee)
                new_invitation = InvitationService.create_invitation(
                    invitation_info, User(user_invitee), '')
                new_invitation_dict = new_invitation.as_dict()
                InvitationService.accept_invitation(new_invitation_dict['id'],
                                                    User(user_invitee), '')
                patch_token_info(TestJwtClaims.public_user_role, monkeypatch)
                members = MembershipService.get_members_for_org(
                    org_dictionary['id'], 'PENDING_APPROVAL')
                assert members
                assert len(members) == 1
コード例 #2
0
def test_accept_invitation_for_govm(session, auth_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Accept the invitation and add membership from the invitation to the org."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        with patch.object(auth, 'check_auth', return_value=True):
            with patch.object(InvitationService,
                              'notify_admin',
                              return_value=None):
                user_with_token = TestUserInfo.user_staff_admin
                user_with_token[
                    'keycloak_guid'] = TestJwtClaims.public_user_role['sub']
                user = factory_user_model(user_with_token)
                org = OrgService.create_org(
                    TestOrgInfo.org_govm,
                    user_id=user.id,
                    token_info=TestJwtClaims.staff_admin_role)
                org_dictionary = org.as_dict()
                invitation_info = factory_invitation(org_dictionary['id'])
                user_with_token_invitee = TestUserInfo.user1
                user_with_token_invitee[
                    'keycloak_guid'] = TestJwtClaims.edit_role_2['sub']
                user_invitee = factory_user_model(user_with_token_invitee)
                new_invitation = InvitationService.create_invitation(
                    invitation_info, User(user_invitee), {}, '')
                new_invitation_dict = new_invitation.as_dict()
                InvitationService.accept_invitation(new_invitation_dict['id'],
                                                    User(user_invitee), '')
                members = MembershipService.get_members_for_org(
                    org_dictionary['id'],
                    'ACTIVE',
                    token_info=TestJwtClaims.staff_admin_role)
                assert members
                assert len(members) == 1, 'user gets active membership'
コード例 #3
0
    def post():
        """Post a new user using the request body who has a proper invitation."""
        try:
            request_json = request.get_json()
            invitation_token = request.headers.get('invitation_token', None)
            invitation = InvitationService.validate_token(invitation_token).as_dict()

            valid_format, errors = schema_utils.validate(request_json, 'anonymous_user')
            if not valid_format:
                return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST

            membership_details = {
                'email': invitation['recipientEmail'],
                'membershipType': invitation['membership'][0]['membershipType'],
                'update_password_on_login': False
            }
            membership_details.update(request_json)
            user = UserService.create_user_and_add_membership([membership_details],
                                                              invitation['membership'][0]['org']['id'],
                                                              single_mode=True)
            user_dict = user['users'][0]
            if user_dict['http_status'] != http_status.HTTP_201_CREATED:
                response, status = {'code': user_dict['http_status'], 'message': user_dict['error']}, user_dict[
                    'http_status']
            else:
                InvitationService.accept_invitation(invitation['id'], None, None, False)
                response, status = user, http_status.HTTP_201_CREATED

        except BusinessException as exception:
            response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
        return response, status
コード例 #4
0
ファイル: invitation.py プロジェクト: shabeeb-aot/sbc-auth
 def get(invitation_token):
     """Check whether the passed token is valid."""
     try:
         InvitationService.validate_token(invitation_token)
         response, status = {}, http_status.HTTP_200_OK
     except BusinessException as exception:
         response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
     return response, status
コード例 #5
0
 def delete(invitation_id):
     """Delete the specified invitation."""
     try:
         InvitationService.delete_invitation(invitation_id)
         response, status = {}, http_status.HTTP_200_OK
     except BusinessException as exception:
         response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
     return response, status
コード例 #6
0
def test_accept_invitation_exceptions(session, auth_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Accept the invitation and add membership from the invitation to the org."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        with patch.object(auth, 'check_auth', return_value=True):
            with patch.object(InvitationService, 'notify_admin', return_value=None):
                user = factory_user_model(TestUserInfo.user_test)
                org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
                org_dictionary = org.as_dict()
                invitation_info = factory_invitation(org_dictionary['id'])

                user_invitee = factory_user_model(TestUserInfo.user1)

                with pytest.raises(BusinessException) as exception:
                    InvitationService.accept_invitation(None, User(user_invitee), '')

                assert exception.value.code == Error.DATA_NOT_FOUND.name

                new_invitation = InvitationService.create_invitation(invitation_info, User(user_invitee), {}, '')
                new_invitation_dict = new_invitation.as_dict()
                InvitationService.accept_invitation(new_invitation_dict['id'], User(user_invitee), '')

                with pytest.raises(BusinessException) as exception:
                    InvitationService.accept_invitation(new_invitation_dict['id'], User(user_invitee), '')

                assert exception.value.code == Error.ACTIONED_INVITATION.name

                with pytest.raises(BusinessException) as exception:
                    expired_invitation: InvitationModel = InvitationModel \
                        .find_invitation_by_id(new_invitation_dict['id'])
                    expired_invitation.invitation_status = InvitationStatusModel.get_status_by_code('EXPIRED')
                    expired_invitation.save()
                    InvitationService.accept_invitation(expired_invitation.id, User(user_invitee), '')

                assert exception.value.code == Error.EXPIRED_INVITATION.name
コード例 #7
0
def test_find_invitation_by_id(session, auth_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Find an existing invitation with the provided id."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        user = factory_user_model(TestUserInfo.user_test)
        org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
        org_dictionary = org.as_dict()
        invitation_info = factory_invitation(org_dictionary['id'])
        new_invitation = InvitationService.create_invitation(invitation_info, User(user), {}, '').as_dict()
        invitation = InvitationService.find_invitation_by_id(new_invitation['id']).as_dict()
        assert invitation
        assert invitation['recipient_email'] == invitation_info['recipientEmail']
コード例 #8
0
def test_delete_invitation(session, auth_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Delete the specified invitation."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        user = factory_user_model(TestUserInfo.user_test)
        org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
        org_dictionary = org.as_dict()
        invitation_info = factory_invitation(org_dictionary['id'])
        new_invitation = InvitationService.create_invitation(invitation_info, User(user), {}, '').as_dict()
        InvitationService.delete_invitation(new_invitation['id'])
        invitation = InvitationService.find_invitation_by_id(new_invitation['id'])
        assert invitation is None
コード例 #9
0
def test_validate_token_valid(session, auth_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Validate the invitation token."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        user = factory_user_model(TestUserInfo.user_test)
        org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
        org_dictionary = org.as_dict()
        invitation_info = factory_invitation(org_dictionary['id'])
        new_invitation = InvitationService.create_invitation(invitation_info, User(user), {}, '').as_dict()
        confirmation_token = InvitationService.generate_confirmation_token(new_invitation['id'])
        invitation_id = InvitationService.validate_token(confirmation_token).as_dict().get('id')
        assert invitation_id == new_invitation['id']
コード例 #10
0
def test_accept_gov_account_invitation(client, jwt, session):  # pylint:disable=unused-argument
    """Assert that an invitation can be accepted."""
    headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.gov_account_holder_user)
    client.post('/api/v1/users', headers=headers, content_type='application/json')
    rv = client.post('/api/v1/orgs', data=json.dumps(TestOrgInfo.org1),
                     headers=headers, content_type='application/json')
    dictionary = json.loads(rv.data)
    org_id = dictionary['id']
    rv = client.post('/api/v1/invitations', data=json.dumps(factory_invitation(org_id=org_id)),
                     headers=headers, content_type='application/json')
    invitation_dictionary = json.loads(rv.data)
    invitation_id = invitation_dictionary['id']
    invitation_id_token = InvitationService.generate_confirmation_token(invitation_id)

    request = KeycloakScenario.create_user_request()
    KEYCLOAK_SERVICE.add_user(request, return_if_exists=True)
    user = KEYCLOAK_SERVICE.get_user_by_username(request.user_name)
    user_id = user.id
    headers_invitee = factory_auth_header(jwt=jwt, claims=TestJwtClaims.get_test_user(user_id, source='IDIR'))
    client.post('/api/v1/users', headers=headers_invitee, content_type='application/json')
    rv = client.put('/api/v1/invitations/tokens/{}'.format(invitation_id_token), headers=headers_invitee,
                    content_type='application/json')
    assert rv.status_code == http_status.HTTP_200_OK

    rv = client.get('/api/v1/orgs/{}/members?status=PENDING_APPROVAL'.format(org_id),
                    headers=headers,
                    content_type='application/json')
    dictionary = json.loads(rv.data)
    assert len(dictionary['members']) == 1
    # Assert that the user got added to the keycloak groups
    user_groups = KEYCLOAK_SERVICE.get_user_groups(user_id=user_id)
    groups = []
    for group in user_groups:
        groups.append(group.get('name'))
    assert GROUP_GOV_ACCOUNT_USERS in groups
コード例 #11
0
def test_validate_token(client, jwt, session, keycloak_mock):  # pylint:disable=unused-argument
    """Assert that a token is valid."""
    headers = factory_auth_header(jwt=jwt,
                                  claims=TestJwtClaims.public_user_role)
    client.post('/api/v1/users',
                headers=headers,
                content_type='application/json')
    rv = client.post('/api/v1/orgs',
                     data=json.dumps(TestOrgInfo.org1),
                     headers=headers,
                     content_type='application/json')
    dictionary = json.loads(rv.data)
    org_id = dictionary['id']
    rv = client.post('/api/v1/invitations',
                     data=json.dumps(factory_invitation(org_id=org_id)),
                     headers=headers,
                     content_type='application/json')
    invitation_dictionary = json.loads(rv.data)
    invitation_id = invitation_dictionary['id']
    invitation_id_token = InvitationService.generate_confirmation_token(
        invitation_id)
    rv = client.get(
        '/api/v1/invitations/tokens/{}'.format(invitation_id_token),
        headers=headers,
        content_type='application/json')
    assert rv.status_code == http_status.HTTP_200_OK
コード例 #12
0
def test_create_invitation(session, auth_mock, keycloak_mock, monkeypatch):  # pylint:disable=unused-argument
    """Assert that an Invitation can be created."""
    with patch.object(InvitationService, 'send_invitation',
                      return_value=None) as mock_notify:
        user = factory_user_model(TestUserInfo.user_test)
        patch_token_info({'sub': user.keycloak_guid}, monkeypatch)
        org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
        org_dictionary = org.as_dict()
        invitation_info = factory_invitation(org_dictionary['id'])

        with patch.object(ActivityLogPublisher,
                          'publish_activity',
                          return_value=None) as mock_alp:
            invitation = InvitationService.create_invitation(
                invitation_info, User(user), '')
            mock_alp.assert_called_with(
                Activity(action=ActivityAction.INVITE_TEAM_MEMBER.value,
                         org_id=ANY,
                         name=invitation_info['recipientEmail'],
                         id=ANY,
                         value='USER'))

        invitation_dictionary = invitation.as_dict()
        assert invitation_dictionary['recipient_email'] == invitation_info[
            'recipientEmail']
        assert invitation_dictionary['id']
        mock_notify.assert_called()
コード例 #13
0
def test_send_invitation_exception(session, notify_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Send an existing invitation with exception."""
    user = factory_user_model(TestUserInfo.user_test)
    user_dictionary = User(user).as_dict()
    org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
    org_dictionary = org.as_dict()

    invitation_info = factory_invitation(org_dictionary['id'])

    invitation = InvitationModel.create_from_dict(invitation_info, user.id, 'STANDARD')

    with patch.object(notification, 'send_email', return_value=False):
        with pytest.raises(BusinessException) as exception:
            InvitationService.send_invitation(invitation, org_dictionary['name'], user_dictionary, '', '')

    assert exception.value.code == Error.FAILED_INVITATION.name
コード例 #14
0
def test_get_invitations_by_org_id(session, auth_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Find an existing invitation with the provided org id."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        user_with_token = TestUserInfo.user_test
        user_with_token['keycloak_guid'] = TestJwtClaims.public_user_role['sub']
        user = factory_user_model(user_with_token)
        org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
        org_dictionary = org.as_dict()
        org_id = org_dictionary['id']
        invitation_info = factory_invitation(org_dictionary['id'])
        InvitationService.create_invitation(invitation_info, User(user), {}, '').as_dict()
        invitations: list = InvitationService.get_invitations_for_org(org_id,
                                                                      status='PENDING',
                                                                      token_info=TestJwtClaims.public_user_role)
        assert invitations
        assert len(invitations) == 1
コード例 #15
0
def test_accept_invitation(client, jwt, session):  # pylint:disable=unused-argument
    """Assert that an invitation can be accepted."""
    headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.edit_role)
    client.post('/api/v1/users',
                headers=headers,
                content_type='application/json')
    rv = client.post('/api/v1/orgs',
                     data=json.dumps(TestOrgInfo.org1),
                     headers=headers,
                     content_type='application/json')
    dictionary = json.loads(rv.data)
    org_id = dictionary['id']
    rv = client.post('/api/v1/invitations',
                     data=json.dumps(factory_invitation(org_id=org_id)),
                     headers=headers,
                     content_type='application/json')
    invitation_dictionary = json.loads(rv.data)
    invitation_id = invitation_dictionary['id']
    invitation_id_token = InvitationService.generate_confirmation_token(
        invitation_id)
    rv = client.put(
        '/api/v1/invitations/tokens/{}'.format(invitation_id_token),
        headers=headers,
        content_type='application/json')
    assert rv.status_code == http_status.HTTP_200_OK
    rv = client.get(
        '/api/v1/orgs/{}/members?status=PENDING_APPROVAL'.format(org_id),
        headers=headers,
        content_type='application/json')
    dictionary = json.loads(rv.data)
    assert len(dictionary['members']) == 1
コード例 #16
0
def test_get_invitations(session, auth_mock):  # pylint:disable=unused-argument
    """Assert that invitations for an org can be retrieved."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        user_with_token = TestUserInfo.user_test
        user_with_token['keycloak_guid'] = TestJwtClaims.edit_role['sub']
        user = factory_user_model(user_info=user_with_token)
        org = OrgService.create_org(TestOrgInfo.org1, user.id)
        org_dictionary = org.as_dict()

        invitation_info = factory_invitation(org_dictionary['id'])

        invitation = InvitationService.create_invitation(invitation_info, UserService(user), {}, '')

        response = InvitationService.get_invitations_for_org(org_dictionary['id'], 'PENDING', TestJwtClaims.edit_role)
        assert response
        assert len(response) == 1
        assert response[0].recipient_email == invitation.as_dict()['recipientEmail']
コード例 #17
0
    def put(invitation_token):
        """Check whether the passed token is valid and add user, role and org from invitation to membership."""
        origin = request.environ.get('HTTP_ORIGIN', 'localhost')

        try:
            user = UserService.find_by_jwt_token()
            if user is None:
                response, status = {'message': 'Not authorized to perform this action'}, \
                                   http_status.HTTP_401_UNAUTHORIZED
            else:
                invitation_id = InvitationService.validate_token(invitation_token).as_dict().get('id')
                response, status = InvitationService.accept_invitation(invitation_id, user, origin).as_dict(), \
                                   http_status.HTTP_200_OK  # noqa:E127

        except BusinessException as exception:
            response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
        return response, status
コード例 #18
0
def test_accept_public_users_invitation(
        client,
        jwt,
        session,
        org_info,
        role,  # pylint:disable=unused-argument
        claims,
        source,
        exp_status):
    """Assert that an invitation can be accepted."""
    headers = factory_auth_header(jwt=jwt, claims=claims)
    client.post('/api/v1/users',
                headers=headers,
                content_type='application/json')
    rv = client.post('/api/v1/orgs',
                     data=json.dumps(org_info),
                     headers=headers,
                     content_type='application/json')
    dictionary = json.loads(rv.data)
    org_id = dictionary['id']
    rv = client.post('/api/v1/invitations',
                     data=json.dumps(
                         factory_invitation(org_id=org_id,
                                            membership_type=role)),
                     headers=headers,
                     content_type='application/json')
    invitation_dictionary = json.loads(rv.data)
    invitation_id = invitation_dictionary['id']
    invitation_id_token = InvitationService.generate_confirmation_token(
        invitation_id)

    request = KeycloakScenario.create_user_request()
    KEYCLOAK_SERVICE.add_user(request, return_if_exists=True)
    user = KEYCLOAK_SERVICE.get_user_by_username(request.user_name)
    user_id = user.id
    headers_invitee = factory_auth_header(jwt=jwt,
                                          claims=TestJwtClaims.get_test_user(
                                              user_id, source=source))
    client.post('/api/v1/users',
                headers=headers_invitee,
                content_type='application/json')
    rv = client.put(
        '/api/v1/invitations/tokens/{}'.format(invitation_id_token),
        headers=headers_invitee,
        content_type='application/json')
    assert rv.status_code == http_status.HTTP_200_OK

    rv = client.get(f'/api/v1/orgs/{org_id}/members?status={exp_status.name}',
                    headers=headers,
                    content_type='application/json')
    dictionary = json.loads(rv.data)
    assert len(dictionary['members']) == 1
    # Assert that the user got added to the keycloak groups
    user_groups = KEYCLOAK_SERVICE.get_user_groups(user_id=user_id)
    groups = []
    for group in user_groups:
        groups.append(group.get('name'))
    assert GROUP_PUBLIC_USERS in groups
コード例 #19
0
ファイル: test_invitation.py プロジェクト: jeznorth/sbc-auth
def test_get_invitations_by_org_id(session, auth_mock):  # pylint:disable=unused-argument
    """Find an existing invitation with the provided org id."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        user = factory_user_model(TestUserInfo.user_test)
        org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
        org_dictionary = org.as_dict()
        org_id = org_dictionary['id']
        invitation_info = factory_invitation(org_dictionary['id'])
        InvitationService.create_invitation(invitation_info, User(user), {},
                                            '').as_dict()
        invitations: list = InvitationService.get_invitations_by_org_id(
            org_id, 'ALL')
        assert invitations
        assert len(invitations) == 1

        invitations: list = InvitationService.get_invitations_by_org_id(
            org_id, 'PENDING')
        assert len(invitations) == 1
コード例 #20
0
 def get(invitation_id):
     """Get the invitation specified by the provided id."""
     invitation = InvitationService.find_invitation_by_id(invitation_id)
     if invitation is None:
         response, status = {'message': 'The requested invitation could not be found.'}, \
                            http_status.HTTP_404_NOT_FOUND
     else:
         response, status = invitation.as_dict(), http_status.HTTP_200_OK
     return response, status
コード例 #21
0
def test_accept_invitation_for_govm(session, auth_mock, keycloak_mock,
                                    monkeypatch):  # pylint:disable=unused-argument
    """Accept the invitation and add membership from the invitation to the org."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        with patch.object(auth, 'check_auth', return_value=True):
            with patch.object(InvitationService,
                              'notify_admin',
                              return_value=None):
                user_with_token = TestUserInfo.user_staff_admin
                user_with_token[
                    'keycloak_guid'] = TestJwtClaims.public_user_role['sub']
                user = factory_user_model(user_with_token)

                patch_token_info(TestJwtClaims.staff_admin_role, monkeypatch)

                org = OrgService.create_org(TestOrgInfo.org_govm,
                                            user_id=user.id)
                org_dictionary = org.as_dict()
                invitation_info = factory_invitation(org_dictionary['id'])
                user_with_token_invitee = TestUserInfo.user1
                user_with_token_invitee[
                    'keycloak_guid'] = TestJwtClaims.edit_role_2['sub']
                user_invitee = factory_user_model(user_with_token_invitee)
                new_invitation = InvitationService.create_invitation(
                    invitation_info, User(user_invitee), '')
                new_invitation_dict = new_invitation.as_dict()
                with patch.object(ActivityLogPublisher,
                                  'publish_activity',
                                  return_value=None) as mock_alp:
                    InvitationService.accept_invitation(
                        new_invitation_dict['id'], User(user_invitee), '')
                    mock_alp.assert_called_with(
                        Activity(
                            action=ActivityAction.APPROVE_TEAM_MEMBER.value,
                            org_id=ANY,
                            name=ANY,
                            id=ANY,
                            value=ANY))

                members = MembershipService.get_members_for_org(
                    org_dictionary['id'], 'ACTIVE')
                assert members
                assert len(members) == 1, 'user gets active membership'
コード例 #22
0
def test_update_invitation(session, auth_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Update the specified invitation with new data."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        user = factory_user_model(TestUserInfo.user_test)
        org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
        org_dictionary = org.as_dict()
        invitation_info = factory_invitation(org_dictionary['id'])
        new_invitation = InvitationService.create_invitation(invitation_info, User(user), {}, '')
        updated_invitation = new_invitation.update_invitation(User(user), {}, '').as_dict()
        assert updated_invitation['status'] == 'PENDING'
コード例 #23
0
def test_as_dict(session, auth_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Assert that the Invitation is exported correctly as a dictionary."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        user = factory_user_model()
        org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
        org_dictionary = org.as_dict()
        invitation_info = factory_invitation(org_dictionary['id'])
        invitation = InvitationService.create_invitation(invitation_info, User(user), {}, '')
        invitation_dictionary = invitation.as_dict()
        assert invitation_dictionary['recipient_email'] == invitation_info['recipientEmail']
コード例 #24
0
ファイル: test_invitation.py プロジェクト: jeznorth/sbc-auth
def test_accept_invitation(session, auth_mock):  # pylint:disable=unused-argument
    """Accept the invitation and add membership from the invitation to the org."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        with patch.object(auth, 'check_auth', return_value=True):
            with patch.object(InvitationService,
                              'notify_admin',
                              return_value=None):
                user = factory_user_model(TestUserInfo.user_test)
                org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
                org_dictionary = org.as_dict()
                invitation_info = factory_invitation(org_dictionary['id'])
                new_invitation = InvitationService.create_invitation(
                    invitation_info, User(user), {}, '')
                new_invitation_dict = new_invitation.as_dict()
                InvitationService.accept_invitation(new_invitation_dict['id'],
                                                    User(user), '')
                org_dict = OrgService.find_by_org_id(
                    org_dictionary['id'], allowed_roles={'basic'}).as_dict()
                assert len(
                    org_dict['members']
                ) == 2  # Member count will be 2 only if the invite accept is successful.
コード例 #25
0
def test_create_invitation(session, auth_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Assert that an Invitation can be created."""
    with patch.object(InvitationService, 'send_invitation', return_value=None) as mock_notify:
        user = factory_user_model(TestUserInfo.user_test)
        org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
        org_dictionary = org.as_dict()
        invitation_info = factory_invitation(org_dictionary['id'])
        invitation = InvitationService.create_invitation(invitation_info, User(user), {}, '')
        invitation_dictionary = invitation.as_dict()
        assert invitation_dictionary['recipient_email'] == invitation_info['recipientEmail']
        assert invitation_dictionary['id']
        mock_notify.assert_called()
コード例 #26
0
    def get(org_id):
        """Retrieve the set of invitations for the given org."""
        try:

            invitation_status = request.args.get('status').upper() if request.args.get('status') else None
            invitations = InvitationService.get_invitations_for_org(org_id=org_id,
                                                                    status=invitation_status)

            response, status = {'invitations': InvitationSchema().dump(invitations, many=True)}, http_status.HTTP_200_OK
        except BusinessException as exception:
            response, status = {'code': exception.code, 'message': exception.message}, exception.status_code

        return response, status
コード例 #27
0
def test_delete_org_failure_members(client, jwt, session, auth_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Assert that a member of an org can have their role updated."""
    # Set up: create/login user, create org
    headers_invitee = factory_auth_header(jwt=jwt, claims=TestJwtClaims.public_user_role)
    rv = client.post('/api/v1/users', headers=headers_invitee, content_type='application/json')
    rv = client.post('/api/v1/orgs', data=json.dumps(TestOrgInfo.org1),
                     headers=headers_invitee, content_type='application/json')
    dictionary = json.loads(rv.data)
    org_id = dictionary['id']

    # Invite a user to the org
    rv = client.post('/api/v1/invitations', data=json.dumps(factory_invitation(org_id, '*****@*****.**')),
                     headers=headers_invitee, content_type='application/json')
    dictionary = json.loads(rv.data)
    invitation_id = dictionary['id']
    invitation_id_token = InvitationService.generate_confirmation_token(invitation_id)

    # Create/login as invited user
    headers_invited = factory_auth_header(jwt=jwt, claims=TestJwtClaims.edit_role_2)
    rv = client.post('/api/v1/users', headers=headers_invited, content_type='application/json')

    # Accept invite as invited user
    rv = client.put('/api/v1/invitations/tokens/{}'.format(invitation_id_token),
                    headers=headers_invited, content_type='application/json')

    assert rv.status_code == http_status.HTTP_200_OK
    dictionary = json.loads(rv.data)
    assert dictionary['status'] == 'ACCEPTED'

    # Get pending members for the org as invitee and assert length of 1
    rv = client.get('/api/v1/orgs/{}/members?status=PENDING_APPROVAL'.format(org_id), headers=headers_invitee)
    assert rv.status_code == http_status.HTTP_200_OK
    dictionary = json.loads(rv.data)
    assert dictionary['members']
    assert len(dictionary['members']) == 1

    # Find the pending member
    new_member = dictionary['members'][0]
    assert new_member['membershipTypeCode'] == 'MEMBER'
    member_id = new_member['id']

    # Update the new member
    rv = client.patch('/api/v1/orgs/{}/members/{}'.format(org_id, member_id), headers=headers_invitee,
                      data=json.dumps({'role': 'ADMIN'}), content_type='application/json')
    assert rv.status_code == http_status.HTTP_200_OK
    dictionary = json.loads(rv.data)
    assert dictionary['membershipTypeCode'] == 'ADMIN'

    headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.passcode)
    rv = client.delete('/api/v1/orgs/{}'.format(org_id), headers=headers, content_type='application/json')
    assert rv.status_code == http_status.HTTP_406_NOT_ACCEPTABLE
コード例 #28
0
def test_get_invitations(session, auth_mock):  # pylint:disable=unused-argument
    """Assert that invitations for an org can be retrieved."""
    with patch.object(InvitationService, 'send_invitation', return_value=None):
        user = factory_user_model()
        org = OrgService.create_org(TestOrgInfo.org1, user.id)

        invitation_info = factory_invitation(org.as_dict()['id'])

        invitation = InvitationService.create_invitation(invitation_info, UserService(user), {}, '')

        response = org.get_invitations()
        assert response
        assert len(response['invitations']) == 1
        assert response['invitations'][0]['recipientEmail'] == invitation.as_dict()['recipientEmail']
コード例 #29
0
 def patch(invitation_id):
     """Update the invitation specified by the provided id as retried."""
     origin = request.environ.get('HTTP_ORIGIN', 'localhost')
     try:
         invitation = InvitationService.find_invitation_by_id(invitation_id)
         if invitation is None:
             response, status = {'message': 'The requested invitation could not be found.'}, \
                                http_status.HTTP_404_NOT_FOUND
         else:
             user = UserService.find_by_jwt_token()
             response, status = invitation.update_invitation(user, origin).as_dict(), http_status.HTTP_200_OK
     except BusinessException as exception:
         response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
     return response, status
コード例 #30
0
 def post():
     """Send a new invitation using the details in request and saves the invitation."""
     origin = request.environ.get('HTTP_ORIGIN', 'localhost')
     request_json = request.get_json()
     valid_format, errors = schema_utils.validate(request_json, 'invitation')
     if not valid_format:
         return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST
     try:
         user = UserService.find_by_jwt_token()
         response, status = InvitationService.create_invitation(request_json, user, origin).as_dict(), \
             http_status.HTTP_201_CREATED
     except BusinessException as exception:
         response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
     return response, status