コード例 #1
0
    def put(business_identifier):
        """Update the business contact for the Entity identified by the provided id."""
        request_json = request.get_json()
        valid_format, errors = schema_utils.validate(request_json, 'contact')
        if not valid_format:
            return {
                'message': schema_utils.serialize(errors)
            }, http_status.HTTP_400_BAD_REQUEST

        try:
            entity = EntityService.find_by_business_identifier(
                business_identifier,
                token_info=g.jwt_oidc_token_info,
                allowed_roles=ALL_ALLOWED_ROLES)
            if entity:
                response, status = entity.update_contact(request_json).as_dict(), \
                                   http_status.HTTP_200_OK
            else:
                response, status = {'message': 'The requested business could not be found.'}, \
                                   http_status.HTTP_404_NOT_FOUND
        except BusinessException as exception:
            response, status = {
                'code': exception.code,
                'message': exception.message
            }, exception.status_code
        return response, status
コード例 #2
0
    def post():
        """Post a new Entity using the request body."""
        request_json = request.get_json()

        # If the record exists, just return existing record.
        entity = EntityService.find_by_business_identifier(
            request_json.get('businessIdentifier'),
            token_info=g.jwt_oidc_token_info,
            allowed_roles=ALL_ALLOWED_ROLES)
        if entity:
            return entity.as_dict(), http_status.HTTP_202_ACCEPTED

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

        try:
            response, status = EntityService.save_entity(
                request_json).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
コード例 #3
0
    def delete_affiliation(org_id,
                           business_identifier,
                           token_info: Dict = None):
        """Delete the affiliation for the provided org id and business id."""
        current_app.logger.info(
            f'<delete_affiliation org_id:{org_id} business_identifier:{business_identifier}'
        )
        org = OrgService.find_by_org_id(org_id,
                                        token_info=token_info,
                                        allowed_roles=(*CLIENT_AUTH_ROLES,
                                                       STAFF))
        if org is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity = EntityService.find_by_business_identifier(
            business_identifier,
            token_info=token_info,
            allowed_roles=(*CLIENT_AUTH_ROLES, STAFF))
        if entity is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity_id = entity.identifier

        affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids(
            org_id=org_id, entity_id=entity_id)
        if affiliation is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        affiliation.delete()
        entity.set_pass_code_claimed(False)
コード例 #4
0
    def delete_affiliation(org_id, business_identifier, email_addresses: str = None,
                           reset_passcode: bool = False, token_info: Dict = None):
        """Delete the affiliation for the provided org id and business id."""
        current_app.logger.info(f'<delete_affiliation org_id:{org_id} business_identifier:{business_identifier}')
        org = OrgService.find_by_org_id(org_id, token_info=token_info, allowed_roles=(*CLIENT_AUTH_ROLES, STAFF))
        if org is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity = EntityService.find_by_business_identifier(business_identifier, token_info=token_info,
                                                           allowed_roles=(*CLIENT_AUTH_ROLES, STAFF))
        if entity is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity_id = entity.identifier

        affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids(org_id=org_id, entity_id=entity_id)
        if affiliation is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        if reset_passcode:
            entity.reset_passcode(entity.business_identifier, email_addresses, token_info)
        affiliation.delete()
        entity.set_pass_code_claimed(False)
        publish_activity(f'{ActivityAction.REMOVE_AFFILIATION.value}-{entity.name}', entity.name,
                         business_identifier, org_id)
コード例 #5
0
    def delete_affiliation(org_id, business_identifier, email_addresses: str = None,
                           reset_passcode: bool = False, log_delete_draft: bool = False):
        """Delete the affiliation for the provided org id and business id."""
        current_app.logger.info(f'<delete_affiliation org_id:{org_id} business_identifier:{business_identifier}')
        org = OrgService.find_by_org_id(org_id, allowed_roles=(*CLIENT_AUTH_ROLES, STAFF))
        if org is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity = EntityService.find_by_business_identifier(business_identifier,
                                                           allowed_roles=(*CLIENT_AUTH_ROLES, STAFF))
        if entity is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity_id = entity.identifier

        affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids(org_id=org_id, entity_id=entity_id)
        if affiliation is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        if reset_passcode:
            entity.reset_passcode(entity.business_identifier, email_addresses)
        affiliation.delete()
        entity.set_pass_code_claimed(False)

        # When registering a business it will affiliate a NR -> unaffiliate a NR draft -> affiliate a business.
        # Users can also intentionally delete a draft. We want to log this action.
        should_publish = (log_delete_draft or not (entity.status == NRStatus.DRAFT.value and
                                                   entity.corp_type == CorpType.NR.value))
        if entity.corp_type != CorpType.RTMP.value and should_publish:
            name = entity.name if len(entity.name) > 0 else entity.business_identifier
            ActivityLogPublisher.publish_activity(Activity(org_id, ActivityAction.REMOVE_AFFILIATION.value,
                                                           name=name, id=entity.business_identifier))
