def test_class(self):
     self.assertEqual('state',
                      DomainPermissionsMirror.source_domain('county'))
     self.assertIsNone(DomainPermissionsMirror.source_domain('state'))
     self.assertEqual(['county'],
                      DomainPermissionsMirror.mirror_domains('state'))
     self.assertEqual([], DomainPermissionsMirror.mirror_domains('county'))
Exemple #2
0
 def test_multi_domain(self):
     dm = DomainPermissionsMirror(source=self.domain.name,
                                  mirror=self.other_domain.name)
     dm.save()
     import_users_and_groups(
         self.domain.name,
         [self._get_spec(username=123, domain=self.other_domain.name)], [],
         self.uploading_user, mock.MagicMock())
     self.assertIsNotNone(
         CommCareUser.get_by_username('{}@{}.commcarehq.org'.format(
             '123', self.other_domain.name)))
Exemple #3
0
    def __init__(self, *args, **kwargs):
        from corehq.apps.locations.forms import LocationSelectWidget
        from corehq.apps.users.views import get_editable_role_choices
        self.domain = kwargs.pop('domain')
        self.couch_user = kwargs.pop('couch_user')
        super(CommCareUserFilterForm, self).__init__(*args, **kwargs)
        self.fields['location_id'].widget = LocationSelectWidget(self.domain)
        self.fields['location_id'].help_text = ExpandedMobileWorkerFilter.location_search_help

        if is_icds_cas_project(self.domain) and not self.couch_user.is_domain_admin(self.domain):
            roles = get_editable_role_choices(self.domain, self.couch_user, allow_admin_role=True,
                                              use_qualified_id=False)
            self.fields['role_id'].choices = roles
        else:
            roles = UserRole.by_domain(self.domain)
            self.fields['role_id'].choices = [('', _('All Roles'))] + [
                (role._id, role.name or _('(No Name)')) for role in roles]

        self.fields['domains'].choices = [(self.domain, self.domain)]
        if len(DomainPermissionsMirror.mirror_domains(self.domain)) > 0:
            self.fields['domains'].choices = [('all_project_spaces', _('All Project Spaces'))] + \
                                             [(self.domain, self.domain)] + \
                                             [(domain, domain) for domain in
                                              DomainPermissionsMirror.mirror_domains(self.domain)]
        self.helper = FormHelper()
        self.helper.form_method = 'GET'
        self.helper.form_id = 'user-filters'
        self.helper.form_class = 'form-horizontal'
        self.helper.form_action = reverse('download_commcare_users', args=[self.domain])

        self.helper.label_class = 'col-sm-3 col-md-2'
        self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
        self.helper.form_text_inline = True

        self.helper.layout = crispy.Layout(
            crispy.Fieldset(
                _("Filter and Download Users"),
                crispy.Field('role_id', css_class="hqwebapp-select2"),
                crispy.Field('search_string'),
                crispy.Field('location_id'),
                crispy.Field('columns'),
                crispy.Field('domains'),
            ),
            hqcrispy.FormActions(
                twbscrispy.StrictButton(
                    _("Download All Users"),
                    type="submit",
                    css_class="btn btn-primary submit_button",
                )
            ),
        )
 def validate_spec(self, spec):
     target_domain = spec.get('domain')
     if target_domain and target_domain != self.domain:
         mirror_domains = DomainPermissionsMirror.mirror_domains(
             self.domain)
         if target_domain not in mirror_domains:
             return self.error_message.format(target_domain, self.domain)
Exemple #5
0
 def test_multi_domain(self):
     self.setup_users()
     dm = DomainPermissionsMirror(source=self.domain.name,
                                  mirror=self.other_domain.name)
     dm.save()
     import_users_and_groups(self.domain.name, [
         self._get_spec(username='******',
                        domain=self.other_domain.name,
                        role=self.other_domain_role.name,
                        email='*****@*****.**')
     ], [], self.uploading_user, mock.MagicMock(), True)
     self.assertIsNotNone(
         Invitation.objects.filter(email='*****@*****.**').first())
     self.assertEqual(
         Invitation.objects.filter(email='*****@*****.**').first().domain,
         self.other_domain.name)
    def setUpClass(cls):
        super().setUpClass()

        # Set up domains
        cls.mirror = DomainPermissionsMirror(source='state', mirror='county')
        cls.mirror.save()
        create_domain('state')
        create_domain('county')

        # Set up users
        cls.web_user_admin = WebUser.create('state',
                                            'emma',
                                            'badpassword',
                                            None,
                                            None,
                                            email='*****@*****.**',
                                            is_admin=True)
        cls.web_user_non_admin = WebUser.create('state',
                                                'clementine',
                                                'worsepassword',
                                                None,
                                                None,
                                                email='*****@*****.**')
        cls.api_key, _ = HQApiKey.objects.get_or_create(
            user=WebUser.get_django_user(cls.web_user_non_admin))
