"""User Logic.""" from ddtrace import tracer from grass.consts.user import AccountTypes, UserGroups from grass.models import oa_user, workstation_user @tracer.wrap() def get_user_by_id(user_id, namespace=None): """Get a user by its id. Args: user_id (int): the user id. namespace (str): the namespace attached to the user id. Returns: User, status: the user information and the status. If the user does not exist, a 404 is returned. """ if namespace: assert namespace == UserGroups.ALW, 'For now only alw is allowed.' if user_id.startswith('alw'): return workstation_user.get_workstation_user_by_id(user_id) elif user_id.startswith('oa'): return oa_user.get_oa_user_by_id(user_id) raise (ValueError(f'User id ({user_id}) must be namespaced')) @tracer.wrap() def get_linked_accounts(user_id, auth0_user_id): """Get linked accounts. Args: user_id (int): the user id. auth0_user_id (str): the auth0 user id. Returns: list: of linked accounts """ return workstation_user.get_linked_account_details(user_id, auth0_user_id) def is_user_vendor(user): """Check if a user is a vendor. Returns: bool: if the user is a label. """ return user.account_type == AccountTypes.VENDOR def is_user_subaccount(user): """Check if a user is a subaccount. Returns: bool: if the user is a subaccount. """ return user.account_type == AccountTypes.SUBACCOUNT @tracer.wrap() def is_allowed_for_any_resources(user_id, resource_names): """Check if a user is allowed for any of the passed in resources. Args: user_id (int): the user id. resource_name (str): the name of the resource. Returns: bool: if the user is allowed to access this particular resource. """ if not resource_names: return True for resource_name in resource_names: if is_allowed_for_resource(user_id, resource_name): return True return False @tracer.wrap() def is_allowed_for_resource(user_id, resource_name): """Check if a user is allowed for a specific resource. Args: user_id (int): the user id. resource_name (str): the name of the resource. Returns: bool: if the user is allowed to access this particular resource. """ if user_id.startswith('alw:'): results = workstation_user.get_resource_privileges_for_user( user_id, resource_name ) return bool(results) if user_id.startswith('oa:'): results = oa_user.get_resource_privileges_for_user(user_id, resource_name) return bool(results) return False @tracer.wrap() def is_group_member(user_id, groups): """Check if a user is a member of the groups. Args: user_id (str): the user id. groups (list): the list of groups. Returns: bool: if the user is a member of one of the groups. """ for group in groups: if user_id.startswith(group): return True return False