Пример #1
0
def domains_for_user(request, selected_domain=None):
    """
    Generate pulldown menu for domains.
    Cache the entire string alongside the couch_user's doc_id that can get invalidated when
    the user doc updates via save.
    """
    domain_list = []
    if selected_domain != 'public':
        cached_domains = cache_core.get_cached_prop(request.couch_user.get_id, 'domain_list')
        if cached_domains:
            domain_list = [Domain.wrap(x) for x in cached_domains]
        else:
            try:
                domain_list = Domain.active_for_user(request.couch_user)
                cache_core.cache_doc_prop(request.couch_user.get_id, 'domain_list', [x.to_json() for x in domain_list])
            except Exception:
                if settings.DEBUG:
                    raise
                else:
                    domain_list = Domain.active_for_user(request.user)
                    notify_exception(request)
    domain_list = [dict(
        url=reverse('domain_homepage', args=[d.name]),
        name=d.long_display_name()
    ) for d in domain_list]
    context = {
        'is_public': selected_domain == 'public',
        'domain_list': domain_list,
        'current_domain': selected_domain,
    }
    template = {
        style_utils.BOOTSTRAP_2: 'hqwebapp/partials/domain_list_dropdown.html',
        style_utils.BOOTSTRAP_3: 'style/includes/domain_list_dropdown.html',
    }[style_utils.bootstrap_version(request)]
    return mark_safe(render_to_string(template, context))
Пример #2
0
def domains_for_user(request, selected_domain=None):
    lst = list()
    lst.append('<ul class="dropdown-menu nav-list dropdown-orange">')
    new_domain_url = reverse("registration_domain")
    if selected_domain == 'public':
        # viewing the public domain with a different db, so the user's domains can't readily be accessed.
        lst.append('<li><a href="%s">Back to My Projects...</a></li>' % reverse("domain_select"))
        lst.append('<li class="divider"></li>')
    else:
        try:
            domain_list = Domain.active_for_user(request.couch_user)
        except Exception:
            if settings.DEBUG:
                raise
            else:
                domain_list = Domain.active_for_user(request.user)
                notify_exception(request)

        if len(domain_list) > 0:
            lst.append('<li class="nav-header">My Projects</li>')
            for domain in domain_list:
                default_url = reverse("domain_homepage", args=[domain.name])
                lst.append('<li><a href="%s">%s</a></li>' % (default_url, domain.long_display_name()))
        else:
            lst.append('<li class="nav-header">No Projects</li>')
    lst.append('<li class="divider"></li>')
    lst.append('<li><a href="%s">New Project...</a></li>' % new_domain_url)
    lst.append('<li><a href="%s">CommCare Exchange...</a></li>' % reverse("appstore"))
    lst.append("</ul>")

    return "".join(lst)
Пример #3
0
def register_domain(request, domain_type=None):
    domain_type = domain_type or 'commcare'
    assert domain_type in DOMAIN_TYPES
    _render = partial(render_registration_view, domain_type=domain_type)

    is_new = False
    referer_url = request.GET.get('referer', '')

    active_domains_for_user = Domain.active_for_user(request.user)
    if len(active_domains_for_user) <= 0 and not request.user.is_superuser:
        is_new = True
        domains_for_user = Domain.active_for_user(request.user, is_active=False)
        if len(domains_for_user) > 0:
            vals = dict(requested_domain=domains_for_user[0])
            return _render(request, 'registration/confirmation_waiting.html', {
                'requested_domain': domains_for_user[0]
            })

    if request.method == 'POST':
        nextpage = request.POST.get('next')
        org = request.POST.get('org')
        form = DomainRegistrationForm(request.POST)
        if form.is_valid():
            reqs_today = RegistrationRequest.get_requests_today()
            max_req = settings.DOMAIN_MAX_REGISTRATION_REQUESTS_PER_DAY
            if reqs_today >= max_req:
                vals = {'error_msg':'Number of domains requested today exceeds limit ('+str(max_req)+') - contact Dimagi',
                        'show_homepage_link': 1 }
                return _render(request, 'error.html', vals)

            request_new_domain(
                request, form, org, new_user=is_new, domain_type=domain_type)

            requested_domain = form.cleaned_data['domain_name']
            if is_new:
                vals = dict(alert_message="An email has been sent to %s." % request.user.username, requested_domain=requested_domain)
                return _render(request, 'registration/confirmation_sent.html', vals)
            else:
                messages.success(request, '<strong>The project {project_name} was successfully created!</strong> An email has been sent to {username} for your records.'.format(
                    username=request.user.username,
                    project_name=requested_domain
                ), extra_tags="html")

                if nextpage:
                    return HttpResponseRedirect(nextpage)
                if referer_url:
                    return redirect(referer_url)
                return HttpResponseRedirect(reverse("domain_homepage", args=[requested_domain]))
        else:
            if nextpage:
#                messages.error(request, "The new project could not be created! Please make sure to fill out all fields of the form.")
                return orgs_landing(request, org, form=form)
    else:
        form = DomainRegistrationForm(initial={'domain_type': domain_type})

    return _render(request, 'registration/domain_request.html', {
        'form': form,
        'is_new': is_new,
    })
Пример #4
0
def redirect_to_default(req, domain=None):
    if not req.user.is_authenticated():
        if domain != None:
            url = reverse('domain_login', args=[domain])
        else:
            try:
                from corehq.apps.prelogin.views import HomePublicView
                url = reverse(HomePublicView.urlname)
            except ImportError:
                # this happens when the prelogin app is not included.
                url = reverse('landing_page')
    else:
        if domain:
            domain = normalize_domain_name(domain)
            domains = [Domain.get_by_name(domain)]
        else:
            domains = Domain.active_for_user(req.user)
        if 0 == len(domains) and not req.user.is_superuser:
            return redirect('registration_domain', domain_type=get_domain_type(None, req))
        elif 1 == len(domains):
            if domains[0]:
                domain = domains[0].name

                if (req.couch_user.is_commcare_user()
                    and not is_mobile_worker_with_report_access(
                        req.couch_user, domain)):
                    url = reverse("cloudcare_main", args=[domain, ""])
                else:
                    url = reverse('dashboard_default', args=[domain])

            else:
                raise Http404
        else:
            url = settings.DOMAIN_SELECT_URL
    return HttpResponseRedirect(url)
Пример #5
0
def resend_confirmation(request):
    dom_req = None
    try:
        dom_req = RegistrationRequest.get_request_for_username(request.user.username)
    except Exception:
        pass


    if not dom_req:
        inactive_domains_for_user = Domain.active_for_user(request.user, is_active=False)
        if len(inactive_domains_for_user) > 0:
            for domain in inactive_domains_for_user:
                domain.is_active = True
                domain.save()
        return redirect('domain_select')

    if request.method == 'POST': # If the form has been submitted...
        try:
            send_domain_registration_email(dom_req.new_user_username, dom_req.domain, dom_req.activation_guid)
        except Exception:
            vals = {'error_msg':'There was a problem with your request',
                    'error_details':sys.exc_info(),
                    'show_homepage_link': 1 }
            return render_to_response(request, 'error.html', vals)
        else:
            vals = dict(alert_message="An email has been sent to %s." % dom_req.new_user_username, requested_domain=dom_req.domain)
            return render_to_response(request, 'registration/confirmation_sent.html', vals)

    vals = dict(requested_domain=dom_req.domain)
    return render_to_response(request, 'registration/confirmation_resend.html', vals)
Пример #6
0
def select(request, domain_select_template='domain/select.html'):

    domains_for_user = Domain.active_for_user(request.user)
    if not domains_for_user:
        return redirect('registration_domain')

    return render(request, domain_select_template, {})
