Exemple #1
0
    def test_update(self):
        self.client.login(username=self.username, password=self.password)

        user = WebUser.create(domain=self.domain.name, username="******", password="******")

        user_json = {
            "email":"*****@*****.**",
            "first_name":"Joe",
            "is_admin": True,
            "last_name":"Admin",
            "permissions":{
                "edit_apps":True,
                "edit_commcare_users":True,
                "edit_data":True,
                "edit_web_users":True,
                "view_reports":True
            },
            "phone_numbers":[
            ],
            "role":"admin"
        }

        backend_id = user._id
        response = self.client.put(self.single_endpoint(backend_id),
                                   simplejson.dumps(user_json),
                                   content_type='application/json')
        self.assertEqual(response.status_code, 204, response.content)
        modified = WebUser.get(backend_id)
        self.assertEqual(modified.username, "test")
        self.assertEqual(modified.first_name, "Joe")
        self.assertEqual(modified.last_name, "Admin")
        self.assertEqual(modified.email, "*****@*****.**")
        modified.delete()
Exemple #2
0
 def obj_update(self, bundle, **kwargs):
     bundle.obj = WebUser.get(kwargs['pk'])
     assert kwargs['domain'] in bundle.obj.domains
     if self._update(bundle):
         assert kwargs['domain'] in bundle.obj.domains
         bundle.obj.save()
     return bundle
Exemple #3
0
    def test_update(self):
        self.client.login(username=self.username, password=self.password)

        user = WebUser.create(domain=self.domain.name, username="******", password="******")

        user_json = {
            "email":"*****@*****.**",
            "first_name":"Joe",
            "is_admin": True,
            "last_name":"Admin",
            "permissions":{
                "edit_apps":True,
                "edit_commcare_users":True,
                "edit_data":True,
                "edit_web_users":True,
                "view_reports":True
            },
            "phone_numbers":[
            ],
            "role":"admin"
        }

        backend_id = user._id
        response = self.client.put(self.single_endpoint(backend_id),
                                   simplejson.dumps(user_json),
                                   content_type='application/json')
        self.assertEqual(response.status_code, 202, response.content)
        modified = WebUser.get(backend_id)
        self.assertEqual(modified.username, "test")
        self.assertEqual(modified.first_name, "Joe")
        self.assertEqual(modified.last_name, "Admin")
        self.assertEqual(modified.email, "*****@*****.**")
        modified.delete()
Exemple #4
0
def orgs_landing(request, org, template="orgs/orgs_landing.html", form=None, add_form=None, invite_member_form=None,
                 add_team_form=None, update_form=None, tab=None):
    organization = request.organization

    class LandingNotification(Notification):
        doc_type = 'OrgLandingNotification'

        def template(self):
            return 'orgs/partials/landing_notification.html'

    MainNotification.display_if_needed(messages, request, ctxt={"org": organization})
    LandingNotification.display_if_needed(messages, request)

    reg_form_empty = not form
    add_form_empty = not add_form
    invite_member_form_empty = not invite_member_form
    add_team_form_empty = not add_team_form

    reg_form = form or DomainRegistrationForm(initial={'org': organization.name})
    add_form = add_form or AddProjectForm(org)
    invite_member_form = invite_member_form or InviteMemberForm(org)
    add_team_form = add_team_form or AddTeamForm(org)

    ctxt = base_context(request, organization, update_form=update_form)
    user_domains = []
    req_domains = []
    # display a notification for each org request that hasn't previously been seen
    if request.couch_user.is_org_admin(org):
        requests = OrgRequest.get_requests(org)
        for req in requests:
            if req.seen or req.domain in [d.name for d in ctxt["domains"]]:
                continue
            messages.info(request, render_to_string("orgs/partials/org_request_notification.html",
                {"requesting_user": WebUser.get(req.requested_by).username, "org_req": req, "org": organization}),
                extra_tags="html")

        def format_domains(dom_list, extra=None):
            extra = extra or []
            dom_list = list(set(filter(lambda d: d not in ctxt["domains"] + extra, dom_list)))
            return [Domain.get_by_name(d) for d in dom_list]

        # get the existing domains that an org admin would add to the organization
        user_domains = request.couch_user.domains or []
        user_domains = filter(
            lambda x: domain_has_privilege(x, privileges.CROSS_PROJECT_REPORTS),
            user_domains
        )
        req_domains = [req.domain for req in requests]
        user_domains = format_domains(user_domains)
        req_domains = format_domains(req_domains, [d.name for d in user_domains if d])
        filter(
            lambda x: domain_has_privilege(x, privileges.CROSS_PROJECT_REPORTS),
            req_domains
        )

    ctxt.update(dict(reg_form=reg_form, add_form=add_form, reg_form_empty=reg_form_empty, add_form_empty=add_form_empty,
                invite_member_form=invite_member_form, invite_member_form_empty=invite_member_form_empty,
                add_team_form=add_team_form, add_team_form_empty=add_team_form_empty, tab="projects",
                user_domains=user_domains, req_domains=req_domains))
    return render(request, template, ctxt)
