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'
示例#2
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
示例#3
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)
示例#4
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
示例#5
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
示例#6
0
def test_delete_user_where_org_has_affiliations(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)
    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()
    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)
    assert len(updated_user.contacts) == 1

    user_orgs = MembershipModel.find_orgs_for_user(updated_user.id)
    for org in user_orgs:
        assert org.status_code == 'ACTIVE'
示例#7
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()

    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
示例#8
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()
示例#9
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.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
示例#10
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
示例#11
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
示例#12
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
示例#13
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')
示例#14
0
    def _notify_admin_about_hold(task_model, org: OrgModel = None, is_new_bceid_admin_request: bool = False,
                                 membership_id: int = None, user: UserModel = None):
        if is_new_bceid_admin_request:
            create_account_signin_route = urllib.parse.quote_plus(
                f"{current_app.config.get('BCEID_ADMIN_SETUP_ROUTE')}/"
                f'{task_model.account_id}/'
                f'{membership_id}')
            admin_email = user.contacts[0].contact.email
            account_id = task_model.account_id
            mailer_type = 'resubmitBceidAdmin'

        else:
            create_account_signin_route = urllib.parse. \
                quote_plus(f"{current_app.config.get('BCEID_ACCOUNT_SETUP_ROUTE')}/"
                           f'{org.id}')
            admin_email = ContactLinkModel.find_by_user_id(org.members[0].user.id).contact.email
            account_id = org.id
            mailer_type = 'resubmitBceidOrg'

        data = {
            'remarks': task_model.remarks,
            'applicationDate': f"{task_model.created.strftime('%m/%d/%Y')}",
            'accountId': account_id,
            'emailAddresses': admin_email,
            'contextUrl': f"{current_app.config.get('WEB_APP_URL')}"
                          f"/{current_app.config.get('BCEID_SIGNIN_ROUTE')}/"
                          f'{create_account_signin_route}'
        }
        try:
            publish_to_mailer(mailer_type, org_id=account_id, data=data)
            current_app.logger.debug('<send_approval_notification_to_member')
        except Exception as e:  # noqa=B901
            current_app.logger.error('<send_notification_to_member failed')
            raise BusinessException(Error.FAILED_NOTIFICATION, None) from e
示例#15
0
 def _notify_admin_about_hold(org, task_model):
     admin_email = ContactLinkModel.find_by_user_id(
         org.members[0].user.id).contact.email
     create_account_signin_route = urllib.parse.quote_plus(
         f"{current_app.config.get('BCEID_ACCOUNT_SETUP_ROUTE')}/"
         f'{org.id}')
     data = {
         'remark':
         task_model.remarks,
         'applicationDate':
         f"{task_model.created.strftime('%m/%d/%Y')}",
         'accountId':
         task_model.relationship_id,
         'emailAddresses':
         admin_email,
         'contextUrl':
         f"{current_app.config.get('WEB_APP_URL')}"
         f"/{current_app.config.get('BCEID_SIGNIN_ROUTE')}/"
         f'{create_account_signin_route}'
     }
     try:
         publish_to_mailer('resubmitBceidOrg', org_id=org.id, data=data)
         current_app.logger.debug('<send_approval_notification_to_member')
     except Exception as e:  # noqa=B901
         current_app.logger.error('<send_notification_to_member failed')
         raise BusinessException(Error.FAILED_NOTIFICATION, None) from e
示例#16
0
    def approve_or_reject(org_id: int, is_approved: bool, token_info: Dict, origin_url: str = None):
        """Mark the affidavit as approved or rejected."""
        current_app.logger.debug('<find_affidavit_by_org_id ')
        # Get the org and check what's the current status
        org: OrgModel = OrgModel.find_by_org_id(org_id)

        # Current User
        user: UserModel = UserModel.find_by_jwt_token(token=token_info)

        # If status is PENDING_AFFIDAVIT_REVIEW handle affidavit approve process, else raise error
        if org.status_code == OrgStatus.PENDING_AFFIDAVIT_REVIEW.value:
            AffidavitService.approve_or_reject(org_id, is_approved, user)
        else:
            raise BusinessException(Error.INVALID_INPUT, None)

        if is_approved:
            org.status_code = OrgStatus.ACTIVE.value
        else:
            org.status_code = OrgStatus.REJECTED.value

        org.decision_made_by = user.username
        org.decision_made_on = datetime.now()

        # TODO Publish to activity stream

        org.save()

        # Find admin email address
        admin_email = ContactLinkModel.find_by_user_id(org.members[0].user.id).contact.email
        Org.send_approved_rejected_notification(admin_email, org.name, org.status_code, origin_url)

        current_app.logger.debug('>find_affidavit_by_org_id ')
        return Org(org)