Пример #7
0
def resend_confirmation(request):
    try:
        dom_req = RegistrationRequest.get_request_for_username(request.user.username)
    except Exception:
        dom_req = None
        
    if not dom_req:
        inactive_domains_for_user = Domain.active_for_user(request.user, is_active=False)
        if len(inactive_domains_for_user) > 0:
            for domain in inactive_domains_for_user:
                domain.is_active = True
                domain.save()
        return redirect('domain_select')

    _render = partial(
        render_registration_view, 
        domain_type='commtrack' if dom_req.project.commtrack_enabled else None)

    if request.method == 'POST':
        try:
            send_domain_registration_email(dom_req.new_user_username, dom_req.domain, dom_req.activation_guid)
        except Exception:
            vals = {'error_msg':'There was a problem with your request',
                    'error_details':sys.exc_info(),
                    'show_homepage_link': 1 }
            return _render(request, 'error.html', vals)
        else:
            vals = dict(alert_message="An email has been sent to %s." % dom_req.new_user_username, requested_domain=dom_req.domain)
            return _render(request, 'registration/confirmation_sent.html', vals)

    return _render(request, 'registration/confirmation_resend.html', {
        'requested_domain': dom_req.domain
    })
Пример #8
0
def register_user(request, domain_type=None):
    domain_type = domain_type or "commcare"
    assert domain_type in DOMAIN_TYPES

    context = get_domain_context(domain_type)

    if request.user.is_authenticated():
        # Redirect to a page which lets user choose whether or not to create a new account
        domains_for_user = Domain.active_for_user(request.user)
        if len(domains_for_user) == 0:
            return redirect("registration_domain")
        else:
            return redirect("homepage")
    else:
        if request.method == "POST":
            form = NewWebUserRegistrationForm(request.POST)
            if form.is_valid():
                activate_new_user(form, ip=get_ip(request))
                new_user = authenticate(username=form.cleaned_data["email"], password=form.cleaned_data["password"])
                login(request, new_user)
                return redirect("registration_domain", domain_type=domain_type)
        else:
            form = NewWebUserRegistrationForm(initial={"domain_type": domain_type})

        context.update({"form": form, "domain_type": domain_type})
        return render(request, "registration/create_new_user.html", context)
Пример #9
0
def redirect_to_default(req, domain=None):
    if not req.user.is_authenticated():
        if domain != None:
            url = reverse('domain_login', args=[domain])
        else:
            # this actually gets hijacked by the static site, but is necessary
            url = reverse('corehq.apps.hqwebapp.views.landing_page')
    else:
        if domain:
            domain = normalize_domain_name(domain)
            domains = [Domain.get_by_name(domain)]
        else:
            domains = Domain.active_for_user(req.user)
        if 0 == len(domains) and not req.user.is_superuser:
            return redirect('registration_domain')
        elif 1 == len(domains):
            if domains[0]:
                domain = domains[0].name
                if req.couch_user.is_commcare_user():
                    if not is_mobile_worker_with_report_access(
                            req.couch_user, domain):
                        url = reverse("cloudcare_main", args=[domain, ""])
                    else:
                        url = reverse("saved_reports", args=[domain])
                elif req.couch_user.can_view_reports(domain) or req.couch_user.get_viewable_reports(domain):
                    url = reverse('corehq.apps.reports.views.default', args=[domain])
                else:
                    url = reverse('corehq.apps.app_manager.views.default', args=[domain])
            else:
                raise Http404
        else:
            url = settings.DOMAIN_SELECT_URL
    return HttpResponseRedirect(url)
Пример #10
0
def select( request, 
            redirect_field_name = REDIRECT_FIELD_NAME,
            domain_select_template = 'domain/select.html' ):
    
    domains_for_user = Domain.active_for_user(request.user)
    if not domains_for_user:
        return redirect('registration_domain')
    
    redirect_to = request.REQUEST.get(redirect_field_name, '')    
    if request.method == 'POST': # If the form has been submitted...        
        form = DomainSelectionForm(domain_list=domains_for_user,
                                   data=request.POST) # A form bound to the POST data
                     
        if form.is_valid():
            # We've just checked the submitted data against a freshly-retrieved set of domains
            # associated with the user. It's safe to set the domain in the sesssion (and we'll
            # check again on views validated with the domain-checking decorator)
            form.save(request) # Needs request because it saves domain in session
    
            #  Weak attempt to give user a good UX - make sure redirect_to isn't garbage.
            domain = form.cleaned_data['domain_list'].name
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = reverse('domain_homepage', args=[domain])
            return HttpResponseRedirect(redirect_to) # Redirect after POST
    else:
        # An unbound form
        form = DomainSelectionForm( domain_list=domains_for_user ) 

    vals = dict( next = redirect_to,
                 form = form )

    return render_to_response(request, domain_select_template, vals)
Пример #11
0
def register_user(request, domain_type=None):
    domain_type = domain_type or 'commcare'
    if domain_type not in DOMAIN_TYPES:
        raise Http404()

    context = get_domain_context(domain_type)

    if request.user.is_authenticated():
        # Redirect to a page which lets user choose whether or not to create a new account
        domains_for_user = Domain.active_for_user(request.user)
        if len(domains_for_user) == 0:
            return redirect("registration_domain", domain_type=domain_type)
        else:
            return redirect("homepage")
    else:
        if request.method == 'POST':
            form = NewWebUserRegistrationForm(request.POST)
            if form.is_valid():
                activate_new_user(form, ip=get_ip(request))
                new_user = authenticate(username=form.cleaned_data['email'],
                                        password=form.cleaned_data['password'])
                login(request, new_user)
                return redirect(
                    'registration_domain', domain_type=domain_type)
        else:
            form = NewWebUserRegistrationForm(
                    initial={'domain_type': domain_type})

        context.update({
            'form': form,
            'domain_type': domain_type
        })
        return render(request, 'registration/create_new_user.html', context)
Пример #12
0
def register_user(request, domain_type=None):
    domain_type = domain_type or 'commcare'
    if domain_type not in DOMAIN_TYPES:
        raise Http404()

    prefilled_email = request.GET.get('e', '')

    context = get_domain_context(domain_type)

    if request.user.is_authenticated():
        # Redirect to a page which lets user choose whether or not to create a new account
        domains_for_user = Domain.active_for_user(request.user)
        if len(domains_for_user) == 0:
            return redirect("registration_domain", domain_type=domain_type)
        else:
            return redirect("homepage")
    else:
        if request.method == 'POST':
            form = NewWebUserRegistrationForm(request.POST)
            if form.is_valid():
                activate_new_user(form, ip=get_ip(request))
                new_user = authenticate(username=form.cleaned_data['email'],
                                        password=form.cleaned_data['password'])
                login(request, new_user)
                track_workflow.delay(new_user.email, "Requested new account")
                meta = {
                    'HTTP_X_FORWARDED_FOR': request.META.get('HTTP_X_FORWARDED_FOR'),
                    'REMOTE_ADDR': request.META.get('REMOTE_ADDR'),
                    'opt_into_emails': form.cleaned_data['email_opt_in'],
                }
                track_created_hq_account_on_hubspot.delay(new_user, request.COOKIES, meta)
                requested_domain = form.cleaned_data['hr_name']
                if form.cleaned_data['create_domain']:
                    org = None
                    try:
                        requested_domain = request_new_domain(
                            request, form, org, new_user=True, domain_type=domain_type)
                    except NameUnavailableException:
                        context.update({
                            'error_msg': _('Project name already taken - please try another'),
                            'show_homepage_link': 1
                        })
                        return render(request, 'error.html', context)

                context = get_domain_context(form.cleaned_data['domain_type']).update({
                    'alert_message': _("An email has been sent to %s.") % request.user.username,
                    'requested_domain': requested_domain,
                    'track_domain_registration': True,
                })
                return render(request, 'registration/confirmation_sent.html', context)
        else:
            form = NewWebUserRegistrationForm(
                initial={'domain_type': domain_type, 'email': prefilled_email, 'create_domain': True})

        context.update({
            'form': form,
            'domain_type': domain_type,
        })
        return render(request, 'registration/create_new_user.html', context)
