예제 #1
0
def test_delete_user_is_member_returns_204(client, jwt, session, keycloak_mock):  # pylint:disable=unused-argument
    """Test if the user is the member of a team assert status is 204."""
    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()

    org = OrgService.create_org(TestOrgInfo.org1, user_id=user_model.id)
    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()

    user_model2 = factory_user_model(user_info=TestUserInfo.user2)
    contact = factory_contact_model()
    contact_link = ContactLinkModel()
    contact_link.contact = contact
    contact_link.user = user_model2
    contact_link.commit()

    membership = MembershipModel(org_id=org_id, user_id=user_model2.id, membership_type_code='MEMBER',
                                 membership_type_status=Status.ACTIVE.value)
    membership.save()

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

    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_204_NO_CONTENT
예제 #2
0
def factory_user_model_with_contact(user_info: dict = TestUserInfo.user1,
                                    keycloak_guid=None):
    """Produce a user model."""
    user_type = Role.ANONYMOUS_USER.name if user_info.get(
        'access_type', None) == AccessType.ANONYMOUS.value else None
    user = UserModel(username=user_info.get(
        'username', user_info.get('preferred_username')),
                     firstname=user_info['firstname'],
                     lastname=user_info['lastname'],
                     keycloak_guid=user_info.get('keycloak_guid',
                                                 keycloak_guid),
                     type=user_type,
                     email='*****@*****.**',
                     login_source=user_info.get('loginSource'))

    user.save()

    contact = factory_contact_model()
    contact.save()
    contact_link = ContactLinkModel()
    contact_link.contact = contact
    contact_link.user = user
    contact_link.save()

    return user
예제 #3
0
def factory_user_model_with_contact():
    """Produce a user model."""
    user_info = {
        'username': '******',
        'firstname': 'bar',
        'lastname': 'User',
        'keycloak_guid': uuid.uuid4()
    }

    user = UserModel(
        username=user_info['username'],
        firstname=user_info['firstname'],
        lastname=user_info['lastname'],
        keycloak_guid=user_info.get('keycloak_guid', None),
        type=user_info.get('access_type', None),
    )

    user.save()

    contact = factory_contact_model()
    contact.save()
    contact_link = ContactLinkModel()
    contact_link.contact = contact
    contact_link.user = user
    contact_link.save()

    return user
예제 #4
0
파일: test_user.py 프로젝트: syin/sbc-auth
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.edit_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.edit_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
예제 #5
0
def test_delete_contact_entity_link(session, auth_mock):  # pylint:disable=unused-argument
    """Assert that a contact can not be deleted without entity."""
    entity_model = factory_entity_model()
    entity = EntityService(entity_model)

    org = factory_org_service()
    org_dictionary = org.as_dict()
    org_id = org_dictionary['id']

    contact = factory_contact_model()

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

    updated_entity = entity.delete_contact()

    dictionary = None
    dictionary = updated_entity.as_dict()
    assert len(dictionary['contacts']) == 0

    delete_contact_link = ContactLinkModel.find_by_entity_id(entity.identifier)
    assert not delete_contact_link

    exist_contact_link = ContactLinkModel.find_by_org_id(org_id)
    assert exist_contact_link
예제 #6
0
def test_delete_contact_user_link(session, auth_mock):  # pylint:disable=unused-argument
    """Assert that a contact can not be deleted if contact link exists."""
    user_model = factory_user_model(user_info=TestUserInfo.user_test)
    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.commit()

    updated_user = user.delete_contact(TestJwtClaims.user_test)

    dictionary = None
    dictionary = updated_user.as_dict()
    assert len(dictionary['contacts']) == 0

    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
예제 #7
0
def test_delete_contact_org_link(session, auth_mock):  # pylint:disable=unused-argument
    """Assert that a contact can not be deleted if it's still being used by an entity."""
    entity_model = factory_entity_model()
    entity = EntityService(entity_model)

    org = factory_org_service()
    org_dictionary = org.as_dict()
    org_id = org_dictionary['id']

    contact = factory_contact_model()

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

    OrgService.delete_contact(org_id=org_id)
    org = OrgService.find_by_org_id(org_id)
    response = OrgService.get_contacts(org_id)

    assert len(response['contacts']) == 0

    delete_contact_link = ContactLinkModel.find_by_entity_id(entity.identifier)
    assert delete_contact_link

    exist_contact_link = ContactLinkModel.find_by_org_id(org_id)
    assert not exist_contact_link
