def ensure_grant(self, grantee_slug, priv_slug, dry_run=False): """ Adds a parameterless grant between grantee and priv, looked up by slug. """ if dry_run: grants = Grant.objects.filter(from_role__slug=grantee_slug, to_role__slug=priv_slug) if not grants: logger.info('[DRY RUN] Granting privilege: %s => %s', grantee_slug, priv_slug) else: grantee = Role.objects.get(slug=grantee_slug) priv = Role.objects.get(slug=priv_slug) Role.get_cache().clear() if grantee.has_privilege(priv): if self.verbose: logger.info('Privilege already granted: %s => %s', grantee.slug, priv.slug) else: if self.verbose: logger.info('Granting privilege: %s => %s', grantee.slug, priv.slug) Grant.objects.create( from_role=grantee, to_role=priv, )
def setUpClass(cls): super(APIResourceTest, cls).setUpClass() Role.get_cache().clear() cls.domain = Domain.get_or_create_with_name('qwerty', is_active=True) cls.list_endpoint = cls._get_list_endpoint() cls.username = '******' cls.password = '******' cls.user = WebUser.create(cls.domain.name, cls.username, cls.password, None, None, email='*****@*****.**', first_name='rudolph', last_name='commcare') cls.user.set_role(cls.domain.name, 'admin') cls.user.save() cls.account = BillingAccount.get_or_create_account_by_domain( cls.domain.name, created_by="automated-test")[0] plan = DefaultProductPlan.get_default_plan_version( edition=SoftwarePlanEdition.ADVANCED) cls.subscription = Subscription.new_domain_subscription( cls.account, cls.domain.name, plan) cls.subscription.is_active = True cls.subscription.save() cls.api_key, _ = HQApiKey.objects.get_or_create( user=WebUser.get_django_user(cls.user))
def setUp(self): self.domain_name = 'test' self.password = "******" username = "******" email = "*****@*****.**" self.client = Client() self.user = WebUser.create(self.domain_name, username, self.password, email, is_admin=True) self.url = '/a/{}/data/edit/archive_forms/'.format(self.domain_name) django_user = self.user.get_django_user() try: self.user_role = UserRole.objects.get(user=django_user) except UserRole.DoesNotExist: user_privs = Role.objects.get_or_create( name="Privileges for %s" % django_user.username, slug="%s_privileges" % django_user.username, )[0] self.user_role = UserRole.objects.create( user=django_user, role=user_privs, ) # Setup default roles and plans generator.instantiate_accounting_for_tests() self.bulk_role = Role.objects.filter(slug=privileges.BULK_CASE_MANAGEMENT)[0] Grant.objects.create(from_role=self.user_role.role, to_role=self.bulk_role) Role.get_cache().clear() self.client.login(username=self.user.username, password=self.password) toggles.BULK_ARCHIVE_FORMS.set(self.user.username, True)
def setUp(self): self.client = Client() self.url = '/a/{}/data/edit/archive_forms/'.format(DOMAIN_NAME) Grant.objects.get_or_create(from_role=self.user_role.role, to_role=self.bulk_role) Role.get_cache().clear() self.client.login(username=self.user.username, password=self.password)
def setUpClass(cls): super(ChangeRoleForSoftwarePlanVersionTest, cls).setUpClass() cls.generic_product_rate = SoftwareProductRate.new_rate( 'product', Decimal('0.0')) cls.generic_product_rate.save() cls.old_role = Role(slug='old_role', name='old') cls.old_role.save() cls.new_role = Role(slug='new_role', name='new') cls.new_role.save()
def setUpClass(cls): super(RegistrationAPITestCase, cls).setUpClass() Role.get_cache().clear() cls.domain1, cls.account1, cls.subscription1 = cls.setup_domain('reg-api-test-1') cls.domain2, cls.account2, cls.subscription2 = cls.setup_domain('reg-api-test-2') cls.admin_user1 = cls.setup_webuser('admin@reg-api-test-1', cls.domain1, 'admin') cls.read_only_user1 = cls.setup_webuser('readonly@reg-api-test-1', cls.domain1, 'read-only') cls.admin_user2 = cls.setup_webuser('admin@reg-api-test-2', cls.domain2, 'admin')
def setUpClass(cls): Role.get_cache().clear() generator.instantiate_accounting_for_tests() cls.domain = Domain.get_or_create_with_name("qwerty", is_active=True) cls.list_endpoint = reverse( "api_dispatch_list", kwargs=dict(domain=cls.domain.name, api_name=cls.api_name, resource_name=cls.resource.Meta.resource_name), ) cls.username = "******" cls.password = "******" cls.user = WebUser.create(cls.domain.name, cls.username, cls.password) cls.user.set_role(cls.domain.name, "admin") cls.user.save() set_up_subscription(cls) cls.domain = Domain.get(cls.domain._id)
def setUpClass(cls): Role.get_cache().clear() generator.instantiate_accounting_for_tests() cls.domain = Domain.get_or_create_with_name("qwerty", is_active=True) cls.username = "******" cls.password = "******" cls.admin_user = WebUser.create(cls.domain.name, cls.username, cls.password) cls.admin_user.set_role(cls.domain.name, "admin") cls.admin_user.save() cls.fake_user_es = FakeUserES() v0_5.MOCK_BULK_USER_ES = cls.mock_es_wrapper cls.make_users() set_up_subscription(cls) cls.domain = Domain.get(cls.domain._id)
def apply_prbac(cls, request): if hasattr(request, 'domain'): try: plan_version, subscription = Subscription.get_subscribed_plan_by_domain(request.domain) request.role = plan_version.role request.plan = plan_version request.subscription = subscription return None except AccountingError: pass privilege = Role.get_privilege('community_plan_v1') if privilege is not None: request.role = privilege.role else: request.role = Role() # A fresh Role() has no privileges
def test_bulk_archive_get_form(self): # Logged in response = self.client.get(self.url) self.assertEqual(response.status_code, 200) self.assertEqual( response.context["bulk_upload"]["download_url"], "/static/data_interfaces/files/forms_bulk_example.xlsx" ) grant = Grant.objects.get(from_role=self.user_role.role, to_role=self.bulk_role) grant.delete() Role.get_cache().clear() # Revoked privileges should not render form response = self.client.get(self.url) self.assertFalse("bulk_upload" in response.context)
def is_accounting_admin(user): accounting_privilege = Role.get_privilege(privileges.ACCOUNTING_ADMIN) if accounting_privilege is None: return False try: return user.prbac_role.has_privilege(accounting_privilege) except (AttributeError, UserRole.DoesNotExist): return False
def test_bulk_archive_get_form(self): # Logged in response = self.client.get(self.url) self.assertEqual(response.status_code, 200) self.assertEqual( response.context['bulk_upload']['download_url'], '/static/data_interfaces/xlsx/forms_bulk_example.xlsx') grant = Grant.objects.get(from_role=self.user_role.role, to_role=self.bulk_role) grant.delete() Role.get_cache().clear() # Revoked privileges should not render form response = self.client.get(self.url) self.assertFalse('bulk_upload' in response.context)
def ensure_grants(grants_to_privs, dry_run=False, verbose=False, roles_by_slug=None): """ Adds a parameterless grant between grantee and priv, looked up by slug. :param grants_to_privs: An iterable of two-tuples: `(grantee_slug, priv_slugs)`. Will only be iterated once. """ dry_run_tag = "[DRY RUN] " if dry_run else "" if roles_by_slug is None: roles_by_slug = {role.slug: role for role in Role.objects.all()} granted = defaultdict(set) for grant in Grant.objects.select_related('from_role', 'to_role').all(): granted[grant.from_role.slug].add(grant.to_role.slug) grants_to_create = [] for grantee_slug, priv_slugs in grants_to_privs: if grantee_slug not in roles_by_slug: logger.info('grantee %s does not exist.', grantee_slug) continue for priv_slug in priv_slugs: if priv_slug not in roles_by_slug: logger.info('privilege %s does not exist.', priv_slug) continue if priv_slug in granted[grantee_slug]: if verbose or dry_run: logger.info('%sPrivilege already granted: %s => %s', dry_run_tag, grantee_slug, priv_slug) else: granted[grantee_slug].add(priv_slug) if verbose or dry_run: logger.info('%sGranting privilege: %s => %s', dry_run_tag, grantee_slug, priv_slug) if not dry_run: grants_to_create.append( Grant(from_role=roles_by_slug[grantee_slug], to_role=roles_by_slug[priv_slug])) if grants_to_create: Role.get_cache().clear() Grant.objects.bulk_create(grants_to_create)
def test_specified_priv_for_grantee_is_revoked(self): privs_to_revoke_for_grantee = [('grantee', ['privilege'])] roles_by_slug = { 'grantee': Role(slug='grantee'), 'privilege': Role(slug='privilege'), } expected_grants = [ Grant(from_role=Role(slug='grantee'), to_role=Role(slug='privilege')) ] with patch('corehq.apps.accounting.utils.get_all_roles_by_slug', return_value=roles_by_slug),\ patch('corehq.apps.accounting.utils.get_grants', return_value=expected_grants),\ patch('corehq.apps.accounting.utils.delete_grants') as mock_deletegrants: revoke_privs_for_grantees(privs_to_revoke_for_grantee) mock_deletegrants.assert_called_with(expected_grants)
def setUpClass(cls): super(APIResourceTest, cls).setUpClass() Role.get_cache().clear() cls.domain = Domain.get_or_create_with_name('qwerty', is_active=True) cls.list_endpoint = cls._get_list_endpoint() cls.username = '******' cls.password = '******' cls.user = WebUser.create(cls.domain.name, cls.username, cls.password) cls.user.set_role(cls.domain.name, 'admin') cls.user.save() cls.account = BillingAccount.get_or_create_account_by_domain(cls.domain.name, created_by="automated-test")[0] plan = DefaultProductPlan.get_default_plan_version(edition=SoftwarePlanEdition.ADVANCED) cls.subscription = Subscription.new_domain_subscription(cls.account, cls.domain.name, plan) cls.subscription.is_active = True cls.subscription.save() cls.api_key, _ = ApiKey.objects.get_or_create(user=WebUser.get_django_user(cls.user))
def ensure_grant(grantee_slug, priv_slug, dry_run=False, verbose=False): """ Adds a parameterless grant between grantee and priv, looked up by slug. """ try: grantee = Role.objects.get(slug=grantee_slug) except Role.DoesNotExist: logger.info( '[DRY RUN] grantee {} does not exist.'.format(grantee_slug)) return try: priv = Role.objects.get(slug=priv_slug) except Role.DoesNotExist: logger.info('[DRY RUN] privilege {} does not exist.'.format(priv_slug)) return if dry_run: grants = Grant.objects.filter(from_role__slug=grantee_slug, to_role__slug=priv_slug) if not grants: logger.info('[DRY RUN] Granting privilege: %s => %s', grantee_slug, priv_slug) if grantee.has_privilege(priv): if verbose: logger.info('[DRY RUN] Privilege already granted: %s => %s', grantee.slug, priv.slug) else: Role.get_cache().clear() if grantee.has_privilege(priv): if verbose: logger.info('Privilege already granted: %s => %s', grantee.slug, priv.slug) else: if verbose: logger.info('Granting privilege: %s => %s', grantee.slug, priv.slug) Grant.objects.create( from_role=grantee, to_role=priv, )
def ensure_grants(grants_to_privs, dry_run=False, verbose=False, roles_by_slug=None): """ Adds a parameterless grant between grantee and priv, looked up by slug. :param grants_to_privs: An iterable of two-tuples: `(grantee_slug, priv_slugs)`. Will only be iterated once. """ dry_run_tag = "[DRY RUN] " if dry_run else "" if roles_by_slug is None: roles_by_slug = {role.slug: role for role in Role.objects.all()} granted = defaultdict(set) for grant in Grant.objects.select_related('from_role', 'to_role').all(): granted[grant.from_role.slug].add(grant.to_role.slug) grants_to_create = [] for grantee_slug, priv_slugs in grants_to_privs: if grantee_slug not in roles_by_slug: logger.info('grantee %s does not exist.', grantee_slug) continue for priv_slug in priv_slugs: if priv_slug not in roles_by_slug: logger.info('privilege %s does not exist.', priv_slug) continue if priv_slug in granted[grantee_slug]: if verbose or dry_run: logger.info('%sPrivilege already granted: %s => %s', dry_run_tag, grantee_slug, priv_slug) else: granted[grantee_slug].add(priv_slug) if verbose or dry_run: logger.info('%sGranting privilege: %s => %s', dry_run_tag, grantee_slug, priv_slug) if not dry_run: grants_to_create.append(Grant( from_role=roles_by_slug[grantee_slug], to_role=roles_by_slug[priv_slug] )) if grants_to_create: Role.get_cache().clear() Grant.objects.bulk_create(grants_to_create)
def ensure_grants(privs_to_ensure_for_grantee, dry_run=False, verbose=False, roles_by_slug=None): """ Adds a parameterless grant between grantee and priv, looked up by slug. :param privs_to_ensure_for_grantee: An iterable of tuples: `(grantee_slug, [priv_slugs])` :param dry_run: if True, will not make any changes to the DB :param verbose: if True, will log additional output :param roles_by_slug: can specify your own roles to consider, otherwise will fetch all Role objects """ dry_run_tag = "[DRY RUN] " if dry_run else "" roles_by_slug = roles_by_slug or get_all_roles_by_slug() granted_privs_for_grantee = get_granted_privs_for_grantee() grants_to_create = [] for grantee_slug, priv_slugs in privs_to_ensure_for_grantee: if grantee_slug not in roles_by_slug: logger.info('grantee %s does not exist.', grantee_slug) continue for priv_slug in priv_slugs: if priv_slug not in roles_by_slug: logger.info('privilege %s does not exist.', priv_slug) continue if priv_slug in granted_privs_for_grantee[grantee_slug]: if verbose or dry_run: logger.info('%sPrivilege already granted: %s => %s', dry_run_tag, grantee_slug, priv_slug) else: granted_privs_for_grantee[grantee_slug].add(priv_slug) if verbose or dry_run: logger.info('%sGranting privilege: %s => %s', dry_run_tag, grantee_slug, priv_slug) if not dry_run: grants_to_create.append( Grant(from_role=roles_by_slug[grantee_slug], to_role=roles_by_slug[priv_slug])) if grants_to_create: Role.get_cache().clear() Grant.objects.bulk_create(grants_to_create)
def test_privilege_already_revoked(self): privs_to_revoke_for_grantee = [('grantee', ['privilege'])] roles_by_slug = { 'grantee': Role(slug='grantee'), 'privilege': Role(slug='privilege'), } expected_grants = [] with patch('corehq.apps.accounting.utils.get_all_roles_by_slug', return_value=roles_by_slug),\ patch('corehq.apps.accounting.utils.get_grants', return_value=expected_grants),\ patch('corehq.apps.accounting.utils.logger.info') as mock_logger,\ patch('corehq.apps.accounting.utils.delete_grants') as mock_deletegrants: # only triggers message if verbose is true revoke_privs_for_grantees(privs_to_revoke_for_grantee, verbose=True) mock_logger.assert_called_with( 'Privilege already revoked: grantee => privilege') mock_deletegrants.assert_not_called()
def test_privilege_does_not_exist(self): privs_to_revoke_for_grantee = [('grantee', ['privilege'])] roles_by_slug = {'grantee': Role(slug='grantee')} with patch('corehq.apps.accounting.utils.get_all_roles_by_slug', return_value=roles_by_slug),\ patch('corehq.apps.accounting.utils.logger.info') as mock_logger,\ patch('corehq.apps.accounting.utils.delete_grants') as mock_deletegrants: revoke_privs_for_grantees(privs_to_revoke_for_grantee) mock_logger.assert_called_with('privilege privilege does not exist.') mock_deletegrants.assert_not_called()
def ensure_grant(grantee_slug, priv_slug, dry_run=False, verbose=False): """ Adds a parameterless grant between grantee and priv, looked up by slug. """ try: grantee = Role.objects.get(slug=grantee_slug) except Role.DoesNotExist: logger.info('[DRY RUN] grantee {} does not exist.'.format(grantee_slug)) return try: priv = Role.objects.get(slug=priv_slug) except Role.DoesNotExist: logger.info('[DRY RUN] privilege {} does not exist.'.format(priv_slug)) return if dry_run: grants = Grant.objects.filter(from_role__slug=grantee_slug, to_role__slug=priv_slug) if not grants: logger.info('[DRY RUN] Granting privilege: %s => %s', grantee_slug, priv_slug) if grantee.has_privilege(priv): if verbose: logger.info('[DRY RUN] Privilege already granted: %s => %s', grantee.slug, priv.slug) else: Role.get_cache().clear() if grantee.has_privilege(priv): if verbose: logger.info('Privilege already granted: %s => %s', grantee.slug, priv.slug) else: if verbose: logger.info('Granting privilege: %s => %s', grantee.slug, priv.slug) Grant.objects.create( from_role=grantee, to_role=priv, )
def domain_has_privilege(domain, privilege_slug, **assignment): from corehq.apps.accounting.models import Subscription try: plan_version = Subscription.get_subscribed_plan_by_domain(domain)[0] privilege = Role.get_privilege(privilege_slug, assignment) if privilege is None: return False if plan_version.role.has_privilege(privilege): return True except ProductPlanNotFoundError: return False except AccountingError: pass return False
def process_request(cls, request): if hasattr(request, 'domain'): try: plan_version, subscription = Subscription.get_subscribed_plan_by_domain(request.domain) request.role = plan_version.role request.plan = plan_version request.subscription = subscription return None except AccountingError: pass try: request.role = Role.objects.get(slug='community_plan_v0') except Role.DoesNotExist: request.role = Role() # A fresh Role() has no privileges
def _create_new_role_from_role(from_role, new_role_slug, new_role_name, privilege_to_add, dry_run=False): """ :param from_role: Role object of existing role to copy :param new_role_slug: str object that is new slug (unique) :param new_role_name: str object that is new name :param privilege_to_add: Role object of privilege to add to new role via Grant :return: new role object """ dry_run_tag = '[DRY_RUN]' if dry_run else '' new_role = Role(slug=new_role_slug, name=new_role_name) if not dry_run: new_role.save() _copy_existing_grants(from_role, new_role) # add new grant Grant.objects.create(from_role=new_role, to_role=privilege_to_add) logger.info(f""" {dry_run_tag}Created new role {new_role.slug} from existing role {from_role.slug} with privilege {privilege_to_add.slug}. """) return new_role
def apply_prbac(cls, request): if hasattr(request, 'domain'): try: plan_version, subscription = Subscription.get_subscribed_plan_by_domain(request.domain) request.role = plan_version.role request.plan = plan_version request.subscription = subscription return None except AccountingError: pass privilege = Role.get_privilege('community_plan_v0') if privilege is not None: request.role = privilege.role else: request.role = Role() # A fresh Role() has no privileges
def has_privilege(request, slug, **assignment): """ Returns true if the request has the privilege specified by slug, otherwise false """ privilege = Role.get_privilege(slug, assignment) if privilege is None: return False if hasattr(request, 'role'): if request.role.has_privilege(privilege): return True if hasattr(request, 'user') and hasattr(request.user, 'prbac_role'): try: request.user.prbac_role except UserRole.DoesNotExist: return False return request.user.prbac_role.has_privilege(privilege) return False
def setUp(self): Role.get_cache().clear() self.zazzle_privilege = arbitrary.role(slug=arbitrary.unique_slug('zazzle'), parameters=set(['domain']))
def setUp(self): Role.get_cache().clear()
class Command(BaseCommand): help = 'Populate a fresh database with some sample roles and grants' def add_arguments(self, parser): parser.add_argument( '--dry-run', action='store_true', default=False, help= 'Do not actually modify the database, just verbosely log what happen', ) parser.add_argument( '--verbose', action='store_true', default=False, help='Enable debug output', ) parser.add_argument( '--fresh-start', action='store_true', default=False, help= 'We changed the core v0 plans, wipe all existing plans and start over. USE CAUTION.', ) def handle(self, dry_run=False, verbose=False, fresh_start=False, **options): self.verbose = verbose if fresh_start: confirm_fresh_start = input( "Are you sure you want to delete all Roles and start over? You can't do this" " if accounting is already set up. Type 'yes' to continue.") if confirm_fresh_start == 'yes': self.flush_roles() self.roles_by_slug = {role.slug: role for role in Role.objects.all()} self.ensure_roles(self.BOOTSTRAP_PRIVILEGES + self.BOOTSTRAP_PLANS, dry_run) ensure_grants( list(self.BOOTSTRAP_GRANTS.items()), # py3 iterable dry_run=dry_run, verbose=self.verbose, roles_by_slug=self.roles_by_slug, ) if verbose or dry_run: log_removed_grants(self.OLD_PRIVILEGES, dry_run=dry_run) if not dry_run: Role.objects.filter(slug__in=self.OLD_PRIVILEGES).delete() def flush_roles(self): logger.info('Flushing ALL Roles...') Role.objects.all().delete() def ensure_roles(self, roles, dry_run=False): """ Add each role if it does not already exist, otherwise skip it. """ dry_run_tag = "[DRY RUN] " if dry_run else "" roles_to_save = [] for role in roles: if role.slug not in self.roles_by_slug: if self.verbose or dry_run: logger.info('%sCreating role: %s', dry_run_tag, role.name) if not dry_run: roles_to_save.append(role) else: logger.info('Role already exists: %s', role.name) if roles_to_save: roles = Role.objects.bulk_create(roles_to_save) self.roles_by_slug.update((role.slug, role) for role in roles) BOOTSTRAP_PRIVILEGES = [ Role(slug=privileges.API_ACCESS, name='API Access', description=''), Role(slug=privileges.LOOKUP_TABLES, name='Lookup Tables', description=''), Role(slug=privileges.CLOUDCARE, name='Web-based Applications (CloudCare)', description=''), Role(slug=privileges.CUSTOM_BRANDING, name='Custom Branding', description=''), Role(slug=privileges.ACTIVE_DATA_MANAGEMENT, name='Active Data Management', description=''), Role(slug=privileges.CUSTOM_REPORTS, name='Custom Reports', description=''), Role(slug=privileges.ROLE_BASED_ACCESS, name='Role-based Access', description=''), Role(slug=privileges.RESTRICT_ACCESS_BY_LOCATION, name='Restrict Access By Location', description=''), Role( slug=privileges.OUTBOUND_SMS, name='Outbound SMS', description='Use of any outbound messaging / SMS services.', ), Role( slug=privileges.REMINDERS_FRAMEWORK, name='Rules Engine (Use of Reminders Framework)', description= 'Use of reminders framework for spawning reminders/alerts based on certain criteria.', ), Role( slug=privileges.CUSTOM_SMS_GATEWAY, name='Custom Telerivet (Android) SMS Gateway', description= 'Ability to set up telerivet gateway on the "SMS Connectivity" page (inbound or outbound).', ), Role(slug=privileges.INBOUND_SMS, name='Inbound SMS (where available)', description=''), Role(slug=privileges.BULK_CASE_MANAGEMENT, name='Bulk Case Management', description=''), Role(slug=privileges.BULK_USER_MANAGEMENT, name='Bulk User Management', description=''), Role(slug=privileges.DEIDENTIFIED_DATA, name='De-identified Data', description=''), Role(slug=privileges.HIPAA_COMPLIANCE_ASSURANCE, name='HIPAA Compliance Assurance', description=''), Role(slug=privileges.ALLOW_EXCESS_USERS, name='Can Add Users Above Limit', description=''), Role(slug=privileges.COMMCARE_LOGO_UPLOADER, name='Custom CommCare Logo Uploader', description=''), Role(slug=privileges.LOCATIONS, name='Locations', description=''), Role(slug=privileges.REPORT_BUILDER, name='User Configurable Report Builder', description=''), Role(slug=privileges.REPORT_BUILDER_TRIAL, name='Report Builder Trial', description=''), Role(slug=privileges.REPORT_BUILDER_5, name='Report Builder, 5 report limit', description=''), Role(slug=privileges.REPORT_BUILDER_15, name='Report Builder, 15 report limit', description=''), Role(slug=privileges.REPORT_BUILDER_30, name='Report Builder, 30 report limit', description=''), Role(slug=privileges.USERCASE, name='User Case Management', description=''), Role( slug=privileges.DATA_CLEANUP, name='Data Management', description= 'Tools for cleaning up data, including editing submissions and archiving forms.' ), Role(slug=privileges.TEMPLATED_INTENTS, name='Templated Intents', description='Provides a dropdown for Android App Callouts'), Role(slug=privileges.CUSTOM_INTENTS, name='Custom Intents', description='Allows for specifying custom intents'), Role(slug=privileges.ADVANCED_DOMAIN_SECURITY, name='Advanced Domain Security', description= 'Allows domains to set security policies for all web users'), Role( slug=privileges.PRACTICE_MOBILE_WORKERS, name='Practice mode for mobile workers', description= 'Allows turning on practice mode for mobile workers and link them to applications' ), Role( slug=privileges.BUILD_PROFILES, name='Application Profiles', description= 'Allows domains to create application profiles to customize app deploys' ), Role( slug=privileges.EXCEL_DASHBOARD, name="Excel Dashbord", description="Allows domains to create Excel dashboard html exports" ), Role(slug=privileges.DAILY_SAVED_EXPORT, name='DAILY_SAVED_EXPORT', description="Allows domains to create Daily Saved Exports"), Role( slug=privileges.ZAPIER_INTEGRATION, name='Zapier Integration', description='Allows domains to use zapier (zapier.com) integration' ), Role(slug=privileges.LOGIN_AS, name='Login As for App Preview', description= 'Allows domains to use the login as feature of app preview'), Role(slug=privileges.CASE_SHARING_GROUPS, name='Case Sharing via Groups', description= 'Allows turning on case sharing between members in a group.'), Role(slug=privileges.CHILD_CASES, name='Child Cases', description= 'Allows for use of child cases / subcases in applications.'), Role( slug=privileges.ODATA_FEED, name='OData Feed - Tableau / BI Integration', description='Allows usage of Tableau / BI Integration (OData Feeds)' ), Role(slug=privileges.DATA_FORWARDING, name='Data Forwarding', description='Allows use of Data Forwarding'), Role(slug=privileges.PROJECT_ACCESS, name='Project Access', description='Allows access to core project functionality.'), Role(slug=privileges.APP_USER_PROFILES, name='App User Profiles', description='Allows use of App User Profiles.'), Role(slug=privileges.GEOCODER, name='Geocoder', description='Address widget in Web Apps.'), Role(slug=privileges.DEFAULT_EXPORT_SETTINGS, name='Default Export Settings', description= 'Allows ability to set default values for newly created exports.') ] BOOTSTRAP_PLANS = [ Role(slug='paused_plan_v0', name='Paused Plan', description=''), Role(slug='community_plan_v0', name='Community Plan', description=''), Role(slug='community_plan_v1', name='Community Plan', description=''), Role(slug='community_plan_v2', name='Community Plan', description=''), Role(slug='standard_plan_v0', name='Standard Plan', description=''), Role(slug='standard_plan_v1', name='Standard Plan', description=''), Role(slug='pro_plan_v0', name='Pro Plan', description=''), Role(slug='pro_plan_v1', name='Pro Plan', description=''), Role(slug='advanced_plan_v0', name='Advanced Plan', description=''), Role(slug='enterprise_plan_v0', name='Enterprise Plan', description=''), ] + [ Role(slug='standard_plan_report_builder_v0', name='Standard Plan - 5 Reports', description=''), Role(slug='pro_plan_report_builder_v0', name='Pro Plan - 5 Reports', description=''), Role(slug='advanced_plan_report_builder_v0', name='Advanced Plan - 5 Reports', description=''), ] OLD_PRIVILEGES = [ BULK_CASE_AND_USER_MANAGEMENT, CROSS_PROJECT_REPORTS, ] BOOTSTRAP_GRANTS = { 'paused_plan_v0': features.paused_v0, 'community_plan_v0': features.community_v0, 'community_plan_v1': features.community_v1, 'community_plan_v2': features.community_v2, 'standard_plan_v0': features.standard_v0, 'standard_plan_v1': features.standard_v1, 'pro_plan_v0': features.pro_v0, 'pro_plan_v1': features.pro_v1, 'advanced_plan_v0': features.advanced_v0, 'enterprise_plan_v0': features.enterprise_v0, }
def test_unsaved_role_does_not_have_permission(self): role1 = Role() role2 = arbitrary.role() self.assertFalse(role1.has_privilege(role2)) self.assertFalse(role2.has_privilege(role1))
def delete_grants(grants): Role.get_cache().clear() for grant in grants: grant.delete()
def setUpClass(cls): super(BaseAccountingTest, cls).setUpClass() Role.get_cache().clear()
def setUp(self): Role.get_cache().clear() self.zazzle_privilege = arbitrary.role( slug=arbitrary.unique_slug('zazzle'), parameters=set(['domain']))
class Command(BaseCommand): help = 'Populate a fresh database with some sample roles and grants' option_list = BaseCommand.option_list + ( make_option( '--dry-run', action='store_true', default=False, help= 'Do not actually modify the database, just verbosely log what happen' ), make_option('--verbose', action='store_true', default=False, help='Enable debug output'), make_option( '--fresh-start', action='store_true', default=False, help= 'We changed the core v0 plans, wipe all existing plans and start over. USE CAUTION.' ), make_option('--testing', action='store_true', default=False, help='Run this command for tests.'), ) def handle(self, dry_run=False, verbose=False, fresh_start=False, testing=False, *args, **options): self.verbose = verbose if fresh_start: confirm_fresh_start = raw_input( "Are you sure you want to delete all Roles and start over? You can't do this" " if accounting is already set up. Type 'yes' to continue.") if confirm_fresh_start == 'yes': self.flush_roles() for role in self.BOOTSTRAP_PRIVILEGES + self.BOOTSTRAP_PLANS: self.ensure_role(role, dry_run=dry_run) for (plan_role_slug, privs) in self.BOOTSTRAP_GRANTS.items(): for priv_role_slug in privs: ensure_grant(plan_role_slug, priv_role_slug, dry_run=dry_run, verbose=self.verbose) for old_priv in self.OLD_PRIVILEGES: remove_grant(old_priv, dry_run=dry_run) if not dry_run: Role.objects.filter(slug=old_priv).delete() def flush_roles(self): logger.info('Flushing ALL Roles...') Role.objects.all().delete() def ensure_role(self, role, dry_run=False): """ Adds the role if it does not already exist, otherwise skips it. """ existing_roles = Role.objects.filter(slug=role.slug) if existing_roles: logger.info('Role already exists: %s', role.name) return existing_roles[0] else: if dry_run: logger.info('[DRY RUN] Creating role: %s', role.name) else: if self.verbose: logger.info('Creating role: %s', role.name) role.save() BOOTSTRAP_PRIVILEGES = [ Role(slug=privileges.API_ACCESS, name='API Access', description=''), Role(slug=privileges.LOOKUP_TABLES, name='Lookup Tables', description=''), Role(slug=privileges.CLOUDCARE, name='Web-based Applications (CloudCare)', description=''), Role(slug=privileges.CUSTOM_BRANDING, name='Custom Branding', description=''), Role(slug=privileges.ACTIVE_DATA_MANAGEMENT, name='Active Data Management', description=''), Role(slug=privileges.CUSTOM_REPORTS, name='Custom Reports', description=''), Role(slug=privileges.ROLE_BASED_ACCESS, name='Role-based Access', description=''), Role( slug=privileges.OUTBOUND_SMS, name='Outbound SMS', description='Use of any outbound messaging / SMS services.', ), Role( slug=privileges.REMINDERS_FRAMEWORK, name='Rules Engine (Use of Reminders Framework)', description= 'Use of reminders framework for spawning reminders/alerts based on certain criteria.', ), Role( slug=privileges.CUSTOM_SMS_GATEWAY, name='Custom Telerivet (Android) SMS Gateway', description= 'Ability to set up telerivet gateway on the "SMS Connectivity" page (inbound or outbound).', ), Role(slug=privileges.INBOUND_SMS, name='Inbound SMS (where available)', description=''), Role(slug=privileges.BULK_CASE_MANAGEMENT, name='Bulk Case Management', description=''), Role(slug=privileges.BULK_USER_MANAGEMENT, name='Bulk User Management', description=''), Role(slug=privileges.DEIDENTIFIED_DATA, name='De-identified Data', description=''), Role(slug=privileges.HIPAA_COMPLIANCE_ASSURANCE, name='HIPAA Compliance Assurance', description=''), Role(slug=privileges.ALLOW_EXCESS_USERS, name='Can Add Users Above Limit', description=''), Role(slug=privileges.COMMCARE_LOGO_UPLOADER, name='Custom CommCare Logo Uploader', description=''), Role(slug=privileges.LOCATIONS, name='Locations', description=''), Role(slug=privileges.REPORT_BUILDER, name='User Configurable Report Builder', description=''), Role(slug=privileges.REPORT_BUILDER_TRIAL, name='Report Builder Trial', description=''), Role(slug=privileges.REPORT_BUILDER_5, name='Report Builder, 5 report limit', description=''), Role(slug=privileges.REPORT_BUILDER_15, name='Report Builder, 15 report limit', description=''), Role(slug=privileges.REPORT_BUILDER_30, name='Report Builder, 30 report limit', description=''), Role(slug=privileges.USER_CASE, name='User Case Management', description=''), Role( slug=privileges.DATA_CLEANUP, name='Data Management', description= 'Tools for cleaning up data, including editing submissions and archiving forms.' ), Role(slug=privileges.TEMPLATED_INTENTS, name='Templated Intents', description='Provides a dropdown for Android App Callouts'), Role(slug=privileges.CUSTOM_INTENTS, name='Custom Intents', description='Allows for specifying custom intents'), Role(slug=privileges.ADVANCED_DOMAIN_SECURITY, name='Advanced Domain Security', description= 'Allows domains to set security policies for all web users'), Role( slug=privileges.BUILD_PROFILES, name='Application Profiles', description= 'Allows domains to create application profiles to customize app deploys' ), Role( slug=privileges.EXCEL_DASHBOARD, name="Excel Dashbord", description="Allows domains to create Excel dashboard html exports" ), Role(slug=privileges.DAILY_SAVED_EXPORT, name='DAILY_SAVED_EXPORT', description="Allows domains to create Daily Saved Exports"), Role( slug=privileges.ZAPIER_INTEGRATION, name='Zapier Integration', description='Allows domains to use zapier (zapier.com) integration' ) ] BOOTSTRAP_PLANS = [ Role(slug='community_plan_v0', name='Community Plan', description=''), Role(slug='community_plan_v1', name='Community Plan', description=''), Role(slug='standard_plan_v0', name='Standard Plan', description=''), Role(slug='pro_plan_v0', name='Pro Plan', description=''), Role(slug='advanced_plan_v0', name='Advanced Plan', description=''), Role(slug='enterprise_plan_v0', name='Enterprise Plan', description=''), ] community_plan_v0_features = [ privileges.EXCEL_DASHBOARD, privileges.DAILY_SAVED_EXPORT, ] community_plan_v1_features = [] standard_plan_features = community_plan_v0_features + [ privileges.API_ACCESS, privileges.LOOKUP_TABLES, privileges.OUTBOUND_SMS, privileges.REMINDERS_FRAMEWORK, privileges.CUSTOM_SMS_GATEWAY, privileges.ROLE_BASED_ACCESS, privileges.BULK_USER_MANAGEMENT, privileges.BULK_CASE_MANAGEMENT, privileges.ALLOW_EXCESS_USERS, privileges.LOCATIONS, privileges.USER_CASE, privileges.ZAPIER_INTEGRATION ] pro_plan_features = standard_plan_features + [ privileges.CLOUDCARE, privileges.CUSTOM_REPORTS, privileges.INBOUND_SMS, privileges.HIPAA_COMPLIANCE_ASSURANCE, privileges.DEIDENTIFIED_DATA, privileges.REPORT_BUILDER, privileges.DATA_CLEANUP, privileges.TEMPLATED_INTENTS, ] advanced_plan_features = pro_plan_features + [ privileges.CUSTOM_BRANDING, privileges.ACTIVE_DATA_MANAGEMENT, privileges.COMMCARE_LOGO_UPLOADER, privileges.CUSTOM_INTENTS, privileges.ADVANCED_DOMAIN_SECURITY, privileges.BUILD_PROFILES, ] enterprise_plan_features = advanced_plan_features + [] OLD_PRIVILEGES = [ BULK_CASE_AND_USER_MANAGEMENT, CROSS_PROJECT_REPORTS, ] BOOTSTRAP_GRANTS = { 'community_plan_v0': community_plan_v0_features, 'community_plan_v1': community_plan_v1_features, 'standard_plan_v0': standard_plan_features, 'pro_plan_v0': pro_plan_features, 'advanced_plan_v0': advanced_plan_features, 'enterprise_plan_v0': enterprise_plan_features, }
def setUpClass(cls): super(BaseAccountingTest, cls).setUpClass() Role.get_cache().clear() generator.instantiate_accounting_for_tests()
def setUpClass(cls): super(BaseAccountingTest, cls).setUpClass() Role.get_cache().clear() generator.instantiate_accounting()
def setUpClass(cls): Role.get_cache().clear() generator.instantiate_accounting_for_tests()
class Command(BaseCommand): help = 'Populate a fresh database with some sample roles and grants' option_list = BaseCommand.option_list + ( make_option('--dry-run', action='store_true', default=False, help='Do not actually modify the database, just verbosely log what happen'), make_option('--verbose', action='store_true', default=False, help='Enable debug output'), make_option('--fresh-start', action='store_true', default=False, help='We changed the core v0 plans, wipe all existing plans and start over. USE CAUTION.'), make_option('--testing', action='store_true', default=False, help='Run this command for tests.'), ) def handle(self, dry_run=False, verbose=False, fresh_start=False, testing=False, *args, **options): self.verbose = verbose if fresh_start: confirm_fresh_start = raw_input("Are you sure you want to delete all Roles and start over? You can't do this" " if accounting is already set up. Type 'yes' to continue.") if confirm_fresh_start == 'yes': self.flush_roles() for role in self.BOOTSTRAP_PRIVILEGES + self.BOOTSTRAP_PLANS: self.ensure_role(role, dry_run=dry_run) for (plan_role_slug, privs) in self.BOOTSTRAP_GRANTS.items(): for priv_role_slug in privs: self.ensure_grant(plan_role_slug, priv_role_slug, dry_run=dry_run) for old_priv in self.OLD_PRIVILEGES: for plan_role_slug in self.BOOTSTRAP_GRANTS.keys(): self.remove_grant(plan_role_slug, old_priv) def flush_roles(self): logger.info('Flushing ALL Roles...') Role.objects.all().delete() def ensure_role(self, role, dry_run=False): """ Adds the role if it does not already exist, otherwise skips it. """ existing_roles = Role.objects.filter(slug=role.slug) if existing_roles: logger.info('Role already exists: %s', role.name) return existing_roles[0] else: if dry_run: logger.info('[DRY RUN] Creating role: %s', role.name) else: if self.verbose: logger.info('Creating role: %s', role.name) role.save() def ensure_grant(self, grantee_slug, priv_slug, dry_run=False): """ Adds a parameterless grant between grantee and priv, looked up by slug. """ if dry_run: grants = Grant.objects.filter(from_role__slug=grantee_slug, to_role__slug=priv_slug) if not grants: logger.info('[DRY RUN] Granting privilege: %s => %s', grantee_slug, priv_slug) else: grantee = Role.objects.get(slug=grantee_slug) priv = Role.objects.get(slug=priv_slug) if grantee.has_privilege(priv): if self.verbose: logger.info('Privilege already granted: %s => %s', grantee.slug, priv.slug) else: if self.verbose: logger.info('Granting privilege: %s => %s', grantee.slug, priv.slug) Grant.objects.create( from_role=grantee, to_role=priv, ) def remove_grant(self, grantee_slug, priv_slug, dry_run=False): grants = Grant.objects.filter(from_role__slug=grantee_slug, to_role__slug=priv_slug) if dry_run: if grants: logger.info("[DRY RUN] Removing privilege %s => %s", grantee_slug, priv_slug) else: if grants: grants.delete() logger.info("Removing privilege %s => %s", grantee_slug, priv_slug) BOOTSTRAP_PRIVILEGES = [ Role(slug=privileges.API_ACCESS, name='API Access', description=''), Role(slug=privileges.LOOKUP_TABLES, name='Lookup Tables', description=''), Role(slug=privileges.CLOUDCARE, name='Web-based Applications (CloudCare)', description=''), Role(slug=privileges.CUSTOM_BRANDING, name='Custom Branding', description=''), Role(slug=privileges.ACTIVE_DATA_MANAGEMENT, name='Active Data Management', description=''), Role(slug=privileges.CROSS_PROJECT_REPORTS, name='Cross-Project Reports', description=''), Role(slug=privileges.CUSTOM_REPORTS, name='Custom Reports', description=''), Role(slug=privileges.ROLE_BASED_ACCESS, name='Role-based Access', description=''), Role(slug=privileges.OUTBOUND_SMS, name='Outbound SMS', description='Use of any outbound messaging / SMS services.', ), Role(slug=privileges.REMINDERS_FRAMEWORK, name='Rules Engine (Use of Reminders Framework)', description='Use of reminders framework for spawning reminders/alerts based on certain criteria.', ), Role(slug=privileges.CUSTOM_SMS_GATEWAY, name='Custom Telerivet (Android) SMS Gateway', description='Ability to set up telerivet gateway on the "SMS Connectivity" page (inbound or outbound).', ), Role(slug=privileges.INBOUND_SMS, name='Inbound SMS (where available)', description=''), Role(slug=privileges.BULK_CASE_MANAGEMENT, name='Bulk Case Management', description=''), Role(slug=privileges.BULK_USER_MANAGEMENT, name='Bulk User Management', description=''), Role(slug=privileges.DEIDENTIFIED_DATA, name='De-identified Data', description=''), Role(slug=privileges.HIPAA_COMPLIANCE_ASSURANCE, name='HIPAA Compliance Assurance', description=''), Role(slug=privileges.ALLOW_EXCESS_USERS, name='Can Add Users Above Limit', description=''), ] BOOTSTRAP_PLANS = [ Role(slug='community_plan_v0', name='Community Plan', description=''), Role(slug='standard_plan_v0', name='Standard Plan', description=''), Role(slug='pro_plan_v0', name='Pro Plan', description=''), Role(slug='advanced_plan_v0', name='Advanced Plan', description=''), Role(slug='enterprise_plan_v0', name='Enterprise Plan', description=''), ] community_plan_features = [ ] standard_plan_features = community_plan_features + [ privileges.API_ACCESS, privileges.LOOKUP_TABLES, privileges.CROSS_PROJECT_REPORTS, privileges.OUTBOUND_SMS, privileges.REMINDERS_FRAMEWORK, privileges.CUSTOM_SMS_GATEWAY, privileges.ROLE_BASED_ACCESS, privileges.BULK_USER_MANAGEMENT, privileges.BULK_CASE_MANAGEMENT, privileges.ALLOW_EXCESS_USERS, ] pro_plan_features = standard_plan_features + [ privileges.CLOUDCARE, privileges.CUSTOM_REPORTS, privileges.INBOUND_SMS, privileges.HIPAA_COMPLIANCE_ASSURANCE, privileges.DEIDENTIFIED_DATA, ] advanced_plan_features = pro_plan_features + [ privileges.CUSTOM_BRANDING, privileges.ACTIVE_DATA_MANAGEMENT, ] enterprise_plan_features = advanced_plan_features + [] OLD_PRIVILEGES = [ BULK_CASE_AND_USER_MANAGEMENT, ] BOOTSTRAP_GRANTS = { 'community_plan_v0': community_plan_features, 'standard_plan_v0': standard_plan_features, 'pro_plan_v0': pro_plan_features, 'advanced_plan_v0': advanced_plan_features, 'enterprise_plan_v0': enterprise_plan_features, }
def setUp(self): Role.get_cache().clear() generator.instantiate_accounting_for_tests()