Пример #13
0
def domains_for_user(request, selected_domain=None):
    """
    Generate pulldown menu for domains.
    Cache the entire string alongside the couch_user's doc_id that can get invalidated when
    the user doc updates via save.
    """


    lst = list()
    lst.append('<ul class="dropdown-menu nav-list dropdown-orange">')
    new_domain_url = reverse("registration_domain")
    if selected_domain == 'public':
        # viewing the public domain with a different db, so the user's domains can't readily be accessed.
        lst.append('<li><a href="%s">%s...</a></li>' % (reverse("domain_select"), _("Back to My Projects")))
        lst.append('<li class="divider"></li>')
    else:

        cached_domains = cache_core.get_cached_prop(request.couch_user.get_id, 'domain_list')
        if cached_domains:
            domain_list = [Domain.wrap(x) for x in cached_domains]
        else:
            try:
                domain_list = Domain.active_for_user(request.couch_user)
                cache_core.cache_doc_prop(request.couch_user.get_id, 'domain_list', [x.to_json() for x in domain_list])
            except Exception:
                if settings.DEBUG:
                    raise
                else:
                    domain_list = Domain.active_for_user(request.user)
                    notify_exception(request)

        if len(domain_list) > 0:
            lst.append('<li class="nav-header">%s</li>' % _('My Projects'))
            for domain in domain_list:
                default_url = reverse("domain_homepage", args=[domain.name])
                lst.append('<li><a href="%s">%s</a></li>' % (default_url, domain.long_display_name()))
        else:
            lst.append('<li class="nav-header">No Projects</li>')
    lst.append('<li class="divider"></li>')
    lst.append('<li><a href="%s">%s...</a></li>' % (new_domain_url, _('New Project')))
    lst.append('<li><a href="%s">%s...</a></li>' % (reverse("appstore"), _('CommCare Exchange')))
    lst.append("</ul>")

    domain_list_str = "".join(lst)
    return domain_list_str
Пример #14
0
def register_user(request):
    prefilled_email = request.GET.get('e', '')
    context = get_domain_context()

    if request.user.is_authenticated():
        # Redirect to a page which lets user choose whether or not to create a new account
        domains_for_user = Domain.active_for_user(request.user)
        if len(domains_for_user) == 0:
            return redirect("registration_domain")
        else:
            return redirect("homepage")
    else:
        if request.method == 'POST':
            form = NewWebUserRegistrationForm(request.POST)
            if form.is_valid():
                activate_new_user(form, ip=get_ip(request))
                new_user = authenticate(username=form.cleaned_data['email'],
                                        password=form.cleaned_data['password'])

                track_workflow(new_user.email, "Requested new account")

                login(request, new_user)

                requested_domain = form.cleaned_data['hr_name']
                if form.cleaned_data['create_domain']:
                    try:
                        requested_domain = request_new_domain(
                            request, form, is_new_user=True)
                    except NameUnavailableException:
                        context.update({
                            'current_page': {'page_name': _('Oops!')},
                            'error_msg': _('Project name already taken - please try another'),
                            'show_homepage_link': 1
                        })
                        return render(request, 'error.html', context)

                context.update({
                    'requested_domain': requested_domain,
                    'track_domain_registration': True,
                    'current_page': {'page_name': _('Confirmation Email Sent')},
                })
                return render(request, 'registration/confirmation_sent.html', context)
            context.update({'create_domain': form.cleaned_data['create_domain']})
        else:
            form = NewWebUserRegistrationForm(
                initial={'email': prefilled_email, 'create_domain': True})
            context.update({'create_domain': True})
            meta = get_meta(request)
            track_clicked_signup_on_hubspot(prefilled_email, request.COOKIES, meta)

        context.update({
            'form': form,
            'current_page': {'page_name': _('Create an Account')},
            'hide_password_feedback': settings.ENABLE_DRACONIAN_SECURITY_FEATURES,
            'is_register_user': True,
        })
        return render(request, 'registration/create_new_user.html', context)
Пример #15
0
 def dispatch(self, request, *args, **kwargs):
     if request.user.is_authenticated():
         # Redirect to a page which lets user choose whether or not to create a new account
         domains_for_user = Domain.active_for_user(request.user)
         if len(domains_for_user) == 0:
             return redirect("registration_domain")
         else:
             return redirect("homepage")
     response = super(UserRegistrationView, self).dispatch(request, *args, **kwargs)
     return response
Пример #16
0
def list_my_domains(request):
    domain_list = Domain.active_for_user(request.user)
    lst = list()
    lst.append('<ul class="nav nav-pills nav-stacked">')
    for domain in domain_list:
        default_url = reverse("domain_homepage", args=[domain.name])
        lst.append('<li><a href="%s">%s</a></li>' % (default_url, domain.display_name()))
    lst.append('</ul>')

    return "".join(lst)
Пример #17
0
 def get(self, request, *args, **kwargs):
     if self.is_new_user:
         pending_domains = Domain.active_for_user(request.user, is_active=False)
         if len(pending_domains) > 0:
             context = get_domain_context()
             context.update({
                 'requested_domain': pending_domains[0],
                 'current_page': {'page_name': _('Confirm Account')},
             })
             return render(request, 'registration/confirmation_waiting.html', context)
     return super(RegisterDomainView, self).get(request, *args, **kwargs)
Пример #18
0
def redirect_to_default(req, domain=None):
    if not req.user.is_authenticated:
        if domain != None:
            url = reverse('domain_login', args=[domain])
        else:
            url = reverse('login')
    elif domain and _two_factor_needed(domain, req):
        return TemplateResponse(
            request=req,
            template='two_factor/core/otp_required.html',
            status=403,
        )
    else:
        if domain:
            domain = normalize_domain_name(domain)
            domains = [Domain.get_by_name(domain)]
        else:
            domains = Domain.active_for_user(req.user)

        if 0 == len(domains) and not req.user.is_superuser:
            from corehq.apps.registration.views import track_domainless_new_user
            track_domainless_new_user(req)
            return redirect('registration_domain')
        elif 1 == len(domains):
            from corehq.apps.dashboard.views import dashboard_default
            from corehq.apps.users.models import DomainMembershipError
            if domains[0]:
                domain = domains[0].name
                couch_user = req.couch_user
                try:
                    role = couch_user.get_role(domain)
                except DomainMembershipError:
                    # commcare users without roles should always be denied access
                    if couch_user.is_commcare_user():
                        raise Http404()
                    else:
                        # web users without roles are redirected to the dashboard default
                        # view since some domains allow web users to request access if they
                        # don't have it
                        return dashboard_default(req, domain)
                else:
                    if role and role.default_landing_page:
                        url = get_redirect_url(role.default_landing_page, domain)
                    elif couch_user.is_commcare_user():
                        url = reverse(get_cloudcare_urlname(domain), args=[domain])
                    else:
                        return dashboard_default(req, domain)
            else:
                raise Http404()
        else:
            url = settings.DOMAIN_SELECT_URL
    return HttpResponseRedirect(url)
Пример #19
0
 def dispatch(self, request, *args, **kwargs):
     if request.user.is_authenticated:
         # Redirect to a page which lets user choose whether or not to create a new account
         domains_for_user = Domain.active_for_user(request.user)
         if len(domains_for_user) == 0:
             track_domainless_new_user(request)
             return redirect("registration_domain")
         else:
             return redirect("homepage")
     response = super(UserRegistrationView, self).dispatch(request, *args, **kwargs)
     if settings.IS_SAAS_ENVIRONMENT:
         ab_tests.SessionAbTest(ab_tests.DEMO_WORKFLOW_V2, request).update_response(response)
     return response