예제 #8
0
def test_get_user_settings(client, jwt, session, keycloak_mock):  # 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

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

    claims = copy.deepcopy(TestJwtClaims.updated_test.value)
    claims['sub'] = str(kc_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"]}/settings/product-settings'
예제 #9
0
파일: test_user.py 프로젝트: syin/sbc-auth
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()

    org = OrgService.create_org(TestOrgInfo.org1, user_id=user_model.id)
    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()

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

    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
예제 #10
0
파일: test_user.py 프로젝트: syin/sbc-auth
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'
예제 #11
0
    def add_contact(token,
                    contact_info: dict,
                    throw_error_for_duplicates: bool = True):
        """Add contact information for an existing user."""
        current_app.logger.debug('add_contact')
        user = UserModel.find_by_jwt_token(token)
        if user is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        # check for existing contact (we only want one contact per user)
        contact_link = ContactLinkModel.find_by_user_id(user.id)
        if contact_link is not None:
            if not throw_error_for_duplicates:
                # TODO may be throw whole object
                return None
            raise BusinessException(Error.DATA_ALREADY_EXISTS, None)

        contact = ContactModel(**camelback2snake(contact_info))
        contact = contact.flush()

        contact_link = ContactLinkModel()
        contact_link.user = user
        contact_link.contact = contact
        contact_link.save()

        return ContactService(contact)
예제 #12
0
    def create_affidavit(token_info: Dict, affidavit_info: Dict):
        """Create a new affidavit record."""
        current_app.logger.debug('<create_affidavit ')
        user = UserService.find_by_jwt_token(token=token_info)
        # If the user already have a pending affidavit, raise error
        existing_affidavit = AffidavitModel.find_pending_by_user_id(
            user_id=user.identifier)
        if existing_affidavit is not None:
            raise BusinessException(Error.ACTIVE_AFFIDAVIT_EXISTS, None)

        contact = affidavit_info.pop('contact')
        affidavit_model = AffidavitModel(
            issuer=affidavit_info.get('issuer'),
            document_id=affidavit_info.get('documentId'),
            status_code=AffidavitStatus.PENDING.value,
            user_id=user.identifier)
        affidavit_model.add_to_session()

        # Save contact for the affidavit
        if contact:
            contact = ContactModel(**camelback2snake(contact))
            contact.add_to_session()

            contact_link = ContactLinkModel()
            contact_link.affidavit = affidavit_model
            contact_link.contact = contact
            contact_link.add_to_session()

        affidavit_model.save()

        return Affidavit(affidavit_model)
예제 #13
0
def test_delete_user_where_org_has_another_owner(session, auth_mock,
                                                 keycloak_mock, monkeypatch):  # pylint:disable=unused-argument
    """Assert that a user can be deleted."""
    # Create a user and org
    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()

    patch_token_info(TestJwtClaims.get_test_user(user_model.keycloak_guid),
                     monkeypatch)
    org = OrgService.create_org(TestOrgInfo.org1, user_id=user_model.id)
    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()

    # Create another user and add membership to the above org
    user_model2 = factory_user_model(user_info=TestUserInfo.user2)
    contact = factory_contact_model()
    contact_link = ContactLinkModel()
    contact_link.contact = contact
    contact_link.user = user_model2
    contact_link.commit()

    membership = MembershipModel(org_id=org_id,
                                 user_id=user_model2.id,
                                 membership_type_code='ADMIN',
                                 membership_type_status=Status.ACTIVE.value)
    membership.save()
    membership.commit()

    # with pytest.raises(BusinessException) as exception:
    patch_token_info(TestJwtClaims.get_test_user(user_model2.keycloak_guid),
                     monkeypatch)
    UserService.delete_user()

    updated_user = UserModel.find_by_jwt_token()
    assert len(updated_user.contacts) == 0

    user_orgs = MembershipModel.find_orgs_for_user(updated_user.id)
    for org in user_orgs:
        assert org.status_code == 'INACTIVE'
예제 #14
0
 def add_contact_to_org(mailing_address, org):
     """Update the passed organization with the mailing address."""
     contact = ContactModel(**camelback2snake(mailing_address))
     contact = contact.add_to_session()
     contact_link = ContactLinkModel()
     contact_link.contact = contact
     contact_link.org = org
     contact_link.add_to_session()
예제 #15
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.org_branch_name, 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 account['additionalLabel'] == TestOrgInfo.org_branch_name.get(
        'branchName')
    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'

    kc_id_no_user = TestUserInfo.user1.get('keycloak_guid')
    claims = copy.deepcopy(TestJwtClaims.updated_test.value)
    claims['sub'] = str(kc_id_no_user)
    patch_token_info(claims, monkeypatch)
    # post token with updated claims
    headers = factory_auth_header(jwt=jwt, claims=claims)
    rv = client.get(f'/api/v1/users/{kc_id_no_user}/settings',
                    headers=headers,
                    content_type='application/json')
    assert rv.status_code == http_status.HTTP_200_OK
    assert schema_utils.validate(item_list, 'user_settings_response')[0]
    item_list = rv.json
    account = next((obj for obj in item_list if obj['type'] == 'ACCOUNT'),
                   None)
    assert account is None
    user_profile = next(obj for obj in item_list
                        if obj['type'] == 'USER_PROFILE')
    assert '/userprofile' in user_profile.get('urlpath')
예제 #16
0
    def add_contact(self, contact_info: dict):
        """Add a business contact to this entity."""
        # check for existing contact (we only want one contact per user)
        contact_link = ContactLinkModel.find_by_entity_id(self._model.id)
        if contact_link is not None:
            raise BusinessException(Error.DATA_ALREADY_EXISTS, None)

        contact = ContactModel(**camelback2snake(contact_info))
        contact.commit()

        contact_link = ContactLinkModel()
        contact_link.contact = contact
        contact_link.entity = self._model
        contact_link.commit()

        return self
예제 #17
0
파일: org.py 프로젝트: jeznorth/sbc-auth
    def add_contact(self, contact_info):
        """Create a new contact for this org."""
        # check for existing contact (only one contact per org for now)
        current_app.logger.debug('>add_contact ')
        contact_link = ContactLinkModel.find_by_org_id(self._model.id)
        if contact_link is not None:
            raise BusinessException(Error.DATA_ALREADY_EXISTS, None)

        contact = ContactModel(**camelback2snake(contact_info))
        contact.commit()

        contact_link = ContactLinkModel()
        contact_link.contact = contact
        contact_link.org = self._model
        contact_link.commit()
        current_app.logger.debug('>add_contact ')
        return self
예제 #18
0
def test_delete_user(session, auth_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.commit()

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

    UserService.delete_user(TestJwtClaims.user_test)
    updated_user = UserModel.find_by_jwt_token(TestJwtClaims.user_test)
    assert len(updated_user.contacts) == 0

    user_orgs = MembershipModel.find_orgs_for_user(updated_user.id)
    for org in user_orgs:
        assert org.status_code == 'INACTIVE'
예제 #19
0
def test_delete_entity(app, session):  # pylint:disable=unused-argument
    """Assert that an entity can be deleted."""
    entity_model = factory_entity_model()
    entity = EntityService(entity_model)

    org = factory_org_service()

    contact = factory_contact_model()

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

    entity.delete()

    entity = EntityService.find_by_entity_id(entity.identifier)

    assert entity is None
예제 #20
0
def factory_user_model_with_contact(user_info: dict = TestUserInfo.user1):
    """Produce a user model."""
    user = UserModel(username=user_info['username'],
                     firstname=user_info['firstname'],
                     lastname=user_info['lastname'],
                     roles=user_info['roles'],
                     keycloak_guid=user_info.get('keycloak_guid', None),
                     type=user_info.get('access_type', None),
                     email='*****@*****.**')

    user.save()

    contact = factory_contact_model()
    contact.save()
    contact_link = ContactLinkModel()
    contact_link.contact = contact
    contact_link.user = user
    contact_link.save()

    return user
예제 #21
0
파일: user.py 프로젝트: sumesh-aot/sbc-auth
    def add_contact(token, contact_info: dict):
        """Add or update contact information for an existing user."""
        user = UserModel.find_by_jwt_token(token)
        if user is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        # check for existing contact (we only want one contact per user)
        contact_link = ContactLinkModel.find_by_user_id(user.id)
        if contact_link is not None:
            raise BusinessException(Error.DATA_ALREADY_EXISTS, None)

        contact = ContactModel(**camelback2snake(contact_info))
        contact.commit()

        contact_link = ContactLinkModel()
        contact_link.user = user
        contact_link.contact = contact
        contact_link.commit()

        return User(user)
예제 #22
0
    def add_contact(org_id, contact_info):
        """Create a new contact for this org."""
        # check for existing contact (only one contact per org for now)
        current_app.logger.debug('>add_contact')
        org = OrgModel.find_by_org_id(org_id)
        if org is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        contact_link = ContactLinkModel.find_by_org_id(org_id)
        if contact_link is not None:
            raise BusinessException(Error.DATA_ALREADY_EXISTS, None)

        contact = ContactModel(**camelback2snake(contact_info))
        contact = contact.flush()

        contact_link = ContactLinkModel()
        contact_link.contact = contact
        contact_link.org = org
        contact_link.save()
        current_app.logger.debug('<add_contact')

        return ContactService(contact)
예제 #23
0
    def create_affidavit(affidavit_info: Dict):
        """Create a new affidavit record."""
        current_app.logger.debug('<create_affidavit ')
        user = UserService.find_by_jwt_token()
        # If the user already have a pending affidavit, raise error
        existing_affidavit: AffidavitModel = AffidavitModel.find_pending_by_user_id(
            user_id=user.identifier)
        trigger_task_update = False
        if existing_affidavit is not None:
            # inactivate the current affidavit
            existing_affidavit.status_code = AffidavitStatus.INACTIVE.value
            existing_affidavit.flush()
            trigger_task_update = True

        contact = affidavit_info.pop('contact')
        affidavit_model = AffidavitModel(
            issuer=affidavit_info.get('issuer'),
            document_id=affidavit_info.get('documentId'),
            status_code=AffidavitStatus.PENDING.value,
            user_id=user.identifier)
        affidavit_model.add_to_session()

        # Save contact for the affidavit
        if contact:
            contact = ContactModel(**camelback2snake(contact))
            contact.add_to_session()

            contact_link = ContactLinkModel()
            contact_link.affidavit = affidavit_model
            contact_link.contact = contact
            contact_link.add_to_session()

        affidavit_model.save()

        if trigger_task_update:
            Affidavit._modify_task(user)

        return Affidavit(affidavit_model)