コード例 #6
0
    def create_affiliation(org_id,
                           business_identifier,
                           pass_code=None,
                           token_info: Dict = None):
        """Create an Affiliation."""
        # Validate if org_id is valid by calling Org Service.
        current_app.logger.info(
            f'<create_affiliation org_id:{org_id} business_identifier:{business_identifier}'
        )
        org = OrgService.find_by_org_id(org_id,
                                        token_info=token_info,
                                        allowed_roles=CLIENT_AUTH_ROLES)
        if org is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity = EntityService.find_by_business_identifier(business_identifier,
                                                           skip_auth=True)
        if entity is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)
        current_app.logger.debug('<create_affiliation entity found')
        entity_id = entity.identifier

        authorized = True

        # Authorized if the entity has been claimed
        if entity.as_dict()['passCodeClaimed']:
            authorized = False

        # If a passcode was provided...
        elif pass_code:
            # ... and the entity has a passcode on it, check that they match
            authorized = validate_passcode(pass_code, entity.pass_code)
        # If a passcode was not provided...
        else:
            # ... check that the entity does not have a passcode protecting it
            if entity.pass_code:
                authorized = False

        if not authorized:
            current_app.logger.debug('<create_affiliation not authorized')
            raise BusinessException(Error.INVALID_USER_CREDENTIALS, None)
        current_app.logger.debug('<create_affiliation find affiliation')
        # Ensure this affiliation does not already exist
        affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids(
            org_id, entity_id)
        if affiliation is not None:
            raise BusinessException(Error.DATA_ALREADY_EXISTS, None)

        # Retrieve entity name from Legal-API and update the entity with current name
        # TODO: Create subscription to listen for future name updates
        current_app.logger.debug('<create_affiliation sync_name')
        entity.sync_name()

        affiliation = AffiliationModel(org_id=org_id, entity_id=entity_id)
        affiliation.save()
        entity.set_pass_code_claimed(True)
        current_app.logger.debug('<create_affiliation affiliated')

        return Affiliation(affiliation)
コード例 #7
0
ファイル: affiliation.py プロジェクト: saravanpa-aot/sbc-auth
    def create_affiliation(org_id, business_identifier, pass_code=None):
        """Create an Affiliation."""
        # Validate if org_id is valid by calling Org Service.
        current_app.logger.info(
            f'<create_affiliation org_id:{org_id} business_identifier:{business_identifier}'
        )
        org = OrgService.find_by_org_id(org_id,
                                        allowed_roles=ALL_ALLOWED_ROLES)
        if org is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity = EntityService.find_by_business_identifier(business_identifier,
                                                           skip_auth=True)
        if entity is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)
        current_app.logger.debug('<create_affiliation entity found')
        entity_id = entity.identifier

        authorized = True
        already_claimed = False

        # Authorized if the entity has been claimed
        if entity.as_dict()['pass_code_claimed']:
            authorized = False
            already_claimed = True

        # If a passcode was provided...
        elif pass_code:
            # ... and the entity has a passcode on it, check that they match
            authorized = validate_passcode(pass_code, entity.pass_code)
        # If a passcode was not provided...
        else:
            # ... check that the entity does not have a passcode protecting it
            if entity.pass_code:
                authorized = False

        if not authorized:
            # show a different message when the passcode is already claimed
            if already_claimed:
                current_app.logger.debug(
                    '<create_affiliation passcode already claimed')
                raise BusinessException(Error.ALREADY_CLAIMED_PASSCODE, None)
            current_app.logger.debug('<create_affiliation not authorized')
            raise BusinessException(Error.INVALID_USER_CREDENTIALS, None)
        current_app.logger.debug('<create_affiliation find affiliation')
        # Ensure this affiliation does not already exist
        affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids(
            org_id, entity_id)
        if affiliation is not None:
            raise BusinessException(Error.DATA_ALREADY_EXISTS, None)

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

        entity.set_pass_code_claimed(True)
        publish_activity(
            f'{ActivityAction.CREATE_AFFILIATION.value}-{entity.name}',
            entity.name, entity_id, org_id)
        return Affiliation(affiliation)