Пример #20
0
def track_domainless_new_user(request):
    if settings.UNIT_TESTING:
        # don't trigger soft assert in a test
        return
    user = request.user
    is_new_user = not (Domain.active_for_user(user) or user.is_superuser)
    if is_new_user:
        _domainless_new_user_soft_assert(
            False, ("A new user '{}' was redirected to "
                    "RegisterDomainView on '{}', which shouldn't "
                    "actually happen.").format(
                user.username, settings.SERVER_ENVIRONMENT
            )
        )
Пример #21
0
def redirect_to_default(req, domain=None):
    from corehq.apps.cloudcare.views import FormplayerMain

    if not req.user.is_authenticated():
        if domain != None:
            url = reverse('domain_login', args=[domain])
        else:
            if settings.ENABLE_PRELOGIN_SITE:
                try:
                    from corehq.apps.prelogin.views import HomePublicView
                    url = reverse(HomePublicView.urlname)
                except ImportError:
                    # this happens when the prelogin app is not included.
                    url = reverse('login')
            else:
                url = reverse('login')
    elif domain and _two_factor_needed(domain, req):
        return TemplateResponse(
            request=req,
            template='two_factor/core/otp_required.html',
            status=403,
        )
    else:
        if domain:
            domain = normalize_domain_name(domain)
            domains = [Domain.get_by_name(domain)]
        else:
            domains = Domain.active_for_user(req.user)
        if 0 == len(domains) and not req.user.is_superuser:
            return redirect('registration_domain')
        elif 1 == len(domains):
            if domains[0]:
                domain = domains[0].name
                couch_user = req.couch_user

                if (couch_user.is_commcare_user() and
                        couch_user.can_view_some_reports(domain)):
                    if toggles.USE_FORMPLAYER_FRONTEND.enabled(domain):
                        url = reverse(FormplayerMain.urlname, args=[domain])
                    else:
                        url = reverse("cloudcare_main", args=[domain, ""])
                else:
                    from corehq.apps.dashboard.views import dashboard_default
                    return dashboard_default(req, domain)

            else:
                raise Http404
        else:
            url = settings.DOMAIN_SELECT_URL
    return HttpResponseRedirect(url)
Пример #22
0
def list_my_domains(request):
    cached_val = cache_core.get_cached_prop(request.couch_user.get_id, 'list_my_domains')
    if cached_val:
        return cached_val.get('list_my_domains', "")

    domain_list = Domain.active_for_user(request.user)
    lst = list()
    lst.append('<ul class="nav nav-pills nav-stacked">')
    for domain in domain_list:
        default_url = reverse("domain_homepage", args=[domain.name])
        lst.append('<li><a href="%s">%s</a></li>' % (default_url, domain.display_name()))
    lst.append('</ul>')

    my_domain_list_str = "".join(lst)
    ret = {"list_my_domains": my_domain_list_str}
    cache_core.cache_doc_prop(request.couch_user.get_id, 'list_my_domains', ret)
    return my_domain_list_str
Пример #23
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        user = request.user
        # Lookup is done via the ContentTypes framework, stored in the domain_membership table
        # id(user) == id(request.user), so we can save a lookup into request by using 'user' alone    
        active_domains = Domain.active_for_user(user)
        user.active_domains = active_domains
        user.selected_domain = None # default case
        domain_from_session = request.session.get(_SESSION_KEY_SELECTED_DOMAIN, None)
        
        if domain_from_session and domain_from_session in active_domains:
            user.selected_domain = domain_from_session

        if not domain_from_session and len(active_domains) == 1:
            request.session[_SESSION_KEY_SELECTED_DOMAIN] = active_domains[0]
            user.selected_domain = active_domains[0]

        return None
Пример #24
0
def resend_confirmation(request):
    try:
        dom_req = RegistrationRequest.get_request_for_username(request.user.username)
    except Exception:
        dom_req = None

    if not dom_req:
        inactive_domains_for_user = Domain.active_for_user(request.user, is_active=False)
        if len(inactive_domains_for_user) > 0:
            for domain in inactive_domains_for_user:
                domain.is_active = True
                domain.save()
        return redirect('domain_select')

    context = get_domain_context()

    if request.method == 'POST':
        try:
            send_domain_registration_email(dom_req.new_user_username,
                    dom_req.domain, dom_req.activation_guid,
                    request.user.get_full_name(), request.user.first_name)
        except Exception:
            context.update({
                'current_page': {'page_name': _('Oops!')},
                'error_msg': _('There was a problem with your request'),
                'error_details': sys.exc_info(),
                'show_homepage_link': 1,
            })
            return render(request, 'error.html', context)
        else:
            context.update({
                'requested_domain': dom_req.domain,
                'current_page': {'page_name': ('Confirmation Email Sent')},
            })
            return render(request, 'registration/confirmation_sent.html',
                context)

    context.update({
        'requested_domain': dom_req.domain,
        'current_page': {'page_name': _('Resend Confirmation Email')},
    })
    return render(request, 'registration/confirmation_resend.html', context)
Пример #25
0
def resend_confirmation(request):
    try:
        dom_req = RegistrationRequest.get_request_for_username(request.user.username)
    except Exception:
        dom_req = None
        
    if not dom_req:
        inactive_domains_for_user = Domain.active_for_user(request.user, is_active=False)
        if len(inactive_domains_for_user) > 0:
            for domain in inactive_domains_for_user:
                domain.is_active = True
                domain.save()
        return redirect('domain_select')

    context = get_domain_context(dom_req.project.domain_type)

    if request.method == 'POST':
        try:
            send_domain_registration_email(dom_req.new_user_username,
                    dom_req.domain, dom_req.activation_guid,
                    request.user.get_full_name())
        except Exception:
            context.update({
                'error_msg': _('There was a problem with your request'),
                'error_details': sys.exc_info(),
                'show_homepage_link': 1,
            })
            return render(request, 'error.html', context)
        else:
            context.update({
                'alert_message': _(
                    "An email has been sent to %s.") % dom_req.new_user_username,
                'requested_domain': dom_req.domain
            })
            return render(request, 'registration/confirmation_sent.html',
                context)

    context.update({
        'requested_domain': dom_req.domain
    })
    return render(request, 'registration/confirmation_resend.html', context)
Пример #26
0
def resend_confirmation(request):
    try:
        dom_req = RegistrationRequest.get_request_for_username(request.user.username)
    except Exception:
        dom_req = None

    if not dom_req:
        inactive_domains_for_user = Domain.active_for_user(request.user, is_active=False)
        if len(inactive_domains_for_user) > 0:
            for domain in inactive_domains_for_user:
                domain.is_active = True
                domain.save()
        return redirect("domain_select")

    context = get_domain_context(dom_req.project.domain_type)

    if request.method == "POST":
        try:
            send_domain_registration_email(dom_req.new_user_username, dom_req.domain, dom_req.activation_guid)
        except Exception:
            context.update(
                {
                    "error_msg": _("There was a problem with your request"),
                    "error_details": sys.exc_info(),
                    "show_homepage_link": 1,
                }
            )
            return render(request, "error.html", context)
        else:
            context.update(
                {
                    "alert_message": _("An email has been sent to %s.") % dom_req.new_user_username,
                    "requested_domain": dom_req.domain,
                }
            )
            return render(request, "registration/confirmation_sent.html", context)

    context.update({"requested_domain": dom_req.domain})
    return render(request, "registration/confirmation_resend.html", context)