Exemple #5
0
 def obj_update(self, bundle, **kwargs):
     bundle.obj = WebUser.get(kwargs['pk'])
     assert kwargs['domain'] in bundle.obj.domains
     if self._update(bundle):
         assert kwargs['domain'] in bundle.obj.domains
         bundle.obj.save()
     return bundle
Exemple #6
0
def set_admin(request, org):
    member_id = request.POST.get("member_id", None)
    if member_id:
        member = WebUser.get(member_id)
        member.set_org_admin(org)
        member.save()
        messages.success(request, 'You have made %s an admin of the organization %s.' % (member.username, org))
    return HttpResponseRedirect(reverse("orgs_members", args=[org]))
Exemple #7
0
def set_admin(request, org):
    member_id = request.POST.get("member_id", None)
    if member_id:
        member = WebUser.get(member_id)
        member.set_org_admin(org)
        member.save()
        messages.success(request, 'You have made %s an admin of the organization %s.' % (member.username, org))
    return HttpResponseRedirect(reverse("orgs_members", args=[org]))
Exemple #8
0
def send_report(notification_id):
    notification = ReportNotification.get(notification_id)
    owner = WebUser.get(notification.owner_id)
    language = owner.get_language_code()
    try:
        with localize(language):
            notification.send()
    except UnsupportedScheduledReportError:
        pass
Exemple #9
0
def remove_member(request, org):
    member_id = request.POST.get("member_id", None)
    if member_id == request.couch_user.get_id and not request.couch_user.is_superuser:
        messages.error(request, "You cannot remove yourself from an organization")
    else:
        member = WebUser.get(member_id)
        record = member.delete_org_membership(org, create_record=True)
        member.save()
        messages.success(request, 'You have removed {m} from the organization {o}. <a href="{url}" class="post-link">Undo</a>'.format(
            url=reverse('undo_remove_member', args=[org, record.get_id]), m=member.username, o=org
        ), extra_tags="html")
    return HttpResponseRedirect(reverse("orgs_members", args=[org]))
Exemple #10
0
    def _assertStdUsers(self):
        for ind, wu in enumerate(self.web_users[1:]):
            web_user = WebUser.get(wu.get_id)
            self.assertEqual(
                web_user.get_domain_membership(self.domain.name).role_id,
                self.user_roles[ind].get_id)

        for ind, cc in enumerate(self.commcare_users[1:]):
            commcare_user = CommCareUser.get(cc.get_id)
            self.assertEqual(
                commcare_user.get_domain_membership(self.domain.name).role_id,
                self.user_roles[ind].get_id)
Exemple #11
0
def remove_member(request, org):
    member_id = request.POST.get("member_id", None)
    if member_id == request.couch_user.get_id and not request.couch_user.is_superuser:
        messages.error(request, "You cannot remove yourself from an organization")
    else:
        member = WebUser.get(member_id)
        record = member.delete_org_membership(org, create_record=True)
        member.save()
        messages.success(request, 'You have removed {m} from the organization {o}. <a href="{url}" class="post-link">Undo</a>'.format(
            url=reverse('undo_remove_member', args=[org, record.get_id]), m=member.username, o=org
        ), extra_tags="html")
    return HttpResponseRedirect(reverse("orgs_members", args=[org]))
