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 ')
def delete_org( org_id, token_info: Dict = None, ): """Soft-Deletes an Org. It should not be deletable if there are members or business associated with the org """ # Check authorization for the user current_app.logger.debug('<org Inactivated') check_auth(token_info, one_of_roles=OWNER, org_id=org_id) org: OrgModel = OrgModel.find_by_org_id(org_id) if not org: raise BusinessException(Error.DATA_NOT_FOUND, None) count_members = len([ member for member in org.members if member.status in VALID_STATUSES ]) if count_members > 1 or len(org.affiliated_entities) >= 1: raise BusinessException(Error.ORG_CANNOT_BE_DISSOLVED, None) org.delete() # Remove user from thr group if the user doesn't have any other orgs membership user = UserModel.find_by_jwt_token(token=token_info) if len(MembershipModel.find_orgs_for_user(user.id)) == 0: KeycloakService.remove_from_account_holders_group( user.keycloak_guid) current_app.logger.debug('org Inactivated>')
def test_create_org_by_verified_bceid_user(session, keycloak_mock, monkeypatch): # pylint:disable=unused-argument """Assert that an Org can be created.""" # Steps # 1. Create a pending affidavit # 2. Create org # 3. Approve Org, which will mark the affidavit as approved # 4. Same user create new org, which should be ACTIVE. user = factory_user_model_with_contact(user_info=TestUserInfo.user_bceid_tester) token_info = TestJwtClaims.get_test_user(sub=user.keycloak_guid, source=LoginSource.BCEID.value) patch_token_info(token_info, monkeypatch) affidavit_info = TestAffidavit.get_test_affidavit_with_contact() AffidavitService.create_affidavit(affidavit_info=affidavit_info) org = OrgService.create_org(TestOrgInfo.org_with_mailing_address(), user_id=user.id) org_dict = org.as_dict() assert org_dict['org_status'] == OrgStatus.PENDING_STAFF_REVIEW.value task_model = TaskModel.find_by_task_for_account(org_dict['id'], status=TaskStatus.OPEN.value) assert task_model.relationship_id == org_dict['id'] assert task_model.action == TaskAction.AFFIDAVIT_REVIEW.value task_info = { 'status': TaskStatus.OPEN.value, 'relationshipStatus': TaskRelationshipStatus.ACTIVE.value, } TaskService.update_task(TaskService(task_model), task_info) org_result: OrgModel = OrgModel.find_by_org_id(org_dict['id']) assert org_result.status_code == OrgStatus.ACTIVE.value
def create_product_subscription(org_id, subscription_data: Tuple[Dict[str, Any]]): """Create product subscription for the user. create product subscription first create the product role next if roles are given """ org = OrgModel.find_by_org_id(org_id) if not org: raise BusinessException(Error.DATA_NOT_FOUND, None) subscriptions_list = subscription_data.get('subscriptions') # just used for returning all the models.. not ideal.. # todo remove this and may be return the subscriptions from db subscriptions_model_list = [] for subscription in subscriptions_list: product_code = subscription.get('productCode') product = ProductCodeModel.find_by_code(product_code) if product: product_subscription = ProductSubscriptionModel( org_id=org_id, product_code=product_code).save() subscriptions_model_list.append(product_subscription) else: raise BusinessException(Error.DATA_NOT_FOUND, None) if subscription.get('product_roles') is not None: for role in subscription.get('productRoles'): product_role_code = ProductRoleCodeModel.find_by_code_and_product_code( role, product_code) if product_role_code: ProductSubscriptionRoleModel( product_subscription_id=product_subscription.id, product_role_id=product_role_code.id).save() # TODO return something better/useful.may be return the whole model from db return subscriptions_model_list
async def process_event(event_message, flask_app): """Render the org status.""" if not flask_app: raise QueueException('Flask App not available.') with flask_app.app_context(): message_type = event_message.get('type', None) data = event_message.get('data') org_id = data.get('accountId') org: OrgModel = OrgModel.find_by_org_id(org_id) if org is None: logger.error('Unknown org for orgid %s', org_id) return if message_type == LOCK_ACCOUNT_MESSAGE_TYPE: org.status_code = OrgStatus.NSF_SUSPENDED.value org.suspended_on = datetime.now() await publish_mailer_events(LOCK_ACCOUNT_MESSAGE_TYPE, org_id) elif message_type == UNLOCK_ACCOUNT_MESSAGE_TYPE: org.status_code = OrgStatus.ACTIVE.value await publish_mailer_events(UNLOCK_ACCOUNT_MESSAGE_TYPE, org_id) else: logger.error('Unknown Message Type : %s', message_type) return org.flush() db.session.commit()
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)
def reset_password_for_anon_user(user_info: dict, user_name, token_info: Dict = None): """Reset the password of the user.""" user = UserModel.find_by_username(user_name) membership = MembershipModel.find_membership_by_userid(user.id) org_id = membership.org_id org = OrgModel.find_by_org_id(org_id) if not org or org.access_type != AccessType.ANONYMOUS.value: raise BusinessException(Error.INVALID_INPUT, None) check_auth(org_id=org_id, token_info=token_info, one_of_roles=(ADMIN, STAFF)) update_user_request = KeycloakUser() update_user_request.user_name = user_name.replace( IdpHint.BCROS.value + '/', '') update_user_request.password = user_info['password'] update_user_request.update_password_on_login() try: kc_user = KeycloakService.update_user(update_user_request) except HTTPError as err: current_app.logger.error('update_user in keycloak failed {}', err) raise BusinessException(Error.UNDEFINED_ERROR, err) return kc_user
def create_product_subscription(org_id, subscription_data: Dict[str, Any], is_new_transaction: bool = True): """Create product subscription for the user. create product subscription first create the product role next if roles are given """ org = OrgModel.find_by_org_id(org_id) if not org: raise BusinessException(Error.DATA_NOT_FOUND, None) subscriptions_list = subscription_data.get('subscriptions') # just used for returning all the models.. not ideal.. # todo remove this and may be return the subscriptions from db subscriptions_model_list = [] for subscription in subscriptions_list: product_code = subscription.get('productCode') product = ProductCodeModel.find_by_code(product_code) if product: product_subscription = ProductSubscriptionModel( org_id=org_id, product_code=product_code).flush() subscriptions_model_list.append(product_subscription) else: raise BusinessException(Error.DATA_NOT_FOUND, None) Product._create_roles(is_new_transaction, product_code, product_subscription, subscription) # TODO return something better/useful.may be return the whole model from db return subscriptions_model_list
def update_login_option(org_id, login_source): """Create a new contact for this org.""" # check for existing contact (only one contact per org for now) current_app.logger.debug('>update_login_option') org = OrgModel.find_by_org_id(org_id) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) check_auth(one_of_roles=ADMIN, org_id=org_id) existing_login_option = AccountLoginOptionsModel.find_active_by_org_id( org_id) if existing_login_option is not None: existing_login_option.is_active = False existing_login_option.add_to_session() login_option = AccountLoginOptionsModel(login_source=login_source, org_id=org_id) login_option.save() ActivityLogPublisher.publish_activity( Activity(org_id, ActivityAction.AUTHENTICATION_METHOD_CHANGE.value, name=org.name, value=login_source, id=login_option.id)) return login_option
def get_all_product_subscription(org_id, skip_auth=False): """Get a list of all products with their subscription details.""" org = OrgModel.find_by_org_id(org_id) if not org: raise BusinessException(Error.DATA_NOT_FOUND, None) # Check authorization for the user if not skip_auth: check_auth(one_of_roles=(*CLIENT_ADMIN_ROLES, STAFF), org_id=org_id) product_subscriptions: List[ ProductSubscriptionModel] = ProductSubscriptionModel.find_by_org_id( org_id) subscriptions_dict = { x.product_code: x.status_code for x in product_subscriptions } products = Product.get_products(include_hidden=False) for product in products: product['subscriptionStatus'] = subscriptions_dict.get( product.get('code'), ProductSubscriptionStatus.NOT_SUBSCRIBED.value) return products
async def test_update_internal_payment(app, session, stan_server, event_loop, client_id, events_stan, future): """Assert that the update internal payment records works.""" # Call back for the subscription from events_listener.worker import cb_subscription_handler events_subject = 'test_subject' events_queue = 'test_queue' events_durable_name = 'test_durable' org = factory_org_model() id = org.id # register the handler to test it await subscribe_to_queue(events_stan, events_subject, events_queue, events_durable_name, cb_subscription_handler) # add an event to queue await helper_add_event_to_queue(events_stan, events_subject, org_id=org.id, action='lock') # Get the internal account and invoice and assert that the identifier is new identifier new_org = OrgModel.find_by_org_id(id) assert new_org.status_code == 'NSF_SUSPENDED'
def change_org_status(org_id: int, status_code, suspension_reason_code, token_info: Dict = None): """Update the status of the org. Used now for suspending/activate account. 1) check access .only staff can do it now 2) check org status/eligiblity 3) suspend it """ current_app.logger.debug('<change_org_status ') org_model: OrgModel = OrgModel.find_by_org_id(org_id) user: UserModel = UserModel.find_by_jwt_token(token=token_info) current_app.logger.debug('<setting org status to ') org_model.status_code = status_code org_model.decision_made_by = user.username # not sure if a new field is needed for this. if status_code == OrgStatus.SUSPENDED.value: org_model.suspended_on = datetime.today() org_model.suspension_reason_code = suspension_reason_code org_model.save() current_app.logger.debug('change_org_status>') return Org(org_model)
def test_org_find_by_id(session): # pylint:disable=unused-argument """Assert that an Org can retrieved by its id.""" org = factory_org_model(name='My Test Org', session=session) session.add(org) session.commit() found_org = OrgModel.find_by_org_id(org.id) assert found_org assert found_org.name == org.name
def search_orgs(**kwargs): # pylint: disable=too-many-locals """Search for orgs based on input parameters.""" orgs = {'orgs': []} if kwargs.get('business_identifier', None): affiliation: AffiliationModel = AffiliationModel. \ find_affiliations_by_business_identifier(kwargs.get('business_identifier')) if affiliation: orgs['orgs'].append( Org(OrgModel.find_by_org_id(affiliation.org_id)).as_dict()) else: include_invitations: bool = False page: int = int(kwargs.get('page')) limit: int = int(kwargs.get('limit')) statuses: str = kwargs.get('statuses', None) name: str = kwargs.get('name', None) # https://github.com/bcgov/entity/issues/4786 access_type, is_staff_admin = Org.refine_access_type( kwargs.get('access_type', None), kwargs.get('token', None)) search_args = (access_type, name, statuses, kwargs.get('bcol_account_id', None), page, limit) if statuses and OrgStatus.PENDING_ACTIVATION.value in statuses: # only staff admin can see director search accounts # https://github.com/bcgov/entity/issues/4786 if not is_staff_admin: raise BusinessException(Error.INVALID_USER_CREDENTIALS, None) org_models, total = OrgModel.search_pending_activation_orgs( name) include_invitations = True else: org_models, total = OrgModel.search_org(*search_args) for org in org_models: org_dict = Org(org).as_dict() org_dict['contacts'] = [] org_dict['invitations'] = [] if org.contacts: org_dict['contacts'].append( ContactSchema(exclude=('links', )).dump( org.contacts[0].contact, many=False)) if include_invitations and org.invitations: org_dict['invitations'].append( InvitationSchema(exclude=('membership', )).dump( org.invitations[0].invitation, many=False)) orgs['orgs'].append(org_dict) orgs['total'] = total orgs['page'] = page orgs['limit'] = limit return orgs
def get_login_options_for_org(org_id, allowed_roles: Tuple = None): """Get the payment settings for the given org.""" current_app.logger.debug('get_login_options(>') org = OrgModel.find_by_org_id(org_id) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) # Check authorization for the user check_auth(one_of_roles=allowed_roles, org_id=org_id) return AccountLoginOptionsModel.find_active_by_org_id(org_id)
def search_orgs(**kwargs): """Search for orgs based on input parameters.""" orgs = {'orgs': []} if kwargs.get('business_identifier', None): affiliation: AffiliationModel = AffiliationModel. \ find_affiliations_by_business_identifier(kwargs.get('business_identifier')) if affiliation: orgs['orgs'].append( Org(OrgModel.find_by_org_id(affiliation.org_id)).as_dict()) return orgs
def _validate_and_throw_exception(memberships, org_id, single_mode): if single_mode: # make sure no bulk operation and only owner is created using if no auth if len(memberships) > 1 or memberships[0].get('membershipType') not in [ADMIN, COORDINATOR]: raise BusinessException(Error.INVALID_USER_CREDENTIALS, None) else: check_auth(org_id=org_id, one_of_roles=(COORDINATOR, ADMIN, STAFF)) # check if anonymous org ;these actions cannot be performed on normal orgs org = OrgModel.find_by_org_id(org_id) if not org or org.access_type != AccessType.ANONYMOUS.value: raise BusinessException(Error.INVALID_INPUT, None)
def create_user_and_add_membership(memberships: List[dict], org_id, token_info: Dict = None, skip_auth: bool = False): """ Create user(s) in the DB and upstream keycloak. accepts a list of memberships ie.a list of objects with username,password and membershipTpe skip_auth can be used if called method already perfomed the authenticaiton skip_auth= true is used now incase of invitation for admin users scenarion other cases should be invoked with skip_auth=false """ if skip_auth: # make sure no bulk operation and only owner is created using if no auth if len(memberships) > 1 or memberships[0].get('membershipType') not in [OWNER, ADMIN]: raise BusinessException(Error.INVALID_USER_CREDENTIALS, None) else: check_auth(org_id=org_id, token_info=token_info, one_of_roles=(ADMIN, OWNER)) # check if anonymous org ;these actions cannot be performed on normal orgs org = OrgModel.find_by_org_id(org_id) if not org or org.access_type != AccessType.ANONYMOUS.value: raise BusinessException(Error.INVALID_INPUT, None) current_app.logger.debug('create_user') users = [] for membership in memberships: create_user_request = KeycloakUser() current_app.logger.debug(f"create user username: {membership['username']}") create_user_request.first_name = membership['username'] create_user_request.user_name = membership['username'] create_user_request.password = membership['password'] create_user_request.enabled = True create_user_request.attributes = {'access_type': AccessType.ANONYMOUS.value} if membership.get('update_password_on_login', True): # by default , reset needed create_user_request.update_password_on_login() try: # TODO may be this method itself throw the business exception;can handle different exceptions? kc_user = KeycloakService.add_user(create_user_request) except HTTPError as err: current_app.logger.error('create_user in keycloak failed', err) raise BusinessException(Error.FAILED_ADDING_USER_IN_KEYCLOAK, None) username = IdpHint.BCROS.value + '/' + membership['username'] existing_user = UserModel.find_by_username(username) if existing_user: current_app.logger.debug('Existing users found in DB') raise BusinessException(Error.DATA_ALREADY_EXISTS, None) user_model: UserModel = UserModel(username=username, # BCROS is temporary value.Will be overwritten when user logs in is_terms_of_use_accepted=False, status=Status.ACTIVE.value, type=AccessType.ANONYMOUS.value, email=membership.get('email', None), firstname=kc_user.first_name, lastname=kc_user.last_name) user_model.save() User._add_org_membership(org_id, user_model.id, membership['membershipType']) users.append(User(user_model).as_dict()) return {'users': users}
def get_contacts(org_id): """Get the contacts for the given org.""" current_app.logger.debug('get_contacts>') org = OrgModel.find_by_org_id(org_id) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) collection = [] for contact_link in org.contacts: collection.append(ContactService(contact_link.contact).as_dict()) return {'contacts': collection}
def delete_contact(org_id): """Delete the contact for this org.""" current_app.logger.debug('>delete_contact ') org = OrgModel.find_by_org_id(org_id) if not org or not org.contacts: raise BusinessException(Error.DATA_NOT_FOUND, None) deleted_contact = Org.__delete_contact(org) current_app.logger.debug('<delete_contact ') return ContactService(deleted_contact)
def get_all_product_subscription(org_id, include_internal_products=True, token_info: Dict = None, skip_auth=False): """Get a list of all products with their subscription details.""" org = OrgModel.find_by_org_id(org_id) if not org: raise BusinessException(Error.DATA_NOT_FOUND, None) # Check authorization for the user if not skip_auth: check_auth(token_info, one_of_roles=(*CLIENT_ADMIN_ROLES, STAFF), org_id=org_id) product_subscriptions: List[ ProductSubscriptionModel] = ProductSubscriptionModel.find_by_org_id( org_id) subscriptions_dict = { x.product_code: x.status_code for x in product_subscriptions } # We only want to return products that have content configured, # so read configuration and merge merged_product_infos = [] products_config = current_app.config.get('PRODUCT_CONFIG') products: List[ProductCodeModel] = ProductCodeModel.get_all_products() if products: for product in products: if not include_internal_products and product.type_code == ProductTypeCode.INTERNAL.value: continue product_config = products_config.get(product.code) if product_config: merged_product_infos.append({ 'code': product.code, 'name': product.description, 'description': product_config.get('description'), 'url': product_config.get('url'), 'type': product.type_code, 'mdiIcon': product_config.get('mdiIcon'), 'subscriptionStatus': subscriptions_dict.get( product.code, ProductSubscriptionStatus.NOT_SUBSCRIBED.value) }) return merged_product_infos
def find_by_org_id(org_id, allowed_roles: Tuple = None): """Find and return an existing organization with the provided id.""" if org_id is None: return None org_model = OrgModel.find_by_org_id(org_id) if not org_model: return None # Check authorization for the user check_auth(one_of_roles=allowed_roles, org_id=org_id) return Org(org_model)
def add_login_option(org_id, login_source, token_info: Dict = None): """Create a new contact for this org.""" # check for existing contact (only one contact per org for now) current_app.logger.debug('>add_login_option') org = OrgModel.find_by_org_id(org_id) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) check_auth(token_info, one_of_roles=ADMIN, org_id=org_id) login_option = AccountLoginOptionsModel(login_source=login_source, org_id=org_id) login_option.save() return login_option
def _update_relationship(self, origin_url: str = None): """Retrieve the relationship record and update the status.""" task_model: TaskModel = self._model current_app.logger.debug('<update_task_relationship ') is_approved: bool = task_model.relationship_status == TaskRelationshipStatus.ACTIVE.value is_hold: bool = task_model.status == TaskStatus.HOLD.value if task_model.relationship_type == TaskRelationshipType.ORG.value: # Update Org relationship org_id = task_model.relationship_id if not is_hold: self._update_org(is_approved=is_approved, org_id=org_id, origin_url=origin_url, task_action=task_model.action) else: # Task with ACCOUNT_REVIEW action cannot be put on hold if task_model.action != TaskAction.AFFIDAVIT_REVIEW.value: raise BusinessException(Error.INVALID_INPUT, None) # no updates on org yet.put the task on hold and send mail to user org: OrgModel = OrgModel.find_by_org_id(org_id) # send on-hold mail notification Task._notify_admin_about_hold(task_model, org=org) # TODO Update user.verified flag elif task_model.relationship_type == TaskRelationshipType.PRODUCT.value: # Update Product relationship product_subscription_id = task_model.relationship_id account_id = task_model.account_id self._update_product_subscription(is_approved=is_approved, product_subscription_id=product_subscription_id, org_id=account_id) elif task_model.relationship_type == TaskRelationshipType.USER.value: user_id = task_model.relationship_id if not is_hold: self._update_bceid_admin(is_approved=is_approved, user_id=user_id) else: user: UserModel = UserModel.find_by_id(user_id) membership = MembershipModel.find_membership_by_userid(user_id) # Send mail to admin about hold with reasons Task._notify_admin_about_hold(user=user, task_model=task_model, is_new_bceid_admin_request=True, membership_id=membership.id) # If action is affidavit review, mark the user as verified. if is_approved and task_model.action == TaskAction.AFFIDAVIT_REVIEW.value and task_model.user: task_model.user.verified = True task_model.user.save() current_app.logger.debug('>update_task_relationship ')
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)
def get_members_for_org( org_id, status=Status.ACTIVE.name, # pylint:disable=too-many-return-statements membership_roles=ALL_ALLOWED_ROLES, **kwargs): """Get members of org.Fetches using status and roles.""" org_model = OrgModel.find_by_org_id(org_id) if not org_model: return None user_from_context: UserContext = kwargs['user_context'] status = Status.ACTIVE.value if status is None else Status[status].value membership_roles = ALL_ALLOWED_ROLES if membership_roles is None else membership_roles # If staff return full list if user_from_context.is_staff(): return MembershipModel.find_members_by_org_id_by_status_by_roles( org_id, membership_roles, status) current_user: UserService = UserService.find_by_jwt_token() current_user_membership: MembershipModel = \ MembershipModel.find_membership_by_user_and_org(user_id=current_user.identifier, org_id=org_id) # If no active or pending membership return empty array if current_user_membership is None or \ current_user_membership.status == Status.INACTIVE.value or \ current_user_membership.status == Status.REJECTED.value: return [] # If pending approval, return empty for active, array of self only for pending if current_user_membership.status == Status.PENDING_APPROVAL.value: return [current_user_membership ] if status == Status.PENDING_APPROVAL.value else [] # If active status for current user, then check organizational role if current_user_membership.status == Status.ACTIVE.value: if current_user_membership.membership_type_code in (ADMIN, COORDINATOR): return MembershipModel.find_members_by_org_id_by_status_by_roles( org_id, membership_roles, status) return MembershipModel.find_members_by_org_id_by_status_by_roles(org_id, membership_roles, status) \ if status == Status.ACTIVE.value else [] return []
def get_members_for_org( org_id, status=Status.ACTIVE, # pylint:disable=too-many-return-statements membership_roles=ALL_ALLOWED_ROLES, token_info: Dict = None): """Get members of org.Fetches using status and roles.""" org_model = OrgModel.find_by_org_id(org_id) if not org_model: return None status = Status.ACTIVE.value if status is None else Status[status].value membership_roles = ALL_ALLOWED_ROLES if membership_roles is None else membership_roles # If staff return full list if 'staff' in token_info.get('realm_access').get('roles'): return MembershipModel.find_members_by_org_id_by_status_by_roles( org_id, membership_roles, status) current_user: UserService = UserService.find_by_jwt_token(token_info) current_user_membership: MembershipModel = \ MembershipModel.find_membership_by_user_and_org(user_id=current_user.identifier, org_id=org_id) # If no active or pending membership return empty array if current_user_membership is None or \ current_user_membership.status == Status.INACTIVE.value or \ current_user_membership.status == Status.REJECTED.value: return [] # If pending approval, return empty for active, array of self only for pending if current_user_membership.status == Status.PENDING_APPROVAL.value: return [current_user_membership ] if status == Status.PENDING_APPROVAL.value else [] # If active status for current user, then check organizational role if current_user_membership.status == Status.ACTIVE.value: if current_user_membership.membership_type_code == ADMIN or \ current_user_membership.membership_type_code == COORDINATOR: return MembershipModel.find_members_by_org_id_by_status_by_roles( org_id, membership_roles, status) return MembershipModel.find_members_by_org_id_by_status_by_roles(org_id, membership_roles, status) \ if status == Status.ACTIVE.value else [] return []
def update_contact(org_id, contact_info): """Update the existing contact for this org.""" current_app.logger.debug('>update_contact ') org = OrgModel.find_by_org_id(org_id) if org is None: raise BusinessException(Error.DATA_NOT_FOUND, None) # find the contact link for this org contact_link = ContactLinkModel.find_by_org_id(org_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.save() current_app.logger.debug('<update_contact ') # return the updated contact return ContactService(contact)
def search_orgs(**kwargs): """Search for orgs based on input parameters.""" orgs = {'orgs': []} if kwargs.get('business_identifier', None): affiliation: AffiliationModel = AffiliationModel. \ find_affiliations_by_business_identifier(kwargs.get('business_identifier')) if affiliation: orgs['orgs'].append( Org(OrgModel.find_by_org_id(affiliation.org_id)).as_dict()) elif kwargs.get('org_type', None): org_models = OrgModel.find_by_org_access_type( kwargs.get('org_type')) for org in org_models: orgs['orgs'].append(Org(org).as_dict()) elif kwargs.get('name', None): org_model = OrgModel.find_similar_org_by_name(kwargs.get('name')) if org_model is not None: orgs['orgs'].append(Org(org_model).as_dict()) return orgs
def get_members_for_org(org_id, status=None, membership_roles=None, token_info: Dict = None, allowed_roles: Tuple = None): """Get members of org.Fetches using status and roles.""" if org_id is None: return None if membership_roles is None: membership_roles = ALL_ALLOWED_ROLES if not status: status = Status.ACTIVE.value else: status = Status[status].value org_model = OrgModel.find_by_org_id(org_id) if not org_model: return None # Check authorization for the user check_auth(token_info, one_of_roles=allowed_roles, org_id=org_id) return MembershipModel.find_members_by_org_id_by_status_by_roles(org_id, membership_roles, status)