Exemple #7
0
def do_import(spreadsheet, config, domain, task=None, record_form_callback=None):
    has_domain_column = 'domain' in [c.lower() for c in spreadsheet.get_header_columns()]
    if has_domain_column and DOMAIN_PERMISSIONS_MIRROR.enabled(domain):
        mirror_domains = DomainPermissionsMirror.mirror_domains(domain)
        sub_domains = set()
        import_results = _ImportResults()
        for row_num, row in enumerate(spreadsheet.iter_row_dicts(), start=1):
            if row_num == 1:
                continue  # skip first row (header row)
            sheet_domain = row.get('domain')
            if sheet_domain != domain and sheet_domain not in mirror_domains:
                err = exceptions.CaseRowError(column_name='domain')
                err.title = _('Invalid domain')
                err.message = _('Following rows contain invalid value for domain column.')
                import_results.add_error(row_num, err)
            else:
                sub_domains.add(sheet_domain)
        for sub_domain in sub_domains:
            importer = _TimedAndThrottledImporter(
                sub_domain,
                config,
                task,
                record_form_callback,
                import_results,
                multi_domain=True
            )
            importer.do_import(spreadsheet)
        return import_results.to_json()
    else:
        importer = _TimedAndThrottledImporter(domain, config, task, record_form_callback, multi_domain=False)
        return importer.do_import(spreadsheet)
Exemple #8
0
def domain(domain, allow_mirroring=False):
    domains = [domain]
    if allow_mirroring:
        from corehq.apps.users.models import DomainPermissionsMirror
        source_domain = DomainPermissionsMirror.source_domain(domain)
        if source_domain:
            domains.append(source_domain)
    return filters.OR(filters.term("domain.exact", domains),
                      filters.term("domain_memberships.domain.exact", domains))
Exemple #9
0
    def clean_domains(self):
        if 'domains' in self.data:
            domains = self.data.getlist('domains')
        else:
            domains = self.data.getlist('domains[]', [self.domain])

        if 'all_project_spaces' in domains:
            domains = DomainPermissionsMirror.mirror_domains(self.domain)
            domains += [self.domain]
        return domains
Exemple #10
0
    def test_multiple_domain_case_import(self):
        mirror_domain1 = DomainPermissionsMirror(source=self.domain,
                                                 mirror='mirrordomain1')
        mirror_domain2 = DomainPermissionsMirror(source=self.domain,
                                                 mirror='mirrordomain2')
        mirror_domain1.save()
        mirror_domain2.save()
        headers_with_domain = ['case_id', 'name', 'artist', 'domain']
        config_1 = self._config(headers_with_domain,
                                create_new_cases=True,
                                search_column='case_id')
        case_with_domain_file = make_worksheet_wrapper(
            ['case_id', 'name', 'artist', 'domain'],
            ['', 'name-0', 'artist-0', self.domain],
            ['', 'name-1', 'artist-1', mirror_domain1.mirror],
            ['', 'name-2', 'artist-2', mirror_domain2.mirror],
            ['', 'name-3', 'artist-3', self.domain],
            ['', 'name-4', 'artist-4', self.domain],
            ['', 'name-5', 'artist-5', 'not-existing-domain'])
        res = do_import(case_with_domain_file, config_1, self.domain)
        self.assertEqual(5, res['created_count'])
        self.assertEqual(0, res['match_count'])
        self.assertEqual(1, res['failed_count'])

        # Asserting current domain
        cur_case_ids = self.accessor.get_case_ids_in_domain()
        cur_cases = list(self.accessor.get_cases(cur_case_ids))
        self.assertEqual(3, len(cur_cases))
        #Asserting current domain case property
        cases = {c.name: c for c in cur_cases}
        self.assertEqual(cases['name-0'].get_case_property('artist'),
                         'artist-0')

        # Asserting mirror domain 1
        md1_case_ids = CaseAccessors(
            mirror_domain1.mirror).get_case_ids_in_domain()
        md1_cases = list(self.accessor.get_cases(md1_case_ids))
        self.assertEqual(1, len(md1_cases))
        # Asserting mirror domain 1 case property
        md1_cases_pro = {c.name: c for c in md1_cases}
        self.assertEqual(md1_cases_pro['name-1'].get_case_property('artist'),
                         'artist-1')

        # Asserting mirror domain 2
        md2_case_ids = CaseAccessors(
            mirror_domain2.mirror).get_case_ids_in_domain()
        md2_cases = list(self.accessor.get_cases(md2_case_ids))
        self.assertEqual(1, len(md2_cases))
        # Asserting mirror domain 2 case propperty
        md2_cases_pro = {c.name: c for c in md2_cases}
        self.assertEqual(md2_cases_pro['name-2'].get_case_property('artist'),
                         'artist-2')