コード例 #8
0
ファイル: entity.py プロジェクト: nchaturv/sbc-auth
 def get(business_identifier):
     """Get an existing entity by it's business number."""
     try:
         response, status = EntityService.find_by_business_identifier(business_identifier).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
コード例 #9
0
ファイル: test_entity.py プロジェクト: shabeeb-aot/sbc-auth
def test_entity_find_by_business_id(session, auth_mock):  # pylint:disable=unused-argument
    """Assert that an Entity can be retrieved by business identifier."""
    factory_entity_model()
    entity = EntityService.find_by_business_identifier(TestEntityInfo.entity1['businessIdentifier'])

    assert entity is not None
    dictionary = entity.as_dict()
    assert dictionary['business_identifier'] == TestEntityInfo.entity1['businessIdentifier']
コード例 #10
0
def test_entity_find_by_business_id(session):  # pylint:disable=unused-argument
    """Assert that an Entity can be retrieved by business identifier."""
    factory_entity_model(business_identifier='CP1234567')
    entity = EntityService.find_by_business_identifier('CP1234567')

    assert entity is not None
    dictionary = entity.as_dict()
    assert dictionary['businessIdentifier'] == 'CP1234567'
コード例 #11
0
ファイル: entity.py プロジェクト: saravanpa-aot/sbc-auth
 def delete(business_identifier):
     """Delete the business contact for the Entity identified by the provided id."""
     try:
         entity = EntityService.find_by_business_identifier(business_identifier, allowed_roles=CLIENT_AUTH_ROLES)
         if entity:
             response, status = entity.delete_contact().as_dict(), http_status.HTTP_200_OK
         else:
             response, status = {'message': 'The requested business could not be found.'}, \
                                http_status.HTTP_404_NOT_FOUND
     except BusinessException as exception:
         response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
     return response, status
コード例 #12
0
ファイル: entity.py プロジェクト: saravanpa-aot/sbc-auth
 def get(business_identifier):
     """Get an existing entity by it's business number."""
     try:
         entity = EntityService.find_by_business_identifier(business_identifier, allowed_roles=ALL_ALLOWED_ROLES)
         if entity is not None:
             response, status = entity.as_dict(), http_status.HTTP_200_OK
         else:
             response, status = {'message': 'A business for {} was not found.'.format(business_identifier)}, \
                                http_status.HTTP_404_NOT_FOUND
     except BusinessException as exception:
         response, status = {'code': exception.code, 'message': exception.message}, exception.status_code
     return response, status
コード例 #13
0
ファイル: entity.py プロジェクト: saravanpa-aot/sbc-auth
    def delete(business_identifier):
        """Delete an existing entity by it's business number."""
        try:
            entity = EntityService.find_by_business_identifier(business_identifier, allowed_roles=ALL_ALLOWED_ROLES)

            if entity:
                entity.delete()
                response, status = {}, http_status.HTTP_204_NO_CONTENT
            else:
                response, status = {'message': 'A business for {} was not found.'.format(business_identifier)}, \
                                   http_status.HTTP_404_NOT_FOUND
        except BusinessException as exception:
            response, status = {'code': exception.code, 'message': exception.message}, exception.status_code

        return response, status