Пример #27
0
def select(request, domain_select_template='domain/select.html', do_not_redirect=False):
    domains_for_user = Domain.active_for_user(request.user)
    if not domains_for_user:
        from corehq.apps.registration.views import track_domainless_new_user
        track_domainless_new_user(request)
        return redirect('registration_domain')

    email = request.couch_user.get_email()
    open_invitations = [e for e in Invitation.by_email(email) if not e.is_expired]

    additional_context = {
        'domains_for_user': domains_for_user,
        'open_invitations': open_invitations,
        'current_page': {'page_name': _('Select A Project')},
    }

    last_visited_domain = request.session.get('last_visited_domain')
    if open_invitations \
       or do_not_redirect \
       or not last_visited_domain:
        return render(request, domain_select_template, additional_context)
    else:
        domain_obj = Domain.get_by_name(last_visited_domain)
        if domain_obj and domain_obj.is_active:
            # mirrors logic in login_and_domain_required
            if (
                request.couch_user.is_member_of(domain_obj)
                or (request.user.is_superuser and not domain_obj.restrict_superusers)
                or domain_obj.is_snapshot
            ):
                try:
                    from corehq.apps.dashboard.views import dashboard_default
                    return dashboard_default(request, last_visited_domain)
                except Http404:
                    pass

        del request.session['last_visited_domain']
        return render(request, domain_select_template, additional_context)
Пример #28
0
def domains_for_user(context, request, selected_domain=None):
    """
    Generate pulldown menu for domains.
    Cache the entire string alongside the couch_user's doc_id that can get invalidated when
    the user doc updates via save.
    """
    domain_list = []
    if selected_domain != 'public':
        domain_list = Domain.active_for_user(request.couch_user)
    domain_list = [dict(
        url=reverse('domain_homepage', args=[d.name]),
        name=d.long_display_name()
    ) for d in domain_list]
    ctxt = {
        'is_public': selected_domain == 'public',
        'domain_list': domain_list,
        'current_domain': selected_domain,
        'DOMAIN_TYPE': context['DOMAIN_TYPE']
    }
    template = {
        style_utils.BOOTSTRAP_2: 'style/bootstrap2/partials/domain_list_dropdown.html',
        style_utils.BOOTSTRAP_3: 'style/bootstrap3/partials/domain_list_dropdown.html',
    }[style_utils.get_bootstrap_version()]
    return mark_safe(render_to_string(template, ctxt))
Пример #29
0
def register_user(request):
    if request.user.is_authenticated():
        # Redirect to a page which lets user choose whether or not to create a new account
        vals = {}
        domains_for_user = Domain.active_for_user(request.user)
        if len(domains_for_user) == 0:
            return redirect("registration_domain")
        else:
            return redirect("domain_list")
    else:
        if request.method == 'POST': # If the form has been submitted...
            form = NewWebUserRegistrationForm(request.POST) # A form bound to the POST data
            if form.is_valid(): # All validation rules pass
                activate_new_user(form)
                new_user = authenticate(username=form.cleaned_data['email'],
                                        password=form.cleaned_data['password'])
                login(request, new_user)

                return redirect('registration_domain')
        else:
            form = NewWebUserRegistrationForm() # An unbound form

        vals = dict(form = form)
        return render_to_response(request, 'registration/create_new_user.html', vals)
Пример #30
0
def view_generic(request,
                 domain,
                 app_id=None,
                 module_id=None,
                 form_id=None,
                 copy_app_form=None,
                 release_manager=False):
    """
    This is the main view for the app. All other views redirect to here.

    """
    if form_id and not module_id:
        return bail(request, domain, app_id)

    app = module = form = None
    try:
        if app_id:
            app = get_app(domain, app_id)
        if module_id:
            try:
                module = app.get_module(module_id)
            except ModuleNotFoundException:
                raise Http404()
            if not module.unique_id:
                module.get_or_create_unique_id()
                app.save()
        if form_id:
            try:
                form = module.get_form(form_id)
            except IndexError:
                raise Http404()
    except ModuleNotFoundException:
        return bail(request, domain, app_id)

    # Application states that should no longer exist
    if app:
        if app.application_version == APP_V1:
            _assert = soft_assert()
            _assert(False, 'App version 1.0', {
                'domain': domain,
                'app_id': app_id
            })
            template = get_app_manager_template(
                domain,
                'app_manager/v1/no_longer_supported.html',
                'app_manager/v2/no_longer_supported.html',
            )
            return render(request, template, {
                'domain': domain,
                'app': app,
            })
        if not app.vellum_case_management:
            # Soft assert but then continue rendering; template will contain a user-facing warning
            _assert = soft_assert(['jschweers' + '@' + 'dimagi.com'])
            _assert(False, 'vellum_case_management=False', {
                'domain': domain,
                'app_id': app_id
            })

    context = get_apps_base_context(request, domain, app)
    if app and app.copy_of:
        # don't fail hard.
        return HttpResponseRedirect(
            reverse(
                "view_app",
                args=[domain, app.copy_of]  # TODO - is this right?
            ))

    # grandfather in people who set commcare sense earlier
    if app and 'use_commcare_sense' in app:
        if app['use_commcare_sense']:
            if 'features' not in app.profile:
                app.profile['features'] = {}
            app.profile['features']['sense'] = 'true'
        del app['use_commcare_sense']
        app.save()

    context.update({
        'module': module,
        'form': form,
    })

    lang = context['lang']
    if app and not module and hasattr(app, 'translations'):
        context.update({"translations": app.translations.get(lang, {})})

    if form:
        template, form_context = get_form_view_context_and_template(
            request, domain, form, context['langs'])
        context.update({
            'case_properties': get_all_case_properties(app),
            'usercase_properties': get_usercase_properties(app),
        })

        context.update(form_context)
    elif module:
        template = get_module_template(domain, module)
        # make sure all modules have unique ids
        app.ensure_module_unique_ids(should_save=True)
        module_context = get_module_view_context(app, module, lang)
        context.update(module_context)
    elif app:
        context.update(get_app_view_context(request, app))

        v2_template = ('app_manager/v2/app_view_release_manager.html'
                       if release_manager else
                       'app_manager/v2/app_view_settings.html')

        template = get_app_manager_template(domain,
                                            'app_manager/v1/app_view.html',
                                            v2_template)

        if release_manager:
            context.update(get_releases_context(request, domain, app_id))
        context.update({
            'is_app_settings_page': not release_manager,
        })
    else:
        from corehq.apps.dashboard.views import NewUserDashboardView
        if toggles.APP_MANAGER_V2.enabled(domain):
            context.update(NewUserDashboardView.get_page_context(domain))
            template = NewUserDashboardView.template_name
        else:
            return HttpResponseRedirect(
                reverse(NewUserDashboardView.urlname, args=[domain]))

    # update multimedia context for forms and modules.
    menu_host = form or module
    if menu_host:
        default_file_name = 'module%s' % module_id
        if form_id:
            default_file_name = '%s_form%s' % (default_file_name, form_id)

        specific_media = {
            'menu': {
                'menu_refs':
                app.get_menu_media(module,
                                   module_id,
                                   form=form,
                                   form_index=form_id,
                                   to_language=lang),
                'default_file_name':
                '{name}_{lang}'.format(name=default_file_name, lang=lang),
            }
        }

        if module and module.uses_media():

            def _make_name(suffix):
                return "{default_name}_{suffix}_{lang}".format(
                    default_name=default_file_name,
                    suffix=suffix,
                    lang=lang,
                )

            specific_media['case_list_form'] = {
                'menu_refs':
                app.get_case_list_form_media(module,
                                             module_id,
                                             to_language=lang),
                'default_file_name':
                _make_name('case_list_form'),
            }
            specific_media['case_list_menu_item'] = {
                'menu_refs':
                app.get_case_list_menu_item_media(module,
                                                  module_id,
                                                  to_language=lang),
                'default_file_name':
                _make_name('case_list_menu_item'),
            }
            specific_media['case_list_lookup'] = {
                'menu_refs':
                app.get_case_list_lookup_image(module, module_id),
                'default_file_name':
                '{}_case_list_lookup'.format(default_file_name),
            }

            if hasattr(module, 'product_details'):
                specific_media['product_list_lookup'] = {
                    'menu_refs':
                    app.get_case_list_lookup_image(module,
                                                   module_id,
                                                   type='product'),
                    'default_file_name':
                    '{}_product_list_lookup'.format(default_file_name),
                }

        context.update({
            'multimedia': {
                "object_map": app.get_object_map(),
                'upload_managers': {
                    'icon':
                    MultimediaImageUploadController(
                        "hqimage",
                        reverse(ProcessImageFileUploadView.name,
                                args=[app.domain, app.get_id])),
                    'audio':
                    MultimediaAudioUploadController(
                        "hqaudio",
                        reverse(ProcessAudioFileUploadView.name,
                                args=[app.domain, app.get_id])),
                },
            }
        })
        try:
            context['multimedia']['references'] = app.get_references()
        except ReportConfigurationNotFoundError:
            pass
        context['multimedia'].update(specific_media)

    error = request.GET.get('error', '')

    context.update({
        'error': error,
        'app': app,
    })

    # Pass form for Copy Application to template
    domain_names = [d.name for d in Domain.active_for_user(request.couch_user)]
    domain_names.sort()
    if app and copy_app_form is None:
        toggle_enabled = toggles.EXPORT_ZIPPED_APPS.enabled(
            request.user.username)
        copy_app_form = CopyApplicationForm(
            domain, app_id, export_zipped_apps_enabled=toggle_enabled)
        context.update({
            'domain_names': domain_names,
        })
    linked_apps_enabled = toggles.LINKED_APPS.enabled(domain)
    context.update({
        'copy_app_form': copy_app_form,
        'linked_apps_enabled': linked_apps_enabled,
    })

    context['latest_commcare_version'] = get_commcare_versions(
        request.user)[-1]

    if app and app.doc_type == 'Application' and has_privilege(
            request, privileges.COMMCARE_LOGO_UPLOADER):
        uploader_slugs = ANDROID_LOGO_PROPERTY_MAPPING.keys()
        from corehq.apps.hqmedia.controller import MultimediaLogoUploadController
        from corehq.apps.hqmedia.views import ProcessLogoFileUploadView
        context.update({
            "sessionid":
            request.COOKIES.get('sessionid'),
            'uploaders': [
                MultimediaLogoUploadController(
                    slug,
                    reverse(
                        ProcessLogoFileUploadView.name,
                        args=[domain, app_id, slug],
                    )) for slug in uploader_slugs
            ],
            "refs": {
                slug: ApplicationMediaReference(
                    app.logo_refs.get(slug, {}).get("path", slug),
                    media_class=CommCareImage,
                    module_id=app.logo_refs.get(slug, {}).get("m_id"),
                ).as_dict()
                for slug in uploader_slugs
            },
            "media_info": {
                slug: app.logo_refs.get(slug)
                for slug in uploader_slugs if app.logo_refs.get(slug)
            },
        })

    live_preview_ab = ab_tests.ABTest(ab_tests.LIVE_PREVIEW, request)
    domain_obj = Domain.get_by_name(domain)
    context.update({
        'live_preview_ab':
        live_preview_ab.context,
        'is_onboarding_domain':
        domain_obj.is_onboarding_domain,
        'show_live_preview':
        (toggles.PREVIEW_APP.enabled(domain)
         or toggles.PREVIEW_APP.enabled(request.couch_user.username)
         or (domain_obj.is_onboarding_domain
             and live_preview_ab.version == ab_tests.LIVE_PREVIEW_ENABLED))
    })

    response = render(request, template, context)

    live_preview_ab.update_response(response)
    response.set_cookie('lang', encode_if_unicode(lang))
    return response
