예제 #1
0
def test_pay_request_is_correct_with_branch_name(session, keycloak_mock,
                                                 monkeypatch):  # pylint:disable=unused-argument
    """Assert that while org creation , pay-api gets called with proper data for basic accounts."""
    user = factory_user_model()
    with patch.object(RestService, 'post') as mock_post:
        patch_token_info({'sub': user.keycloak_guid}, monkeypatch)
        org = OrgService.create_org(TestOrgInfo.org_branch_name,
                                    user_id=user.id)
        assert org
        dictionary = org.as_dict()
        assert dictionary['name'] == TestOrgInfo.org_branch_name['name']
        mock_post.assert_called()
        actual_data = mock_post.call_args.kwargs.get('data')
        expected_data = {
            'accountId': dictionary.get('id'),
            'accountName':
            f"{dictionary.get('name')}-{TestOrgInfo.org_branch_name['branchName']}",
            'paymentInfo': {
                'methodOfPayment':
                OrgService._get_default_payment_method_for_creditcard(),
                'billable':
                True
            }
        }
        assert expected_data == actual_data
예제 #2
0
def test_fetch_activity_log(client, jwt, session):  # pylint:disable=unused-argument
    """Assert that the activity log can be fetched."""
    user = factory_user_model()
    org = factory_org_model()

    factory_activity_log_model(actor=user.id,
                               action=ActivityAction.APPROVE_TEAM_MEMBER.value,
                               item_name='Superb',
                               item_value='')
    factory_activity_log_model(actor=user.id,
                               action=ActivityAction.CREATE_AFFILIATION.value,
                               org_id=org.id,
                               item_name='Great Business',
                               item_value='')
    factory_activity_log_model(actor=user.id,
                               action=ActivityAction.REMOVE_AFFILIATION.value,
                               org_id=org.id,
                               item_name='Must sleep',
                               item_value='Getting Late')

    headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.staff_role)
    rv = client.get(f'/api/v1/orgs/{org.id}/activity-logs',
                    headers=headers,
                    content_type='application/json')
    activity_logs = rv.json
    assert len(activity_logs.get('activityLogs')) == 2
    assert schema_utils.validate(activity_logs, 'paged_response')[0]
    assert rv.status_code == http_status.HTTP_200_OK

    rv = client.get(
        f'/api/v1/orgs/{org.id}/activity-logs?action={ActivityAction.REMOVE_AFFILIATION.value}',
        headers=headers,
        content_type='application/json')
    assert len(rv.json.get('activityLogs')) == 1