示例#17
0
    def update_product_subscription(product_subscription_id: int,
                                    is_approved: bool,
                                    org_id: int,
                                    is_new_transaction: bool = True):
        """Update Product Subscription."""
        current_app.logger.debug('<update_task_product ')
        # Approve/Reject Product subscription
        product_subscription: ProductSubscriptionModel = ProductSubscriptionModel.find_by_id(
            product_subscription_id)
        if is_approved:
            product_subscription.status_code = ProductSubscriptionStatus.ACTIVE.value
        else:
            product_subscription.status_code = ProductSubscriptionStatus.REJECTED.value
        product_subscription.flush()
        if is_new_transaction:  # Commit the transaction if it's a new transaction
            db.session.commit()

        # Get the org and to get admin mail address
        org: OrgModel = OrgModel.find_by_org_id(org_id)
        # Find admin email address
        admin_email = ContactLinkModel.find_by_user_id(
            org.members[0].user.id).contact.email
        product_model: ProductCodeModel = ProductCodeModel.find_by_code(
            product_subscription.product_code)
        Product.send_approved_product_subscription_notification(
            admin_email, product_model.description,
            product_subscription.status_code)
        if is_approved:
            ActivityLogPublisher.publish_activity(
                Activity(org_id,
                         ActivityAction.ADD_PRODUCT_AND_SERVICE.value,
                         name=product_model.description))
        current_app.logger.debug('>update_task_product ')
示例#18
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'
示例#19
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'
示例#20
0
文件: user.py 项目: jeznorth/sbc-auth
 def __delete_contact(user):
     # unlink the user from its contact
     contact_link = ContactLinkModel.find_by_user_id(user.id)
     if contact_link:
         del contact_link.user
         contact_link.commit()
         # clean up any orphaned contacts and links
         if not contact_link.has_links():
             contact = contact_link.contact
             contact_link.delete()
             contact.delete()
示例#21
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
示例#22
0
    def update_membership(self, updated_fields, token_info: Dict = None):
        """Update an existing membership with the given role."""
        # Ensure that this user is an COORDINATOR or ADMIN on the org associated with this membership
        current_app.logger.debug('<update_membership')
        check_auth(org_id=self._model.org_id, token_info=token_info, one_of_roles=(COORDINATOR, ADMIN, STAFF))

        # bceid Members cant be ADMIN's.Unless they have an affidavit approved.
        # TODO when multiple teams for bceid are present , do if the user has affidavit present check
        is_bceid_user = self._model.user.login_source == LoginSource.BCEID.value
        if is_bceid_user and getattr(updated_fields.get('membership_type', None), 'code', None) == ADMIN:
            raise BusinessException(Error.BCEID_USERS_CANT_BE_OWNERS, None)

        # Ensure that a member does not upgrade a member to ADMIN from COORDINATOR unless they are an ADMIN themselves
        if self._model.membership_type.code == COORDINATOR and updated_fields.get('membership_type', None) == ADMIN:
            check_auth(org_id=self._model.org_id, token_info=token_info, one_of_roles=(ADMIN, STAFF))

        admin_getting_removed: bool = False
        # Admin can be removed by other admin or staff. #4909
        if updated_fields.get('membership_status', None) \
                and updated_fields['membership_status'].id == Status.INACTIVE.value \
                and self._model.membership_type.code == ADMIN:
            admin_getting_removed = True
            if OrgService(self._model.org).get_owner_count() == 1:
                raise BusinessException(Error.CHANGE_ROLE_FAILED_ONLY_OWNER, None)

        # Ensure that if downgrading from owner that there is at least one other owner in org
        if self._model.membership_type.code == ADMIN and \
                updated_fields.get('membership_type', None) != ADMIN and \
                OrgService(self._model.org).get_owner_count() == 1:
            raise BusinessException(Error.CHANGE_ROLE_FAILED_ONLY_OWNER, None)

        for key, value in updated_fields.items():
            if value is not None:
                setattr(self._model, key, value)
        self._model.save()
        # Add to account_holders group in keycloak
        Membership._add_or_remove_group(self._model)
        is_staff_modifying = 'staff' in token_info.get('realm_access').get('roles')
        is_bcros_user = self._model.user.login_source == LoginSource.BCROS.value
        # send mail if staff modifies , not applicable for bcros , only if anything is getting updated
        if is_staff_modifying and not is_bcros_user and len(updated_fields) != 0:
            publish_to_mailer(notification_type='teamModified', org_id=self._model.org.id)

        # send mail to the person itself who is getting removed by staff ;if he is admin
        if is_staff_modifying and not is_bcros_user and admin_getting_removed:
            recipient_email = ContactLinkModel.find_by_user_id(self._model.user.id).contact.email
            data = {
                'accountId': self._model.org.id,
                'recipientEmail': recipient_email
            }
            publish_to_mailer(notification_type='adminRemoved', org_id=self._model.org.id, data=data)

        current_app.logger.debug('>update_membership')
        return self