Пример #31
0
def _get_domain_list(couch_user):
    domains = Domain.active_for_user(couch_user)
    return [{
        'url': reverse('domain_homepage', args=[domain.name]),
        'name': domain.long_display_name(),
    } for domain in domains]
Пример #32
0
def register_domain(request, domain_type=None):
    domain_type = domain_type or 'commcare'
    if domain_type not in DOMAIN_TYPES or request.couch_user.is_commcare_user(
    ):
        raise Http404()

    context = get_domain_context(domain_type)

    is_new = False
    referer_url = request.GET.get('referer', '')

    active_domains_for_user = Domain.active_for_user(request.user)
    if len(active_domains_for_user) <= 0 and not request.user.is_superuser:
        is_new = True
        domains_for_user = Domain.active_for_user(request.user,
                                                  is_active=False)
        if len(domains_for_user) > 0:
            context['requested_domain'] = domains_for_user[0]
            return render(request, 'registration/confirmation_waiting.html',
                          context)

    if request.method == 'POST':
        nextpage = request.POST.get('next')
        org = request.POST.get('org')
        form = DomainRegistrationForm(request.POST)
        if form.is_valid():
            reqs_today = RegistrationRequest.get_requests_today()
            max_req = settings.DOMAIN_MAX_REGISTRATION_REQUESTS_PER_DAY
            if reqs_today >= max_req:
                context.update({
                    'error_msg':
                    _('Number of domains requested today exceeds limit (%d) - contact Dimagi'
                      ) % max_req,
                    'show_homepage_link':
                    1
                })
                return render(request, 'error.html', context)

            try:
                domain_name = request_new_domain(request,
                                                 form,
                                                 org,
                                                 new_user=is_new,
                                                 domain_type=domain_type)
            except NameUnavailableException:
                context.update({
                    'error_msg':
                    _('Project name already taken - please try another'),
                    'show_homepage_link':
                    1
                })
                return render(request, 'error.html', context)

            if is_new:
                context.update({
                    'alert_message':
                    _("An email has been sent to %s.") % request.user.username,
                    'requested_domain':
                    domain_name,
                    'track_domain_registration':
                    True,
                })
                return render(request, 'registration/confirmation_sent.html',
                              context)
            else:
                if nextpage:
                    return HttpResponseRedirect(nextpage)
                if referer_url:
                    return redirect(referer_url)
                return HttpResponseRedirect(
                    reverse("domain_homepage", args=[domain_name]))
        else:
            if nextpage:
                return orgs_landing(request, org, form=form)
    else:
        form = DomainRegistrationForm(initial={'domain_type': domain_type})

    context.update({
        'form': form,
        'is_new': is_new,
    })
    return render(request, 'registration/domain_request.html', context)
Пример #33
0
 def is_new_user(self):
     user = self.request.user
     return not (Domain.active_for_user(user) or user.is_superuser)
Пример #34
0
def resend_confirmation(request):
    try:
        dom_req = RegistrationRequest.get_request_for_username(
            request.user.username)
    except Exception:
        dom_req = None

    if not dom_req:
        inactive_domains_for_user = Domain.active_for_user(request.user,
                                                           is_active=False)
        if len(inactive_domains_for_user) > 0:
            for domain in inactive_domains_for_user:
                domain.is_active = True
                domain.save()
        return redirect('domain_select')

    context = get_domain_context()
    default_page_name = _('Resend Confirmation Email')

    if request.method == 'POST':
        if (datetime.utcnow() - dom_req.request_time
            ).seconds < CONFIRMATION_RESEND_LIMIT_SECONDS:
            context = {
                'message_body':
                _(f'Please wait at least {CONFIRMATION_RESEND_LIMIT_SECONDS} '
                  f'seconds before requesting again.'),
                'current_page': {
                    'page_name': default_page_name
                },
            }
            return render(request, 'registration/confirmation_error.html',
                          context)
        try:
            dom_req.request_time = datetime.utcnow()
            dom_req.request_ip = get_ip(request)
            dom_req.save()
            send_domain_registration_email(dom_req.new_user_username,
                                           dom_req.domain,
                                           dom_req.activation_guid,
                                           request.user.get_full_name(),
                                           request.user.first_name)
        except Exception:
            context.update({
                'current_page': {
                    'page_name': _('Oops!')
                },
                'error_msg':
                _('There was a problem with your request'),
                'show_homepage_link':
                1,
            })
            return render(request, 'error.html', context)
        else:
            context.update({
                'requested_domain': dom_req.domain,
                'current_page': {
                    'page_name': _('Confirmation Email Sent')
                },
            })
            return render(request, 'registration/confirmation_sent.html',
                          context)

    context.update({
        'requested_domain': dom_req.domain,
        'current_page': {
            'page_name': default_page_name
        },
    })
    return render(request, 'registration/confirmation_resend.html', context)