コード例 #14
0
ファイル: affiliation.py プロジェクト: sumesh-aot/sbc-auth
    def create_affiliation(org_id, business_identifier, pass_code=None):
        """Create an Affiliation."""
        # Validate if org_id is valid by calling Org Service.
        org = OrgService.find_by_org_id(org_id)
        if org is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity = EntityService.find_by_business_identifier(business_identifier)
        if entity is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity_id = entity.identifier

        authorized = True

        # Authorized if the entity has been claimed
        if entity.as_dict()['passCodeClaimed']:
            authorized = False

        # If a passcode was provided...
        if pass_code:
            # ... and the entity has a passcode on it, check that they match
            if entity.pass_code != pass_code:
                authorized = False
        # If a passcode was not provided...
        else:
            # ... check that the entity does not have a passcode protecting it
            if entity.pass_code:
                authorized = False

        if not authorized:
            # If org being affiliated was IMPLICIT, remove it since the affiliation was not valid
            if org.as_dict()['org_type'] == 'IMPLICIT':
                org.delete_org()
            raise BusinessException(Error.INVALID_USER_CREDENTIALS, None)

        # Ensure this affiliation does not already exist
        affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids(
            org_id, entity_id)
        if affiliation is not None:
            raise BusinessException(Error.DATA_ALREADY_EXISTS, None)

        affiliation = AffiliationModel(org_id=org_id, entity_id=entity_id)
        affiliation.save()
        entity.set_pass_code_claimed(True)

        return Affiliation(affiliation)
コード例 #15
0
ファイル: affiliation.py プロジェクト: sumesh-aot/sbc-auth
    def delete_affiliation(org_id, business_identifier):
        """Delete the affiliation for the provided org id and business id."""
        org = OrgService.find_by_org_id(org_id)
        if org is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity = EntityService.find_by_business_identifier(business_identifier)
        if entity is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity_id = entity.identifier

        affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids(
            org_id=org_id, entity_id=entity_id)
        if affiliation is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        affiliation.delete()
        entity.set_pass_code_claimed(False)
コード例 #16
0
ファイル: entity.py プロジェクト: sumesh-aot/sbc-auth
    def post(business_identifier):
        """Add a new contact for the Entity identified by the provided id."""
        request_json = request.get_json()
        valid_format, errors = schema_utils.validate(request_json, 'contact')
        if not valid_format:
            return {
                'message': schema_utils.serialize(errors)
            }, http_status.HTTP_400_BAD_REQUEST

        try:
            entity = EntityService.find_by_business_identifier(
                business_identifier)
            if entity:
                response, status = entity.add_contact(request_json).as_dict(), \
                                   http_status.HTTP_201_CREATED
            else:
                response, status = {'message': 'The requested business could not be found.'}, \
                                   http_status.HTTP_404_NOT_FOUND
        except BusinessException as exception:
            response, status = {
                'code': exception.code,
                'message': exception.message
            }, exception.status_code
        return response, status
コード例 #17
0
    def create_new_business_affiliation(org_id,  # pylint: disable=too-many-arguments, too-many-locals
                                        business_identifier=None, email=None, phone=None,
                                        bearer_token: str = None):
        """Initiate a new incorporation."""
        current_app.logger.info(f'<create_affiliation org_id:{org_id} business_identifier:{business_identifier}')

        if not email and not phone:
            raise BusinessException(Error.NR_INVALID_CONTACT, None)

        # Validate if org_id is valid by calling Org Service.
        org = OrgService.find_by_org_id(org_id, allowed_roles=CLIENT_AUTH_ROLES)
        if org is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity = EntityService.find_by_business_identifier(business_identifier, skip_auth=True)
        # If entity already exists and passcode is already claimed, throw error
        if entity and entity.as_dict()['pass_code_claimed']:
            raise BusinessException(Error.NR_CONSUMED, None)

        # Call the legal-api to verify the NR details
        nr_json = Affiliation._get_nr_details(business_identifier, bearer_token)

        if nr_json:
            status = nr_json.get('state')
            nr_phone = nr_json.get('applicants').get('phoneNumber')
            nr_email = nr_json.get('applicants').get('emailAddress')

            if status not in (NRStatus.APPROVED.value, NRStatus.CONDITIONAL.value):
                raise BusinessException(Error.NR_NOT_APPROVED, None)

            # If consentFlag is not R, N or Null for a CONDITIONAL NR throw error
            if status == NRStatus.CONDITIONAL.value and nr_json.get('consentFlag', None) not in (None, 'R', 'N'):
                raise BusinessException(Error.NR_NOT_APPROVED, None)

            if (phone and phone != nr_phone) or (email and email.casefold() != nr_email.casefold()):
                raise BusinessException(Error.NR_INVALID_CONTACT, None)

            # Create an entity with the Name from NR if entity doesn't exist
            if not entity:
                # Filter the names from NR response and get the name which has status APPROVED as the name.
                # Filter the names from NR response and get the name which has status CONDITION as the name.
                nr_name_state = NRNameStatus.APPROVED.value if status == NRStatus.APPROVED.value \
                    else NRNameStatus.CONDITION.value
                name = next((name.get('name') for name in nr_json.get('names') if
                             name.get('state', None) == nr_name_state), None)

                entity = EntityService.save_entity({
                    'businessIdentifier': business_identifier,
                    'name': name,
                    'corpTypeCode': CorpType.NR.value,
                    'passCodeClaimed': True
                })
            # Create an affiliation with org
            affiliation_model = AffiliationModel(org_id=org_id, entity_id=entity.identifier)
            affiliation_model.save()
            if entity.corp_type != CorpType.RTMP.value:
                ActivityLogPublisher.publish_activity(Activity(org_id, ActivityAction.CREATE_AFFILIATION.value,
                                                               name=entity.name, id=entity.business_identifier))
            entity.set_pass_code_claimed(True)
        else:
            raise BusinessException(Error.NR_NOT_FOUND, None)

        return Affiliation(affiliation_model)