Exemple #12
0
def orgs_landing(request, org, template="orgs/orgs_landing.html", form=None, add_form=None, invite_member_form=None,
                 add_team_form=None, update_form=None, tab=None):
    organization = request.organization

    class LandingNotification(Notification):
        doc_type = 'OrgLandingNotification'

        def template(self):
            return 'orgs/partials/landing_notification.html'

    MainNotification.display_if_needed(messages, request, ctxt={"org": organization})
    LandingNotification.display_if_needed(messages, request)

    reg_form_empty = not form
    add_form_empty = not add_form
    invite_member_form_empty = not invite_member_form
    add_team_form_empty = not add_team_form

    reg_form = form or DomainRegistrationForm(initial={'org': organization.name})
    add_form = add_form or AddProjectForm(org)
    invite_member_form = invite_member_form or InviteMemberForm(org)
    add_team_form = add_team_form or AddTeamForm(org)

    ctxt = base_context(request, organization, update_form=update_form)
    user_domains = []
    req_domains = []
    # display a notification for each org request that hasn't previously been seen
    if request.couch_user.is_org_admin(org):
        requests = OrgRequest.get_requests(org)
        for req in requests:
            if req.seen or req.domain in [d.name for d in ctxt["domains"]]:
                continue
            messages.info(request, render_to_string("orgs/partials/org_request_notification.html",
                {"requesting_user": WebUser.get(req.requested_by).username, "org_req": req, "org": organization}),
                extra_tags="html")

        def format_domains(dom_list, extra=None):
            extra = extra or []
            dom_list = list(set(filter(lambda d: d not in ctxt["domains"] + extra, dom_list)))
            return [Domain.get_by_name(d) for d in dom_list]

        # get the existing domains that an org admin would add to the organization
        user_domains = request.couch_user.domains or []
        req_domains = [req.domain for req in requests]
        user_domains = format_domains(user_domains)
        req_domains = format_domains(req_domains, [d.name for d in user_domains if d])

    ctxt.update(dict(reg_form=reg_form, add_form=add_form, reg_form_empty=reg_form_empty, add_form_empty=add_form_empty,
                invite_member_form=invite_member_form, invite_member_form_empty=invite_member_form_empty,
                add_team_form=add_team_form, add_team_form_empty=add_team_form_empty, tab="projects",
                user_domains=user_domains, req_domains=req_domains))
    return render(request, template, ctxt)
    def assertStdUsers(self):
        for ind, wu in enumerate(self.web_users[1:]):
            web_user = WebUser.get(wu.get_id)
            self.assertEqual(
                web_user.get_domain_membership(self.domain.name).role_id,
                self.user_roles[ind].get_id
            )

        for ind, cc in enumerate(self.commcare_users[1:]):
            commcare_user = CommCareUser.get(cc.get_id)
            self.assertEqual(
                commcare_user.get_domain_membership(self.domain.name).role_id,
                self.user_roles[ind].get_id
            )
    def test_edit_webuser_email(self):
        with open(os.path.join(self.datapath, 'sample_webusers.json')) as f:
            webuser = ILSUser(json.loads(f.read())[0])
        self.assertEqual(len(WebUser.by_domain(TEST_DOMAIN)), 0)

        ils_webuser = self.api_object.web_user_sync(webuser)
        self.assertEqual(len(WebUser.by_domain(TEST_DOMAIN)), 1)

        webuser.email = '*****@*****.**'
        ils_webuser2 = self.api_object.web_user_sync(webuser)
        ils_webuser = WebUser.get(docid=ils_webuser.get_id)

        self.assertEqual(len(WebUser.by_domain(TEST_DOMAIN)), 1)
        self.assertIsNone(ils_webuser.get_domain_membership(TEST_DOMAIN))
        self.assertEqual(ils_webuser2.username, '*****@*****.**')
Exemple #15
0
 def owner(self):
     if self.owner_doc_type == "CommCareCase":
         # Circular import
         from corehq.apps.sms.models import CommConnectCase
         return CommConnectCase.get(self.owner_id)
     elif self.owner_doc_type == "CommCareUser":
         # Circular import
         from corehq.apps.users.models import CommCareUser
         return CommCareUser.get(self.owner_id)
     elif self.owner_doc_type == 'WebUser':
         # Circular importsms
         from corehq.apps.users.models import WebUser
         return WebUser.get(self.owner_id)
     else:
         return None