Пример #35
0
def view_generic(request,
                 domain,
                 app_id=None,
                 module_id=None,
                 form_id=None,
                 copy_app_form=None,
                 release_manager=False,
                 module_unique_id=None,
                 form_unique_id=None):
    """
    This is the main view for the app. All other views redirect to here.

    """
    if form_id and not module_id and module_unique_id is None:
        return bail(request, domain, app_id)

    app = module = form = None
    try:
        if app_id:
            app = get_app(domain, app_id)

        if module_id:
            try:
                module = app.get_module(module_id)
            except ModuleNotFoundException:
                raise Http404()
            if not module.unique_id:
                module.get_or_create_unique_id()
                app.save()
        elif module_unique_id:
            try:
                module = app.get_module_by_unique_id(module_unique_id)
            except ModuleNotFoundException:
                raise Http404()
            module_id = module.id

        if form_id and module is not None:
            try:
                form = module.get_form(form_id)
            except IndexError:
                raise Http404()
        elif form_unique_id:
            try:
                form = app.get_form(form_unique_id)
            except FormNotFoundException:
                raise Http404()
            form_id = form.id

        if form is not None and module is None:
            # this is the case where only the form_unique_id is given
            module = form.get_module()
            module_id = module.id

    except (ModuleNotFoundException, FormNotFoundException):
        return bail(request, domain, app_id)

    # Application states that should no longer exist
    if app:
        if app.application_version == APP_V1:
            _assert = soft_assert()
            _assert(False, 'App version 1.0', {
                'domain': domain,
                'app_id': app_id
            })
            return render(request, "app_manager/no_longer_supported.html", {
                'domain': domain,
                'app': app,
            })
        if not app.vellum_case_management and not app.is_remote_app():
            # Soft assert but then continue rendering; template will contain a user-facing warning
            _assert = soft_assert(['jschweers' + '@' + 'dimagi.com'])
            _assert(False, 'vellum_case_management=False', {
                'domain': domain,
                'app_id': app_id
            })
        if (form is not None
                and "usercase_preload" in getattr(form, "actions", {})
                and form.actions.usercase_preload.preload):
            _assert = soft_assert(['dmiller' + '@' + 'dimagi.com'])
            _assert(
                False, 'User property easy refs + old-style config = bad', {
                    'domain': domain,
                    'app_id': app_id,
                    'module_id': module_id,
                    'module_unique_id': module_unique_id,
                    'form_id': form_id,
                    'form_unique_id': form_unique_id,
                })

    context = get_apps_base_context(request, domain, app)
    if app and app.copy_of:
        # redirect to "main" app rather than specific build
        return HttpResponseRedirect(
            reverse("view_app", args=[domain, app.copy_of]))

    # grandfather in people who set commcare sense earlier
    if app and 'use_commcare_sense' in app:
        if app['use_commcare_sense']:
            if 'features' not in app.profile:
                app.profile['features'] = {}
            app.profile['features']['sense'] = 'true'
        del app['use_commcare_sense']
        app.save()

    context.update({
        'module': module,
        'form': form,
    })

    lang = context['lang']
    if app and not module and hasattr(app, 'translations'):
        context.update({"translations": app.translations.get(lang, {})})

    if app and not app.is_remote_app():
        context.update({
            'add_ons': add_ons.get_dict(request, app, module, form),
            'add_ons_layout': add_ons.get_layout(request),
        })

    if form:
        template, form_context = get_form_view_context_and_template(
            request, domain, form, context['langs'])
        context.update(form_context)
    elif module:
        template = get_module_template(request.user, module)
        # make sure all modules have unique ids
        app.ensure_module_unique_ids(should_save=True)
        module_context = get_module_view_context(app, module, lang)
        context.update(module_context)
    elif app:
        context.update(get_app_view_context(request, app))

        template = 'app_manager/app_view_settings.html'
        if release_manager:
            template = 'app_manager/app_view_release_manager.html'
        if release_manager:
            context.update(get_releases_context(request, domain, app_id))
        context.update({
            'is_app_settings_page': not release_manager,
        })
    else:
        from corehq.apps.dashboard.views import DomainDashboardView
        return HttpResponseRedirect(
            reverse(DomainDashboardView.urlname, args=[domain]))

    # update multimedia context for forms and modules.
    menu_host = form or module
    if menu_host:
        default_file_name = 'module%s' % module_id
        if form:
            default_file_name = '%s_form%s' % (default_file_name, form_id)

        specific_media = [{
            'menu_refs':
            app.get_menu_media(module,
                               module_id,
                               form=form,
                               form_index=form_id,
                               to_language=lang),
            'default_file_name':
            '{name}_{lang}'.format(name=default_file_name, lang=lang),
        }]

        if not form and module and not isinstance(
                module, ReportModule) and module.uses_media():

            def _make_name(suffix):
                return "{default_name}_{suffix}_{lang}".format(
                    default_name=default_file_name,
                    suffix=suffix,
                    lang=lang,
                )

            specific_media.append({
                'menu_refs':
                app.get_case_list_form_media(module,
                                             module_id,
                                             to_language=lang),
                'default_file_name':
                _make_name('case_list_form'),
                'qualifier':
                'case_list_form_',
            })
            specific_media.append({
                'menu_refs':
                app.get_case_list_menu_item_media(module,
                                                  module_id,
                                                  to_language=lang),
                'default_file_name':
                _make_name('case_list_menu_item'),
                'qualifier':
                'case_list-menu_item_',
            })
            if (toggles.CASE_LIST_LOOKUP.enabled(request.user.username)
                    or toggles.CASE_LIST_LOOKUP.enabled(app.domain)):
                specific_media.append({
                    'menu_refs':
                    app.get_case_list_lookup_image(module, module_id),
                    'default_file_name':
                    '{}_case_list_lookup'.format(default_file_name),
                    'qualifier':
                    'case-list-lookupcase',
                })

                if hasattr(module, 'product_details'):
                    specific_media.append({
                        'menu_refs':
                        app.get_case_list_lookup_image(module,
                                                       module_id,
                                                       type='product'),
                        'default_file_name':
                        '{}_product_list_lookup'.format(default_file_name),
                        'qualifier':
                        'case-list-lookupproduct',
                    })

        uploaders = {
            'icon':
            MultimediaImageUploadController(
                "hqimage",
                reverse(ProcessImageFileUploadView.name,
                        args=[app.domain, app.get_id])),
            'audio':
            MultimediaAudioUploadController(
                "hqaudio",
                reverse(ProcessAudioFileUploadView.name,
                        args=[app.domain, app.get_id])),
        }
        context.update({
            'multimedia': {
                "object_map": app.get_object_map(),
                'upload_managers': uploaders,
                'upload_managers_js':
                {type: u.js_options
                 for type, u in six.iteritems(uploaders)},
            }
        })
        context['module_icon'] = None
        if toggles.CUSTOM_ICON_BADGES.enabled(domain):
            context[
                'module_icon'] = module.custom_icon if module.custom_icon else CustomIcon(
                )
        try:
            context['multimedia']['references'] = app.get_references()
        except ReportConfigurationNotFoundError:
            pass
        context['nav_menu_media_specifics'] = specific_media

    error = request.GET.get('error', '')

    context.update({
        'error': error,
        'app': app,
    })

    # Pass form for Copy Application to template
    domain_names = [d.name for d in Domain.active_for_user(request.couch_user)]
    domain_names.sort()
    if app and copy_app_form is None:
        toggle_enabled = toggles.EXPORT_ZIPPED_APPS.enabled(
            request.user.username)
        copy_app_form = CopyApplicationForm(
            domain, app, export_zipped_apps_enabled=toggle_enabled)
        context.update({
            'domain_names': domain_names,
        })
    linked_domains_enabled = toggles.LINKED_DOMAINS.enabled(domain)
    context.update({
        'copy_app_form': copy_app_form,
        'linked_domains_enabled': linked_domains_enabled,
    })

    context['latest_commcare_version'] = get_commcare_versions(
        request.user)[-1]

    if app and app.doc_type == 'Application' and has_privilege(
            request, privileges.COMMCARE_LOGO_UPLOADER):
        uploader_slugs = list(ANDROID_LOGO_PROPERTY_MAPPING.keys())
        from corehq.apps.hqmedia.controller import MultimediaLogoUploadController
        from corehq.apps.hqmedia.views import ProcessLogoFileUploadView
        uploaders = [
            MultimediaLogoUploadController(
                slug,
                reverse(
                    ProcessLogoFileUploadView.name,
                    args=[domain, app_id, slug],
                )) for slug in uploader_slugs
        ]
        context.update({
            "sessionid": request.COOKIES.get('sessionid'),
            "uploaders": uploaders,
            "uploaders_js": [u.js_options for u in uploaders],
            "refs": {
                slug: ApplicationMediaReference(
                    app.logo_refs.get(slug, {}).get("path", slug),
                    media_class=CommCareImage,
                    module_id=app.logo_refs.get(slug, {}).get("m_id"),
                ).as_dict()
                for slug in uploader_slugs
            },
            "media_info": {
                slug: app.logo_refs.get(slug)
                for slug in uploader_slugs if app.logo_refs.get(slug)
            },
        })

    context.update({
        'show_live_preview':
        app
        and should_show_preview_app(request, app, request.couch_user.username),
        'can_preview_form':
        request.couch_user.has_permission(domain, 'edit_data')
    })

    confirm = request.session.pop('CONFIRM', False)
    context.update({'confirm': confirm})

    response = render(request, template, context)

    response.set_cookie('lang', encode_if_unicode(lang))
    return response