コード例 #18
0
    def create_affiliation(org_id, business_identifier, pass_code=None, bearer_token=None):
        """Create an Affiliation."""
        # Validate if org_id is valid by calling Org Service.
        current_app.logger.info(f'<create_affiliation org_id:{org_id} business_identifier:{business_identifier}')
        org = OrgService.find_by_org_id(org_id, allowed_roles=ALL_ALLOWED_ROLES)
        if org is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        entity = EntityService.find_by_business_identifier(business_identifier, skip_auth=True)
        if entity is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)
        current_app.logger.debug('<create_affiliation entity found')
        entity_id = entity.identifier
        entity_type = entity.corp_type

        authorized = True

        if entity_type in ['SP', 'GP']:
            if not pass_code:
                authorized = False
            else:
                authorized = Affiliation._validate_firms_party(bearer_token, business_identifier, pass_code)
        else:
            # Unauthorized if the entity has been claimed
            # Leaving the code as it may come back. Removing as part of #8863
            # if entity.as_dict()['pass_code_claimed']:
            #     authorized = False
            #     already_claimed = True
            # If a passcode was provided...
            if pass_code:
                # ... and the entity has a passcode on it, check that they match
                authorized = validate_passcode(pass_code, entity.pass_code)
            # If a passcode was not provided...
            else:
                # ... check that the entity does not have a passcode protecting it
                if entity.pass_code:
                    authorized = False

        # show a different message when the passcode is already claimed
        # if already_claimed:
        #     current_app.logger.debug('<create_affiliation passcode already claimed')
        #     raise BusinessException(Error.ALREADY_CLAIMED_PASSCODE, None)

        if not authorized:
            current_app.logger.debug('<create_affiliation not authorized')
            raise BusinessException(Error.INVALID_USER_CREDENTIALS, None)

        current_app.logger.debug('<create_affiliation find affiliation')
        # Ensure this affiliation does not already exist
        affiliation = AffiliationModel.find_affiliation_by_org_and_entity_ids(org_id, entity_id)
        if affiliation is not None:
            raise BusinessException(Error.DATA_ALREADY_EXISTS, None)

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

        if entity_type not in ['SP', 'GP']:
            entity.set_pass_code_claimed(True)
        if entity_type != CorpType.RTMP.value:
            name = entity.name if len(entity.name) > 0 else entity.business_identifier
            ActivityLogPublisher.publish_activity(Activity(org_id, ActivityAction.CREATE_AFFILIATION.value,
                                                           name=name, id=entity.business_identifier))
        return Affiliation(affiliation)
コード例 #19
0
ファイル: test_entity.py プロジェクト: stevenc987/sbc-auth
def test_entity_find_by_business_id_no_model(session, auth_mock):  # pylint:disable=unused-argument
    """Assert that an Entity which does not exist cannot be retrieved."""
    entity = EntityService.find_by_business_identifier(
        TestEntityInfo.entity1['businessIdentifier'])

    assert entity is None
コード例 #20
0
def test_entity_find_by_business_id_no_model(session):  # pylint:disable=unused-argument
    """Assert that an Entity which does not exist cannot be retrieved."""
    entity = EntityService.find_by_business_identifier('CP1234567')

    assert entity is None