Exemple #16
0
 def recipient(self):
     if self.recipient_type == 'CommCareCase':
         return CaseAccessors(self.domain).get_case(self.recipient_id)
     elif self.recipient_type == 'CommCareUser':
         return CommCareUser.get(self.recipient_id)
     elif self.recipient_type == 'WebUser':
         return WebUser.get(self.recipient_id)
     elif self.recipient_type == 'CommCareCaseGroup':
         return CommCareCaseGroup.get(self.recipient_id)
     elif self.recipient_type == 'Group':
         return Group.get(self.recipient_id)
     elif self.recipient_type == 'Location':
         return SQLLocation.by_location_id(self.recipient_id)
     else:
         raise UnknownRecipientType(self.recipient_type)
Exemple #17
0
 def recipient(self):
     if self.recipient_type == self.RECIPIENT_TYPE_CASE:
         return CaseAccessors(self.domain).get_case(self.recipient_id)
     elif self.recipient_type == self.RECIPIENT_TYPE_MOBILE_WORKER:
         return CommCareUser.get(self.recipient_id)
     elif self.recipient_type == self.RECIPIENT_TYPE_WEB_USER:
         return WebUser.get(self.recipient_id)
     elif self.recipient_type == self.RECIPIENT_TYPE_CASE_GROUP:
         return CommCareCaseGroup.get(self.recipient_id)
     elif self.recipient_type == self.RECIPIENT_TYPE_USER_GROUP:
         return Group.get(self.recipient_id)
     elif self.recipient_type == self.RECIPIENT_TYPE_LOCATION:
         return SQLLocation.by_location_id(self.recipient_id)
     else:
         raise UnknownRecipientType(self.recipient_type)
Exemple #18
0
 def owner(self):
     if self.owner_doc_type == "CommCareCase":
         # Circular import
         from corehq.apps.sms.models import CommConnectCase
         return CommConnectCase.get(self.owner_id)
     elif self.owner_doc_type == "CommCareUser":
         # Circular import
         from corehq.apps.users.models import CommCareUser
         return CommCareUser.get(self.owner_id)
     elif self.owner_doc_type == 'WebUser':
         # Circular importsms
         from corehq.apps.users.models import WebUser
         return WebUser.get(self.owner_id)
     else:
         return None
Exemple #19
0
 def test_update(self):
     user = WebUser.create(domain=self.domain.name, username="******", password="******")
     self.addCleanup(user.delete)
     user_json = deepcopy(self.default_user_json)
     user_json.pop('username')
     backend_id = user._id
     response = self._assert_auth_post_resource(self.single_endpoint(backend_id),
                                                json.dumps(user_json),
                                                content_type='application/json',
                                                method='PUT')
     self.assertEqual(response.status_code, 200, response.content)
     modified = WebUser.get(backend_id)
     self.assertEqual(modified.username, "test")
     self.assertEqual(modified.first_name, "Joe")
     self.assertEqual(modified.last_name, "Admin")
     self.assertEqual(modified.email, "*****@*****.**")
Exemple #20
0
 def test_update(self):
     user = WebUser.create(domain=self.domain.name, username="******", password="******")
     self.addCleanup(user.delete)
     user_json = deepcopy(self.default_user_json)
     user_json.pop('username')
     backend_id = user._id
     response = self._assert_auth_post_resource(self.single_endpoint(backend_id),
                                                json.dumps(user_json),
                                                content_type='application/json',
                                                method='PUT')
     self.assertEqual(response.status_code, 200, response.content)
     modified = WebUser.get(backend_id)
     self.assertEqual(modified.username, "test")
     self.assertEqual(modified.first_name, "Joe")
     self.assertEqual(modified.last_name, "Admin")
     self.assertEqual(modified.email, "*****@*****.**")