Пример #36
0
def register_domain(request, domain_type=None):
    domain_type = domain_type or 'commcare'
    if domain_type not in DOMAIN_TYPES or request.couch_user.is_commcare_user(
    ):
        raise Http404()

    context = get_domain_context(domain_type)

    is_new = False
    referer_url = request.GET.get('referer', '')

    active_domains_for_user = Domain.active_for_user(request.user)
    if len(active_domains_for_user) <= 0 and not request.user.is_superuser:
        is_new = True
        domains_for_user = Domain.active_for_user(request.user,
                                                  is_active=False)
        if len(domains_for_user) > 0:
            context['requested_domain'] = domains_for_user[0]
            return render(request, 'registration/confirmation_waiting.html',
                          context)

    if request.method == 'POST':
        nextpage = request.POST.get('next')
        org = request.POST.get('org')
        form = DomainRegistrationForm(request.POST)
        if form.is_valid():
            reqs_today = RegistrationRequest.get_requests_today()
            max_req = settings.DOMAIN_MAX_REGISTRATION_REQUESTS_PER_DAY
            if reqs_today >= max_req:
                context.update({
                    'error_msg':
                    _('Number of domains requested today exceeds limit (%d) - contact Dimagi'
                      ) % max_req,
                    'show_homepage_link':
                    1
                })
                return render(request, 'error.html', context)

            request_new_domain(request,
                               form,
                               org,
                               new_user=is_new,
                               domain_type=domain_type)

            requested_domain = form.cleaned_data['domain_name']
            if is_new:
                context.update({
                    'alert_message':
                    _("An email has been sent to %s.") % request.user.username,
                    'requested_domain':
                    requested_domain
                })
                return render(request, 'registration/confirmation_sent.html',
                              context)
            else:
                messages.success(
                    request,
                    _('<strong>The project {project} was successfully created!</strong> '
                      'An email has been sent to {user} for your records.'
                      ).format(project=requested_domain,
                               user=request.user.username),
                    extra_tags="html")

                if nextpage:
                    return HttpResponseRedirect(nextpage)
                if referer_url:
                    return redirect(referer_url)
                return HttpResponseRedirect(
                    reverse("domain_homepage", args=[requested_domain]))
        else:
            if nextpage:
                return orgs_landing(request, org, form=form)
    else:
        form = DomainRegistrationForm(initial={'domain_type': domain_type})

    context.update({
        'form': form,
        'is_new': is_new,
    })
    return render(request, 'registration/domain_request.html', context)
Пример #37
0
def register_user(request, domain_type=None):
    domain_type = domain_type or 'commcare'
    if domain_type not in DOMAIN_TYPES:
        raise Http404()

    prefilled_email = request.GET.get('e', '')

    context = get_domain_context(domain_type)

    if request.user.is_authenticated():
        # Redirect to a page which lets user choose whether or not to create a new account
        domains_for_user = Domain.active_for_user(request.user)
        if len(domains_for_user) == 0:
            return redirect("registration_domain", domain_type=domain_type)
        else:
            return redirect("homepage")
    else:
        if request.method == 'POST':
            form = NewWebUserRegistrationForm(request.POST)
            if form.is_valid():
                activate_new_user(form, ip=get_ip(request))
                new_user = authenticate(username=form.cleaned_data['email'],
                                        password=form.cleaned_data['password'])
                login(request, new_user)
                track_workflow.delay(new_user.email, "Requested new account")
                meta = {
                    'HTTP_X_FORWARDED_FOR':
                    request.META.get('HTTP_X_FORWARDED_FOR'),
                    'REMOTE_ADDR':
                    request.META.get('REMOTE_ADDR'),
                    'opt_into_emails':
                    form.cleaned_data['email_opt_in'],
                }
                track_created_hq_account_on_hubspot.delay(
                    new_user, request.COOKIES, meta)
                requested_domain = form.cleaned_data['hr_name']
                if form.cleaned_data['create_domain']:
                    org = None
                    try:
                        requested_domain = request_new_domain(
                            request,
                            form,
                            org,
                            new_user=True,
                            domain_type=domain_type)
                    except NameUnavailableException:
                        context.update({
                            'error_msg':
                            _('Project name already taken - please try another'
                              ),
                            'show_homepage_link':
                            1
                        })
                        return render(request, 'error.html', context)

                context = get_domain_context(
                    form.cleaned_data['domain_type']).update({
                        'alert_message':
                        _("An email has been sent to %s.") %
                        request.user.username,
                        'requested_domain':
                        requested_domain,
                        'track_domain_registration':
                        True,
                    })
                return render(request, 'registration/confirmation_sent.html',
                              context)
        else:
            form = NewWebUserRegistrationForm(
                initial={
                    'domain_type': domain_type,
                    'email': prefilled_email,
                    'create_domain': True
                })

        context.update({
            'form': form,
            'domain_type': domain_type,
        })
        return render(request, 'registration/create_new_user.html', context)
Пример #38
0
def _get_domain_list(couch_user):
    domains = Domain.active_for_user(couch_user)
    return [
        {"url": reverse("domain_homepage", args=[domain.name]), "name": domain.long_display_name()}
        for domain in domains
    ]
Пример #39
0
def get_domain_links_for_dropdown(couch_user, view_name="domain_homepage"):
    # Returns dicts with keys 'name', 'display_name', and 'url'
    return _domains_to_links(Domain.active_for_user(couch_user), view_name)