Exemple #11
0
def get_mirror_domain_links_for_dropdown(couch_user, view_name="domain_homepage"):
    # Returns dicts with keys 'name', 'display_name', and 'url'
    from corehq.apps.users.models import DomainPermissionsMirror
    domain_links_by_name = {d['name']: d for d in get_domain_links_for_dropdown(couch_user)}
    mirror_domain_objects_by_name = {}
    for domain_name in domain_links_by_name:
        for mirror_domain in DomainPermissionsMirror.mirror_domains(domain_name):
            if mirror_domain not in domain_links_by_name:
                mirror_domain_objects_by_name[mirror_domain] = Domain.get_by_name(mirror_domain)

    return _domains_to_links(mirror_domain_objects_by_name.values(), view_name)
Exemple #12
0
    def post(self, request, *args, **kwargs):
        try:
            data = json.loads(request.body.decode('utf-8'))
        except ValueError:
            return HttpResponseBadRequest()

        if not data or not isinstance(data, dict):
            return HttpResponseBadRequest()

        session_id = data.get('sessionId', None)
        if not session_id:
            return HttpResponseBadRequest()

        session = get_session(session_id)
        user = get_django_user_from_session(session)
        if user:
            couch_user = CouchUser.get_by_username(user.username)
            if not couch_user:
                raise Http404
        else:
            raise Http404

        domain = data.get('domain')
        if domain and DISABLE_WEB_APPS.enabled(domain):
            return HttpResponse('Service Temporarily Unavailable',
                                content_type='text/plain',
                                status=503)

        # reset the session's expiry if there's some formplayer activity
        secure_session = session.get('secure_session')
        TimeoutMiddleware.update_secure_session(session,
                                                secure_session,
                                                couch_user,
                                                domain=data.get('domain'))
        session.save()

        domains = set()
        for domain in couch_user.domains:
            domains.add(domain)
            mirror_domains = DomainPermissionsMirror.mirror_domains(domain)
            domains.update(mirror_domains)

        return JsonResponse({
            'username': user.username,
            'djangoUserId': user.pk,
            'superUser': user.is_superuser,
            'authToken': None,
            'domains': list(domains),
            'anonymous': False
        })
Exemple #13
0
    def _user_requires_secure_session(couch_user):
        if not couch_user:
            return False

        domains = couch_user.get_domains()
        if any(Domain.is_secure_session_required(domain) for domain in domains):
            return True

        from corehq.apps.users.models import DomainPermissionsMirror
        for domain in domains:
            mirrors = DomainPermissionsMirror.mirror_domains(domain)
            if any(Domain.is_secure_session_required(m) for m in mirrors):
                return True

        return False
    def setUpClass(cls):
        super().setUpClass()

        # Set up domains
        cls.mirror = DomainPermissionsMirror(source='state', mirror='county')
        cls.mirror.save()
        create_domain('state')
        create_domain('county')

        # Set up users
        cls.web_user_admin = WebUser.create('state',
                                            'emma',
                                            'badpassword',
                                            '*****@*****.**',
                                            is_admin=True)
        cls.web_user_non_admin = WebUser.create('state', 'clementine',
                                                'worsepassword', '*****@*****.**')
Exemple #15
0
    def _get_relevant_domains(cls, couch_user, domain=None):
        domains = []

        # Include current domain, which user may not be a member of
        if domain:
            domains.append(domain)

        if not couch_user:
            return domains

        domains.extend(couch_user.get_domains())

        from corehq.apps.users.models import DomainPermissionsMirror
        for domain in domains:
            domains.extend(DomainPermissionsMirror.mirror_domains(domain))

        return domains
Exemple #16
0
    def test_domain_allow_mirroring(self):
        source_domain = self.domain + "-source"
        mirror = DomainPermissionsMirror(source=source_domain, mirror=self.domain)
        mirror.save()
        self._send_user_to_es()

        self.assertEqual(['superman'], UserES().domain(self.domain).values_list('username', flat=True))
        self.assertEqual([], UserES().domain(source_domain).values_list('username', flat=True))
        self.assertEqual(
            ['superman'],
            UserES().domain(self.domain, allow_mirroring=True).values_list('username', flat=True)
        )
        mirror.delete()
Exemple #17
0
    def setUpClass(cls):
        super().setUpClass()
        delete_all_users()

        # Set up domains
        cls.domain = create_domain('test')
        cls.mirror_domain = create_domain('mirror')
        cls.mirror = DomainPermissionsMirror(source=cls.domain.name,
                                             mirror=cls.mirror_domain.name)
        cls.mirror.save()

        # Set up user
        cls.web_user = WebUser.create(
            domain='test',
            username='******',
            password='******',
            created_by=None,
            created_via=None,
        )

        cls.today = datetime.today().date()
        cls.last_week = cls.today - timedelta(days=7)
Exemple #18
0
 def page_context(self):
     return {
         'mirrors': DomainPermissionsMirror.mirror_domains(self.domain),
     }