Exemple #21
0
def export_all_rows_task(ReportClass, report_state):
    report = object.__new__(ReportClass)

    # Somehow calling generic _init function or __setstate__ is raising AttributeError
    # on '_update_initial_context' function call...
    try:
        report.__setstate__(report_state)
    except AttributeError:
        pass

    # need to set request
    setattr(report.request, 'REQUEST', {})

    file = report.excel_response
    hash_id = _store_excel_in_redis(file)
    user = WebUser.get(report_state["request"]["couch_user"])
    _send_email(user.get_email(), report, hash_id)
Exemple #22
0
def export_all_rows_task(ReportClass, report_state):
    report = object.__new__(ReportClass)

    # Somehow calling generic _init function or __setstate__ is raising AttributeError
    # on '_update_initial_context' function call...
    try:
        report.__setstate__(report_state)
    except AttributeError:
        pass

    # need to set request
    setattr(report.request, 'REQUEST', {})

    file = report.excel_response
    hash_id = _store_excel_in_redis(file)
    user = WebUser.get(report_state["request"]["couch_user"])
    _send_email(user.get_email(), report, hash_id)
Exemple #23
0
    def handle(self, export_file, config_file, domain, user_id, **options):
        start = datetime.utcnow()

        if '@' in user_id:
            user = WebUser.get_by_username(user_id)
        else:
            user = WebUser.get(user_id)
        if not user.is_member_of(domain):
            raise CommandError("%s can't access %s" % (user, domain))

        with open(config_file, 'r', encoding='utf-8') as f:
            config = ImporterConfig.from_json(f.read())

        config.couch_user_id = user._id
        with get_spreadsheet(export_file) as spreadsheet:
            print(json.dumps(do_import(spreadsheet, config, domain),
                             default=json_handler))
            print('finished in %s seconds' % (datetime.utcnow() - start).seconds)
Exemple #24
0
def _users_context(request, domain):
    couch_user = request.couch_user
    web_users = WebUser.by_domain(domain)
    teams = Team.get_by_domain(domain)
    for team in teams:
        for member_id in team.member_ids:
            team_user = WebUser.get(member_id)
            if team_user.get_id not in [web_user.get_id for web_user in web_users]:
                    web_users.append(team_user)

    for user in [couch_user] + list(web_users):
        user.current_domain = domain

    return {
        'web_users': web_users,
        'domain': domain,
        'couch_user': couch_user,
    }
    def handle(self, *args, **options):
        if len(args) != 4:
            raise CommandError('Usage is import_cases %s' % self.args)

        start = datetime.now()
        export_file, config_file, domain, user_id = args
        if '@' in user_id:
            user = WebUser.get_by_username(user_id)
        else:
            user = WebUser.get(user_id)
        if not user.is_member_of(domain):
            raise CommandError("%s can't access %s" % (user, domain))

        with open(config_file, 'r') as f:
            config = ImporterConfig.from_json(f.read())

        config.couch_user_id = user._id
        spreadsheet = ExcelFile(export_file, True)
        print json.dumps(do_import(spreadsheet, config, domain))
        print 'finished in %s seconds' % (datetime.now() - start).seconds
 def handle(self, *args, **options):
     for user_data in WebUser.view('users/mailing_list_emails').all():
         email_address = user_data['key']
         if options.get(RUN_FIX, False):
             print 'subscribing %s' % email_address
             try:
                 subscribe_user_to_mailchimp_list(
                     WebUser.get(user_data['id']),
                     settings.MAILCHIMP_MASS_EMAIL_ID,
                     email=email_address,
                 )
                 print 'subscribed %s' % email_address
             except mailchimp.ListAlreadySubscribedError:
                 print 'already subscribed %s' % email_address
             except mailchimp.ListInvalidImportError as e:
                 print e.message
             except mailchimp.ValidationError as e:
                 print e.message
             except mailchimp.Error as e:
                 raise e
         else:
             print 'ready to subscribe %s' % email_address