예제 #3
0
def test_create_user_and_add_membership_admin_bulk_mode_multiple(
        session, auth_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Assert that an admin can add a group of members."""
    org = factory_org_model(org_info=TestOrgInfo.org_anonymous)
    user = factory_user_model()
    factory_membership_model(user.id, org.id)
    claims = TestJwtClaims.get_test_real_user(user.keycloak_guid)
    membership = [
        TestAnonymousMembership.generate_random_user(MEMBER),
        TestAnonymousMembership.generate_random_user(ADMIN)
    ]
    users = UserService.create_user_and_add_membership(membership,
                                                       org.id,
                                                       token_info=claims)

    assert len(users['users']) == 2
    assert users['users'][0][
        'username'] == IdpHint.BCROS.value + '/' + membership[0]['username']
    assert users['users'][0]['type'] == 'ANONYMOUS'
    assert users['users'][1][
        'username'] == IdpHint.BCROS.value + '/' + membership[1]['username']
    assert users['users'][1]['type'] == 'ANONYMOUS'

    members = MembershipModel.find_members_by_org_id(org.id)

    # staff didnt create members..so count is count of owner+other 2 members
    assert len(members) == 3
예제 #4
0
def test_add_user_adds_to_account_holders_group(client, jwt, session):  # pylint:disable=unused-argument
    """Assert that a user gets added to account_holders group if the user has any active account."""
    # Create a user in keycloak
    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

    # Create user, org and membserhip in DB
    user = factory_user_model(TestUserInfo.get_user_with_kc_guid(user_id))
    org = factory_org_model(org_status_info=None)
    factory_membership_model(user.id, org.id)

    # Login as that user
    headers = factory_auth_header(jwt=jwt,
                                  claims=TestJwtClaims.get_test_user(
                                      user_id, source='BCSC'))
    client.post('/api/v1/users',
                headers=headers,
                content_type='application/json')

    user_groups = KEYCLOAK_SERVICE.get_user_groups(user_id=user_id)
    groups = []
    for group in user_groups:
        groups.append(group.get('name'))
    assert GROUP_ACCOUNT_HOLDERS in groups
예제 #5
0
def test_delete_user_where_org_has_affiliations(session, auth_mock,
                                                keycloak_mock):  # pylint:disable=unused-argument
    """Assert that a user can be deleted."""
    user_model = factory_user_model(user_info=TestUserInfo.user_test)
    contact = factory_contact_model()
    contact_link = ContactLinkModel()
    contact_link.contact = contact
    contact_link.user = user_model
    contact_link = contact_link.flush()
    contact_link.commit()

    org = OrgService.create_org(TestOrgInfo.org1,
                                user_id=user_model.id).as_dict()
    org_id = org['id']

    entity = factory_entity_model(entity_info=TestEntityInfo.entity_lear_mock)

    affiliation = AffiliationModel(org_id=org_id, entity_id=entity.id)
    affiliation.save()
    with pytest.raises(BusinessException) as exception:
        UserService.delete_user(TestJwtClaims.user_test)
        assert exception.code == Error.DELETE_FAILED_ONLY_OWNER

    updated_user = UserModel.find_by_jwt_token(TestJwtClaims.user_test)
    contacts = UserService.get_contacts(TestJwtClaims.user_test)
    assert len(contacts) == 1

    user_orgs = MembershipModel.find_orgs_for_user(updated_user.id)
    for org in user_orgs:
        assert org.status_code == 'ACTIVE'
예제 #6
0
def test_update_product_subscription(session, keycloak_mock, monkeypatch):
    """Assert that updating product subscription works."""
    user = factory_user_model(TestUserInfo.user_test)
    patch_token_info({'sub': user.keycloak_guid}, monkeypatch)
    org = Org.create_org(TestOrgInfo.org1, user_id=user.id)
    product_subscription = ProductSubscription(
        org_id=org._model.id,
        product_code='PPR',
        status_code=ProductSubscriptionStatus.ACTIVE.value).flush()

    class MockContact(object):
        email = ''

    class MockPerson(object):
        def __init__(self, contact: MockContact):
            self.contact = contact

    with patch.object(ActivityLogPublisher,
                      'publish_activity',
                      return_value=None) as mock_alp:
        with patch.object(ContactLinkModel,
                          'find_by_user_id',
                          return_value=MockPerson(contact=MockContact())):
            ProductService.update_product_subscription(product_subscription.id,
                                                       True, org._model.id)
            mock_alp.assert_called_with(
                Activity(action=ActivityAction.ADD_PRODUCT_AND_SERVICE.value,
                         org_id=ANY,
                         value=ANY,
                         id=ANY,
                         name='Personal Property Registry'))
예제 #7
0
def test_user_authorizations_returns_200(client, jwt, session):  # pylint:disable=unused-argument
    """Assert authorizations for users returns 200."""
    user = factory_user_model()
    org = factory_org_model()
    factory_membership_model(user.id, org.id)
    entity = factory_entity_model()
    factory_affiliation_model(entity.id, org.id)

    claims = copy.deepcopy(TestJwtClaims.public_user_role.value)
    claims['sub'] = str(user.keycloak_guid)

    headers = factory_auth_header(jwt=jwt, claims=claims)
    rv = client.get('/api/v1/users/authorizations',
                    headers=headers,
                    content_type='application/json')

    assert rv.status_code == http_status.HTTP_200_OK
    assert rv.json.get('authorizations')[0].get('orgMembership') == 'ADMIN'

    # Test with invalid user
    claims['sub'] = str(uuid.uuid4())
    headers = factory_auth_header(jwt=jwt, claims=claims)
    rv = client.get('/api/v1/users/authorizations',
                    headers=headers,
                    content_type='application/json')

    assert rv.status_code == http_status.HTTP_200_OK
    assert len(rv.json.get('authorizations')) == 0
예제 #8
0
def test_create_premium_org_assert_pay_request_is_correct(
        session, keycloak_mock):  # pylint:disable=unused-argument
    """Assert that while org creation , pay-api gets called with proper data for basic accounts."""
    bcol_response = Mock(spec=Response)
    bcol_response.json.return_value = {
        'userId': 'PB25020',
        'accountNumber': '180670',
        'orgName': 'BC ONLINE TECHNICAL TEAM DEVL'
    }
    bcol_response.status_code = 200

    pay_api_response = Mock(spec=Response)
    pay_api_response.status_code = 201

    with patch.object(RestService,
                      'post',
                      side_effect=[bcol_response,
                                   pay_api_response]) as mock_post:
        user = factory_user_model()
        org = OrgService.create_org(TestOrgInfo.bcol_linked(), user_id=user.id)
        assert org
        dictionary = org.as_dict()
        mock_post.assert_called()
        actual_data = mock_post.call_args_list[1].kwargs.get('data')
        expected_data = {
            'accountId': dictionary.get('id'),
            'accountName': TestOrgInfo.bcol_linked().get('name'),
            'paymentInfo': {
                'methodOfPayment': PaymentType.BCOL.value,
                'billable': True
            },
            'bcolAccountNumber': dictionary.get('bcol_account_id'),
            'bcolUserId': dictionary.get('bcol_user_id')
        }
        assert actual_data == expected_data
예제 #9
0
def test_authorizations_with_multiple_accounts_returns_200(client, jwt, session):  # pylint:disable=unused-argument
    """Assert authorizations for product returns 200."""
    product_code = 'PPR'
    user = factory_user_model()
    org = factory_org_model()
    factory_membership_model(user.id, org.id)
    factory_product_model(org.id)

    org2 = factory_org_model(org_info=TestOrgInfo.org2, org_type_info=TestOrgTypeInfo.implicit, org_status_info=None,
                             payment_type_info=None)
    factory_membership_model(user.id, org.id)

    claims = copy.deepcopy(TestJwtClaims.public_user_role.value)
    claims['sub'] = str(user.keycloak_guid)

    headers = factory_auth_header(jwt=jwt, claims=claims)
    rv = client.get(f'/api/v1/accounts/{org2.id}/products/{product_code}/authorizations',
                    headers=headers, content_type='application/json')

    assert rv.status_code == http_status.HTTP_200_OK
    assert len(rv.json.get('roles')) == 0

    headers = factory_auth_header(jwt=jwt, claims=claims)
    rv = client.get(f'/api/v1/accounts/{org.id}/products/{product_code}/authorizations',
                    headers=headers, content_type='application/json')

    assert rv.status_code == http_status.HTTP_200_OK
    assert rv.json.get('roles') == ['search']
예제 #10
0
def test_fetch_tasks(session):  # pylint:disable=unused-argument
    """Assert that we can fetch all tasks."""
    user = factory_user_model()
    task_type = TaskTypePrefix.NEW_ACCOUNT_STAFF_REVIEW.value
    task = TaskModel(
        name='TEST',
        date_submitted=datetime.now(),
        relationship_type=TaskRelationshipType.ORG.value,
        relationship_id=10,
        type=task_type,
        due_date=datetime.now(),
        status=TaskStatus.OPEN.value,
        related_to=user.id,
        relationship_status=TaskRelationshipStatus.PENDING_STAFF_REVIEW.value)
    session.add(task)
    session.commit()
    found_tasks, count = TaskModel.fetch_tasks(
        task_relationship_status=TaskRelationshipStatus.PENDING_STAFF_REVIEW.
        value,
        task_type=task_type,
        task_status=[TaskStatus.OPEN.value],
        page=1,
        limit=10)
    assert found_tasks
    assert count == 1

    for found_staff_task in found_tasks:
        assert found_staff_task.name == task.name
예제 #11
0
def test_authorizations_for_expanded_result(client, jwt, session):  # pylint:disable=unused-argument
    """Assert authorizations for affiliated users returns 200."""
    user = factory_user_model()
    org = factory_org_model()
    factory_membership_model(user.id, org.id)
    entity = factory_entity_model()
    factory_affiliation_model(entity.id, org.id)

    claims = copy.deepcopy(TestJwtClaims.edit_user_role.value)
    claims['sub'] = str(user.keycloak_guid)

    headers = factory_auth_header(jwt=jwt, claims=claims)
    rv = client.get(
        f'/api/v1/entities/{entity.business_identifier}/authorizations',
        headers=headers,
        content_type='application/json')

    assert rv.status_code == http_status.HTTP_200_OK
    assert rv.json.get('orgMembership') == 'ADMIN'
    assert rv.json.get('account', None) is None

    rv = client.get(
        f'/api/v1/entities/{entity.business_identifier}/authorizations?expanded=true',
        headers=headers,
        content_type='application/json')
    assert rv.status_code == http_status.HTTP_200_OK
    assert rv.json.get('account') is not None
    assert rv.json.get('account').get('name') == org.name
    assert rv.json.get('business').get('name') == entity.name
    assert rv.json.get('business').get('folioNumber') == entity.folio_number
예제 #12
0
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_with_token = TestUserInfo.user_test
                user_with_token['keycloak_guid'] = TestJwtClaims.edit_role[
                    'sub']
                user = factory_user_model(user_with_token)
                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), '')
                members = MembershipService.get_members_for_org(
                    org_dictionary['id'],
                    'PENDING_APPROVAL',
                    token_info=TestJwtClaims.edit_role)
                assert members
                assert len(members) == 1
예제 #13
0
def test_as_dict(session):  # pylint: disable=unused-argument
    """Assert that a user is rendered correctly as a dictionary."""
    user_model = factory_user_model()
    user = UserService(user_model)

    dictionary = user.as_dict()
    assert dictionary['username'] == TestUserInfo.user1['username']
예제 #14
0
def test_create_user_and_add_membership_admin_bulk_mode_multiple(
        session, auth_mock, keycloak_mock, monkeypatch):  # pylint:disable=unused-argument
    """Assert that an admin can add a group of members."""
    org = factory_org_model(org_info=TestOrgInfo.org_anonymous)
    user = factory_user_model()
    factory_membership_model(user.id, org.id)
    factory_product_model(org.id, product_code=ProductCode.DIR_SEARCH.value)
    claims = TestJwtClaims.get_test_real_user(user.keycloak_guid)
    membership = [
        TestAnonymousMembership.generate_random_user(USER),
        TestAnonymousMembership.generate_random_user(COORDINATOR)
    ]

    patch_token_info(claims, monkeypatch)
    users = UserService.create_user_and_add_membership(membership, org.id)

    assert len(users['users']) == 2
    assert users['users'][0][
        'username'] == IdpHint.BCROS.value + '/' + membership[0]['username']
    assert users['users'][0]['type'] == Role.ANONYMOUS_USER.name
    assert users['users'][1][
        'username'] == IdpHint.BCROS.value + '/' + membership[1]['username']
    assert users['users'][1]['type'] == Role.ANONYMOUS_USER.name

    members = MembershipModel.find_members_by_org_id(org.id)

    # staff didnt create members..so count is count of owner+other 2 members
    assert len(members) == 3
예제 #15
0
def test_create_org(session, keycloak_mock):  # pylint:disable=unused-argument
    """Assert that an Org can be created."""
    user = factory_user_model()
    org = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
    assert org
    dictionary = org.as_dict()
    assert dictionary['name'] == TestOrgInfo.org1['name']
예제 #16
0
def test_check_auth_for_service_account_invalid(session):  # pylint:disable=unused-argument
    """Assert that check_auth is working as expected and throws exception."""
    user = factory_user_model()
    org = factory_org_model()
    factory_membership_model(user.id, org.id)
    entity = factory_entity_model()
    factory_affiliation_model(entity.id, org.id)

    # Test for invalid CP
    with pytest.raises(HTTPException) as excinfo:
        check_auth(
            {
                'realm_access': {
                    'roles': ['system']
                },
                'corp_type': 'IVALIDCP'
            },
            org_id=org.id)
        assert excinfo.exception.code == 403

    # Test for invalid CP
    with pytest.raises(HTTPException) as excinfo:
        check_auth({'realm_access': {'roles': ['system']}}, org_id=org.id)
        assert excinfo.exception.code == 403

    # Test for invalid CP with no args
    with pytest.raises(HTTPException) as excinfo:
        check_auth({'realm_access': {'roles': ['system']}})
        assert excinfo.exception.code == 403
예제 #17
0
def test_check_auth_for_service_account_invalid(session):  # pylint:disable=unused-argument
    """Assert that check_auth is working as expected and throws exception."""
    user = factory_user_model()
    org = factory_org_model()
    factory_membership_model(user.id, org.id)
    entity = factory_entity_model()
    factory_affiliation_model(entity.id, org.id)
예제 #18
0
def test_create_task_product(session, keycloak_mock):  # pylint:disable=unused-argument
    """Assert that a task can be created."""
    user = factory_user_model()
    test_org = factory_org_model()
    test_product = factory_product_model(org_id=test_org.id)
    product: ProductCodeModel = ProductCodeModel.find_by_code(
        test_product.product_code)
    test_task_info = {
        'name': test_org.name,
        'relationshipId': test_product.id,
        'relatedTo': user.id,
        'dateSubmitted': datetime.today(),
        'relationshipType': TaskRelationshipType.PRODUCT.value,
        'type': product.description,
        'status': [TaskStatus.OPEN.value],
        'accountId': test_org.id,
        'relationship_status':
        TaskRelationshipStatus.PENDING_STAFF_REVIEW.value
    }
    task = TaskService.create_task(test_task_info)
    assert task
    dictionary = task.as_dict()
    assert dictionary['name'] == test_task_info['name']
    assert dictionary['account_id'] == test_org.id
    assert dictionary[
        'relationship_type'] == TaskRelationshipType.PRODUCT.value
예제 #19
0
def test_add_back_a_delete_bcros(client, jwt, session, keycloak_mock):
    """Assert different conditions of user deletion."""
    org = factory_org_model(org_info=TestOrgInfo.org_anonymous)
    user = factory_user_model(user_info=TestUserInfo.user_bcros_active)
    factory_membership_model(user.id, org.id)
    factory_product_model(org.id, product_code=ProductCode.DIR_SEARCH.value)
    owner_claims = TestJwtClaims.get_test_real_user(user.keycloak_guid)
    member = TestAnonymousMembership.generate_random_user(USER)
    membership = [
        member,
        TestAnonymousMembership.generate_random_user(COORDINATOR)
    ]
    UserService.create_user_and_add_membership(membership,
                                               org.id,
                                               token_info=owner_claims)
    headers = factory_auth_header(jwt=jwt, claims=owner_claims)
    member_user_id = IdpHint.BCROS.value + '/' + member.get('username')
    rv = client.delete(f'/api/v1/users/{member_user_id}',
                       headers=headers,
                       content_type='application/json')
    assert rv.status_code == http_status.HTTP_204_NO_CONTENT
    kc_user = KeycloakService.get_user_by_username(member.get('username'))
    assert kc_user.enabled is False
    user_model = UserService.find_by_username(member_user_id)
    assert user_model.as_dict().get('user_status') == UserStatus.INACTIVE.value
    membership = MembershipModel.find_membership_by_userid(
        user_model.identifier)
    assert membership.status == Status.INACTIVE.value
예제 #20
0
def test_reset(session, auth_mock):  # pylint: disable=unused-argument
    """Assert that can be reset data by the provided token."""
    user_with_token = TestUserInfo.user_tester
    user_with_token['keycloak_guid'] = TestJwtClaims.tester_role['sub']
    user = factory_user_model(user_info=user_with_token)
    org = factory_org_model(user_id=user.id)
    factory_membership_model(user.id, org.id)
    entity = factory_entity_model(user_id=user.id)

    ResetDataService.reset(TestJwtClaims.tester_role)

    with pytest.raises(BusinessException) as exception:
        UserService.find_by_jwt_token(user_with_token)
    assert exception.value.code == Error.DATA_NOT_FOUND.name

    found_org = OrgService.find_by_org_id(org.id)
    assert found_org is None

    found_entity = EntityService.find_by_entity_id(entity.id)
    assert found_entity is not None
    dictionary = found_entity.as_dict()
    assert dictionary['businessIdentifier'] == TestEntityInfo.entity1[
        'businessIdentifier']
    assert not dictionary['passCodeClaimed']

    found_memeber = MembershipService.get_members_for_org(org.id)
    assert found_memeber is None
예제 #21
0
def test_delete_user_as_only_admin_returns_400(client, jwt, session,
                                               keycloak_mock):  # pylint:disable=unused-argument
    """Test if the user is the only owner of a team assert status is 400."""
    user_model = factory_user_model(user_info=TestUserInfo.user_test)
    contact = factory_contact_model()
    contact_link = ContactLinkModel()
    contact_link.contact = contact
    contact_link.user = user_model
    contact_link.commit()

    claims = copy.deepcopy(TestJwtClaims.public_user_role.value)
    claims['sub'] = str(user_model.keycloak_guid)

    org = OrgService.create_org(TestOrgInfo.org1,
                                user_id=user_model.id,
                                token_info=claims)
    org_dictionary = org.as_dict()
    org_id = org_dictionary['id']

    entity = factory_entity_model(entity_info=TestEntityInfo.entity_lear_mock)

    affiliation = AffiliationModel(org_id=org_id, entity_id=entity.id)
    affiliation.save()

    headers = factory_auth_header(jwt=jwt, claims=claims)

    rv = client.delete('/api/v1/users/@me',
                       headers=headers,
                       content_type='application/json')
    assert rv.status_code == http_status.HTTP_400_BAD_REQUEST
예제 #22
0
def test_get_owner_count_one_owner(session, keycloak_mock):  # pylint:disable=unused-argument
    """Assert that count of owners is correct."""
    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)
    assert org.get_owner_count() == 1
예제 #23
0
def test_delete_contact_user_link(session, auth_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Assert that a contact can not be deleted if contact link exists."""
    user_with_token = TestUserInfo.user_test
    user_with_token['keycloak_guid'] = TestJwtClaims.public_user_role['sub']
    user_model = factory_user_model(user_info=user_with_token)
    user = UserService(user_model)

    org = OrgService.create_org(TestOrgInfo.org1, user_id=user.identifier)
    org_dictionary = org.as_dict()
    org_id = org_dictionary['id']

    contact = factory_contact_model()

    contact_link = ContactLinkModel()
    contact_link.contact = contact
    contact_link.user = user_model
    contact_link.org = org._model  # pylint:disable=protected-access
    contact_link = contact_link.flush()
    contact_link.commit()

    deleted_contact = UserService.delete_contact(
        TestJwtClaims.public_user_role)

    assert deleted_contact is None

    delete_contact_link = ContactLinkModel.find_by_user_id(user.identifier)
    assert not delete_contact_link

    exist_contact_link = ContactLinkModel.find_by_org_id(org_id)
    assert exist_contact_link
예제 #24
0
def test_delete_org_with_affiliation_fail(session, auth_mock, keycloak_mock):  # pylint:disable=unused-argument
    """Assert that an org cannot be deleted."""
    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_id = org.as_dict()['id']

    entity_service = factory_entity_service(
        entity_info=TestEntityInfo.entity_lear_mock)
    entity_dictionary = entity_service.as_dict()
    business_identifier = entity_dictionary['businessIdentifier']
    AffiliationService.create_affiliation(
        org_id, business_identifier,
        TestEntityInfo.entity_lear_mock['passCode'], {})

    with pytest.raises(BusinessException) as exception:
        OrgService.delete_org(org_id, TestJwtClaims.edit_role)

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

    AffiliationService.delete_affiliation(
        org_id, business_identifier,
        TestEntityInfo.entity_lear_mock['passCode'])
    OrgService.delete_org(org.as_dict()['id'], TestJwtClaims.edit_role)
    org_inactive = OrgService.find_by_org_id(org.as_dict()['id'])
    assert org_inactive.as_dict()['org_status'] == 'INACTIVE'
예제 #25
0
def test_get_user_settings(client, jwt, session, keycloak_mock, monkeypatch):  # pylint:disable=unused-argument
    """Assert that get works and adhere to schema."""
    user_model = factory_user_model(user_info=TestUserInfo.user_test)
    contact = factory_contact_model()
    contact_link = ContactLinkModel()
    contact_link.contact = contact
    contact_link.user = user_model
    contact_link.commit()
    kc_id = user_model.keycloak_guid

    claims = copy.deepcopy(TestJwtClaims.updated_test.value)
    claims['sub'] = str(kc_id)
    patch_token_info(claims, monkeypatch)

    OrgService.create_org(TestOrgInfo.org1, user_id=user_model.id)

    # post token with updated claims
    headers = factory_auth_header(jwt=jwt, claims=claims)
    rv = client.get(f'/api/v1/users/{kc_id}/settings', headers=headers, content_type='application/json')
    item_list = rv.json
    account = next(obj for obj in item_list if obj['type'] == 'ACCOUNT')
    assert account['accountType'] == 'BASIC'
    assert rv.status_code == http_status.HTTP_200_OK
    assert schema_utils.validate(item_list, 'user_settings_response')[0]
    assert account['productSettings'] == f'/account/{account["id"]}/restricted-product'
예제 #26
0
def test_create_org_adds_user_to_account_holders_group(session, monkeypatch):  # pylint:disable=unused-argument
    """Assert that an Org creation adds the user to account holders group."""
    # Create a user in keycloak
    keycloak_service = KeycloakService()
    keycloak_service.add_user(KeycloakScenario.create_user_request(),
                              return_if_exists=True)
    kc_user = keycloak_service.get_user_by_username(
        KeycloakScenario.create_user_request().user_name)
    user = factory_user_model(
        TestUserInfo.get_user_with_kc_guid(kc_guid=kc_user.id))

    # Patch token info
    def token_info():  # pylint: disable=unused-argument; mocks of library methods
        return {
            'sub': str(kc_user.id),
            'username': '******',
            'realm_access': {
                'roles': []
            }
        }

    monkeypatch.setattr(
        'auth_api.services.keycloak.KeycloakService._get_token_info',
        token_info)
    OrgService.create_org(TestOrgInfo.org1, user_id=user.id)

    user_groups = keycloak_service.get_user_groups(user_id=kc_user.id)
    groups = []
    for group in user_groups:
        groups.append(group.get('name'))
    assert GROUP_ACCOUNT_HOLDERS in groups
def factory_membersip_model(session):
    """Produce a templated org model."""
    user = factory_user_model()
    org_type = OrgTypeModel(code='TEST', desc='Test')
    session.add(org_type)
    session.commit()

    org_status = OrgStatusModel(code='TEST', desc='Test')
    session.add(org_status)
    session.commit()

    preferred_payment = PaymentTypeModel(code='TEST', desc='Test')
    session.add(preferred_payment)
    session.commit()
    org = OrgModel(name='Test Org')
    org.org_type = org_type
    org.org_status = OrgStatusModel.get_default_status()
    org.preferred_payment = preferred_payment
    org.save()

    membership = MembershipModel(org_id=org.id,
                                 user_id=user.id,
                                 membership_type_code=OWNER,
                                 status=1)
    membership.save()
    return membership
예제 #28
0
def test_delete_does_not_remove_user_from_account_holder_group(
        session, monkeypatch, auth_mock):  # pylint:disable=unused-argument
    """Assert that if the user has multiple Orgs, and deleting one doesn't remove account holders group."""
    # Create a user in keycloak
    keycloak_service = KeycloakService()
    keycloak_service.add_user(KeycloakScenario.create_user_request(),
                              return_if_exists=True)
    kc_user = keycloak_service.get_user_by_username(
        KeycloakScenario.create_user_request().user_name)
    user = factory_user_model(
        TestUserInfo.get_user_with_kc_guid(kc_guid=kc_user.id))

    # Patch token info
    def token_info():  # pylint: disable=unused-argument; mocks of library methods
        return {
            'sub': str(kc_user.id),
            'username': '******',
            'realm_access': {
                'roles': []
            }
        }

    monkeypatch.setattr(
        'auth_api.services.keycloak.KeycloakService._get_token_info',
        token_info)
    org1 = OrgService.create_org(TestOrgInfo.org1, user_id=user.id)
    OrgService.create_org(TestOrgInfo.org2, user_id=user.id)
    OrgService.delete_org(org1.as_dict().get('id'), token_info())

    user_groups = keycloak_service.get_user_groups(user_id=kc_user.id)
    groups = []
    for group in user_groups:
        groups.append(group.get('name'))
    assert GROUP_ACCOUNT_HOLDERS in groups
예제 #29
0
def test_update_contact_for_user(session):  # pylint: disable=unused-argument
    """Assert that a contact can be updated for a user."""
    user_with_token = TestUserInfo.user_test
    user_with_token['keycloak_guid'] = TestJwtClaims.user_test['sub']
    factory_user_model(user_info=user_with_token)

    contact = UserService.add_contact(TestJwtClaims.user_test,
                                      TestContactInfo.contact1).as_dict()

    assert contact is not None

    updated_contact = UserService.update_contact(
        TestJwtClaims.user_test, TestContactInfo.contact2).as_dict()

    assert updated_contact is not None
    assert updated_contact['email'] == TestContactInfo.contact2['email']
예제 #30
0
def test_delete_org_with_affiliation(session, auth_mock, keycloak_mock,
                                     monkeypatch):  # pylint:disable=unused-argument
    """Assert that an org cannot be deleted."""
    user_with_token = TestUserInfo.user_test
    user_with_token['keycloak_guid'] = TestJwtClaims.public_user_role['sub']
    user = factory_user_model(user_info=user_with_token)

    patch_token_info({'sub': user.keycloak_guid}, monkeypatch)
    org = OrgService.create_org(TestOrgInfo.org1, user.id)
    org_id = org.as_dict()['id']

    entity_service = factory_entity_service(
        entity_info=TestEntityInfo.entity_lear_mock)
    entity_dictionary = entity_service.as_dict()
    business_identifier = entity_dictionary['business_identifier']
    AffiliationService.create_affiliation(
        org_id, business_identifier,
        TestEntityInfo.entity_lear_mock['passCode'])

    patch_token_info(TestJwtClaims.public_user_role, monkeypatch)
    patch_pay_account_delete(monkeypatch)
    OrgService.delete_org(org_id)

    assert len(
        AffiliationService.find_visible_affiliations_by_org_id(org_id)) == 0