示例#23
0
文件: org.py 项目: jeznorth/sbc-auth
    def update_contact(self, contact_info):
        """Update the existing contact for this org."""
        current_app.logger.debug('>update_contact ')
        contact_link = ContactLinkModel.find_by_org_id(self._model.id)
        if contact_link is None or contact_link.contact is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        contact = contact_link.contact
        contact.update_from_dict(**camelback2snake(contact_info))
        contact.commit()
        current_app.logger.debug('<update_contact ')
        return self
示例#24
0
    def update_contact(self, contact_info: dict):
        """Update a business contact for this entity."""
        # find the contact link object for this entity
        contact_link = ContactLinkModel.find_by_entity_id(self._model.id)
        if contact_link is None or contact_link.contact is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        contact = contact_link.contact
        contact.update_from_dict(**camelback2snake(contact_info))
        contact.commit()

        return self
示例#25
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)
示例#26
0
 def __delete_contact(org):
     # unlink the org from its contact
     contact_link = ContactLinkModel.find_by_org_id(org.id)
     if contact_link:
         del contact_link.org
         contact_link.commit()
         # clean up any orphaned contacts and links
         if not contact_link.has_links():
             contact = contact_link.contact
             contact_link.delete()
             contact.delete()
             return contact
     return None
示例#27
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)
示例#28
0
    def delete_contact(self):
        """Delete a business contact for this entity."""
        contact_link = ContactLinkModel.find_by_entity_id(self._model.id)
        if contact_link is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        del contact_link.entity
        contact_link.commit()

        if not contact_link.has_links():
            contact = contact_link.contact
            contact_link.delete()
            contact.delete()

        return self
示例#29
0
文件: org.py 项目: jeznorth/sbc-auth
    def delete_contact(self):
        """Delete the contact for this org."""
        current_app.logger.debug('>delete_contact ')
        contact_link = ContactLinkModel.find_by_org_id(self._model.id)
        if contact_link is None:
            raise BusinessException(Error.DATA_NOT_FOUND, None)

        del contact_link.org
        contact_link.commit()

        if not contact_link.has_links():
            contact = contact_link.contact
            contact_link.delete()
            contact.delete()
        current_app.logger.debug('<delete_contact ')
        return self
示例#30
0
    def approve_or_reject(org_id: int,
                          is_approved: bool,
                          origin_url: str = None):
        """Mark the affidavit as approved or rejected."""
        current_app.logger.debug('<find_affidavit_by_org_id ')
        # Get the org and check what's the current status
        org: OrgModel = OrgModel.find_by_org_id(org_id)

        # Current User
        user: UserModel = UserModel.find_by_jwt_token()

        # If status is PENDING_STAFF_REVIEW handle affidavit approve process, else raise error
        if org.status_code == OrgStatus.PENDING_STAFF_REVIEW.value and \
                org.access_type in (AccessType.EXTRA_PROVINCIAL.value, AccessType.REGULAR_BCEID.value):
            AffidavitService.approve_or_reject(org_id, is_approved, user)
        elif org.status_code != OrgStatus.PENDING_STAFF_REVIEW.value or \
                org.access_type not in \
                (AccessType.EXTRA_PROVINCIAL.value, AccessType.REGULAR_BCEID.value, AccessType.GOVM.value):
            raise BusinessException(Error.INVALID_INPUT, None)

        if is_approved:
            org.status_code = OrgStatus.ACTIVE.value
        else:
            org.status_code = OrgStatus.REJECTED.value

        org.decision_made_by = user.username
        org.decision_made_on = datetime.now()

        # TODO Publish to activity stream

        org.save()

        # Find admin email address
        admin_email = ContactLinkModel.find_by_user_id(
            org.members[0].user.id).contact.email
        if org.access_type in (AccessType.EXTRA_PROVINCIAL.value,
                               AccessType.REGULAR_BCEID.value):
            Org.send_approved_rejected_notification(admin_email, org.name,
                                                    org.id, org.status_code,
                                                    origin_url)
        elif org.access_type == AccessType.GOVM.value:
            Org.send_approved_rejected_govm_notification(
                admin_email, org.name, org.id, org.status_code, origin_url)

        current_app.logger.debug('>find_affidavit_by_org_id ')
        return Org(org)