Exemple #27
0
 def handle(self, *args, **options):
     for user_data in WebUser.view('users/mailing_list_emails').all():
         email_address = user_data['key']
         if options.get(RUN_FIX, False):
             print 'subscribing %s' % email_address
             try:
                 subscribe_user_to_mailchimp_list(
                     WebUser.get(user_data['id']),
                     settings.MAILCHIMP_MASS_EMAIL_ID,
                     email=email_address,
                 )
                 print 'subscribed %s' % email_address
             except mailchimp.ListAlreadySubscribedError:
                 print 'already subscribed %s' % email_address
             except mailchimp.ListInvalidImportError as e:
                 print e.message
             except mailchimp.ValidationError as e:
                 print e.message
             except mailchimp.Error as e:
                 raise e
         else:
             print 'ready to subscribe %s' % email_address
Exemple #28
0
 def setUp(self):
     # Reload users before each test
     self.webuser = WebUser.get(self.webuser._id)
     self.webuser2 = WebUser.get(self.webuser2._id)
     self.ccuser = CommCareUser.get(self.ccuser._id)
 def web_user(self):
     return WebUser.get(self.user_id)
Exemple #30
0
 def setUp(self):
     # Reload users before each test
     self.webuser = WebUser.get(self.webuser._id)
     self.webuser2 = WebUser.get(self.webuser2._id)
     self.ccuser = CommCareUser.get(self.ccuser._id)
Exemple #31
0
def orgs_landing(
    request,
    org,
    template="orgs/orgs_landing.html",
    form=None,
    add_form=None,
    invite_member_form=None,
    add_team_form=None,
    update_form=None,
    tab=None,
):
    organization = Organization.get_by_name(org, strict=True)

    reg_form_empty = not form
    add_form_empty = not add_form
    invite_member_form_empty = not invite_member_form
    add_team_form_empty = not add_team_form

    reg_form = form or DomainRegistrationForm(initial={"org": organization.name})
    add_form = add_form or AddProjectForm(org)
    invite_member_form = invite_member_form or InviteMemberForm(org)
    add_team_form = add_team_form or AddTeamForm(org)

    ctxt = base_context(request, organization, update_form=update_form)
    potential_domains = []

    # display a notification for each org request that hasn't previously been seen
    if request.couch_user.is_org_admin(org):
        requests = OrgRequest.get_requests(org)
        for req in requests:
            if req.seen or req.domain in [d.name for d in ctxt["domains"]]:
                continue
            messages.info(
                request,
                render_to_string(
                    "orgs/partials/org_request_notification.html",
                    {"requesting_user": WebUser.get(req.requested_by).username, "org_req": req, "org": organization},
                ),
                extra_tags="html",
            )

        # get the existing domains that an org admin would add to the organization
        potential_domains = request.couch_user.domains
        potential_domains.extend([req.domain for req in requests])
        potential_domains = list(set(filter(lambda d: d not in ctxt["domains"], potential_domains)))

    ctxt.update(
        dict(
            reg_form=reg_form,
            add_form=add_form,
            reg_form_empty=reg_form_empty,
            add_form_empty=add_form_empty,
            invite_member_form=invite_member_form,
            invite_member_form_empty=invite_member_form_empty,
            add_team_form=add_team_form,
            add_team_form_empty=add_team_form_empty,
            tab="projects",
            potential_domains=potential_domains,
        )
    )
    return render(request, template, ctxt)
Exemple #32
0
 def web_user(self):
     return WebUser.get(docid=self.kwargs['user_id'])
Exemple #33
0
 def owner(self):
     return WebUser.get(self.owner_id)
Exemple #34
0
 def editable_user(self):
     try:
         return WebUser.get(self.editable_user_id)
     except (ResourceNotFound, CouchUser.AccountTypeError):
         raise Http404()
Exemple #35
0
 def owner(self):
     id = self.owner_id if self.owner_id else self.user_ids[0]
     return WebUser.get(id)
Exemple #36
0
 def editable_user(self):
     try:
         return WebUser.get(self.editable_user_id)
     except (ResourceNotFound, CouchUser.AccountTypeError):
         raise Http404()
Exemple #37
0
 def web_user(self):
     return WebUser.get(docid=self.kwargs['user_id'])
Exemple #38
0
 def obj_get(self, bundle, **kwargs):
     return WebUser.get(kwargs['pk'])
Exemple #39
0
 def obj_get(self, bundle, **kwargs):
     return WebUser.get(kwargs['pk'])
Exemple #40
0
 def web_user(self):
     return WebUser.get(self.user_id)