def logout(req): referer = req.META.get('HTTP_REFERER') domain = get_domain_from_url(urlparse(referer).path) if referer else None # we don't actually do anything with the response here: django_logout(req, **{"template_name": settings.BASE_TEMPLATE}) if referer and domain: domain_login_url = reverse('domain_login', kwargs={'domain': domain}) return HttpResponseRedirect('%s' % domain_login_url) else: return HttpResponseRedirect(reverse('login'))
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)
def toggle_build_profile(request, domain, build_id, build_profile_id): build = Application.get(build_id) action = request.GET.get('action') if action and action == 'enable' and not build.is_released: messages.error(request, _("Release the build first. Can not enable profiles for unreleased versions")) return HttpResponseRedirect(reverse('download_index', args=[domain, build_id])) latest_enabled_build_profile = LatestEnabledBuildProfiles.objects.filter( app_id=build.copy_of, build_profile_id=build_profile_id ).order_by('-version').first() if action == 'enable' and latest_enabled_build_profile: if latest_enabled_build_profile.version > build.version: messages.error(request, _( "Latest version available for this profile is {}, which is " "higher than this version. Disable any higher versions first.".format( latest_enabled_build_profile.version ))) return HttpResponseRedirect(reverse('download_index', args=[domain, build_id])) if action == 'enable': build_profile = LatestEnabledBuildProfiles.objects.create( app_id=build.copy_of, version=build.version, build_profile_id=build_profile_id, build_id=build_id ) build_profile.expire_cache(domain) elif action == 'disable': build_profile = LatestEnabledBuildProfiles.objects.filter( app_id=build.copy_of, version=build.version, build_profile_id=build_profile_id, build_id=build_id ).first() build_profile.delete() build_profile.expire_cache(domain) latest_enabled_build_profile = LatestEnabledBuildProfiles.objects.filter( app_id=build.copy_of, build_profile_id=build_profile_id ).order_by('-version').first() if latest_enabled_build_profile: messages.success(request, _("Latest version for profile {} is now {}").format( build.build_profiles[build_profile_id].name, latest_enabled_build_profile.version )) else: messages.success(request, _("Latest release now available for profile {}").format( build.build_profiles[build_profile_id].name )) return HttpResponseRedirect(reverse('download_index', args=[domain, build_id]))
def release_build(request, domain, app_id, saved_app_id): is_released = request.POST.get('is_released') == 'true' if not is_released: if LatestEnabledBuildProfiles.objects.filter(build_id=saved_app_id).exists(): return json_response({'error': _('Please disable any enabled profiles to un-release this build.')}) ajax = request.POST.get('ajax') == 'true' saved_app = get_app(domain, saved_app_id) if saved_app.copy_of != app_id: raise Http404 saved_app.is_released = is_released saved_app.is_auto_generated = False saved_app.save(increment_version=False) from corehq.apps.app_manager.signals import app_post_release app_post_release.send(Application, application=saved_app) if is_released: if saved_app.build_profiles and domain_has_privilege(domain, privileges.BUILD_PROFILES): create_build_files_for_all_app_profiles.delay(domain, saved_app_id) _track_build_for_app_preview(domain, request.couch_user, app_id, 'User starred a build') if ajax: return json_response({ 'is_released': is_released, 'latest_released_version': get_latest_released_app_version(domain, app_id) }) else: return HttpResponseRedirect(reverse('release_manager', args=[domain, app_id]))
def odk_install(request, domain, app_id, with_media=False): download_target_version = request.GET.get('download_target_version') == 'true' app = get_app(domain, app_id) qr_code_view = "odk_qr_code" if not with_media else "odk_media_qr_code" build_profile_id = request.GET.get('profile') profile_url = app.odk_profile_url if not with_media else app.odk_media_profile_url kwargs = [] if build_profile_id is not None: kwargs.append('profile={profile}'.format(profile=build_profile_id)) if download_target_version: kwargs.append('download_target_version=true') if kwargs: profile_url += '?' + '&'.join(kwargs) context = { "domain": domain, "app": app, "qr_code": reverse(qr_code_view, args=[domain, app_id], params={ 'profile': build_profile_id, 'download_target_version': 'true' if download_target_version else 'false', }), "profile_url": profile_url, } return render(request, "app_manager/odk_install.html", context)
def get(self, request, *args, **kwargs): if _has_permission(self.domain, request.couch_user, self.report_config_id): context = super(DownloadUCRStatusView, self).main_context context.update({ 'domain': self.domain, 'download_id': kwargs['download_id'], 'poll_url': reverse('ucr_download_job_poll', args=[self.domain, kwargs['download_id']], params={'config_id': self.report_config_id}), 'title': _("Download Report Status"), 'progress_text': _("Preparing report download."), 'error_text': _("There was an unexpected error! Please try again or report an issue."), 'next_url': reverse(ConfigurableReportView.slug, args=[self.domain, self.report_config_id]), 'next_url_text': _("Go back to report"), }) return render(request, 'hqwebapp/soil_status_full.html', context) else: raise Http403()
def login(req): # This is a wrapper around the _login view if settings.SERVER_ENVIRONMENT in settings.ICDS_ENVS: login_url = reverse('domain_login', kwargs={'domain': 'icds-cas'}) return HttpResponseRedirect(login_url) req_params = req.GET if req.method == 'GET' else req.POST domain = req_params.get('domain', None) return _login(req, domain, get_custom_login_page(req.get_host()))
def login(req): # This is a wrapper around the _login view if settings.SERVER_ENVIRONMENT in settings.ICDS_ENVS: login_url = reverse('domain_login', kwargs={'domain': 'icds-cas'}) return HttpResponseRedirect(login_url) req_params = req.GET if req.method == 'GET' else req.POST domain = req_params.get('domain', None) return _login(req, domain)
def logout(req): referer = req.META.get('HTTP_REFERER') domain = get_domain_from_url(urlparse(referer).path) if referer else None # we don't actually do anything with the response here: django_logout(req, **{"template_name": settings.BASE_TEMPLATE}) if referer and domain and is_mobile_url(referer): mobile_mainnav_url = reverse('custom_project_report_dispatcher', args=[domain, 'mobile/mainnav']) mobile_login_url = reverse('domain_mobile_login', kwargs={'domain': domain}) return HttpResponseRedirect('%s?next=%s' % (mobile_login_url, mobile_mainnav_url)) elif referer and domain: domain_login_url = reverse('domain_login', kwargs={'domain': domain}) return HttpResponseRedirect('%s' % domain_login_url) else: return HttpResponseRedirect(reverse('login'))
def prepare_issnip_monthly_register_reports(domain, user, awcs, pdf_format, month, year): utc_now = datetime.now(pytz.utc) india_now = utc_now.astimezone(india_timezone) selected_date = date(year, month, 1) report_context = {'reports': []} pdf_files = [] for awc in awcs: pdf_hash = uuid.uuid4().hex awc_location = SQLLocation.objects.get(location_id=awc) pdf_files.append({ 'uuid': pdf_hash, 'location_name': awc_location.name.replace(' ', '_') }) report = ISSNIPMonthlyReport( config={ 'awc_id': awc_location.location_id, 'month': selected_date, 'domain': domain }) qrcode = get_qrcode("{} {}".format(awc_location.site_code, india_now.strftime('%d %b %Y'))) context = {'qrcode_64': b64encode(qrcode), 'report': report} if pdf_format == 'one': report_context['reports'].append(context) else: report_context['reports'] = [context] create_pdf_file(pdf_hash, report_context) if pdf_format == 'many': cache_key = zip_folder(pdf_files) else: cache_key = create_pdf_file(uuid.uuid4().hex, report_context) params = {'domain': domain, 'uuid': cache_key, 'format': pdf_format} return { 'domain': domain, 'uuid': cache_key, 'format': pdf_format, 'link': reverse('icds_download_pdf', params=params, absolute=True, kwargs={'domain': domain}) }
def get_releases_context(request, domain, app_id): app = get_app(domain, app_id) can_send_sms = domain_has_privilege(domain, privileges.OUTBOUND_SMS) build_profile_access = domain_has_privilege(domain, privileges.BUILD_PROFILES) prompt_settings_form = PromptUpdateSettingsForm.from_app(app, request_user=request.couch_user) context = { 'release_manager': True, 'can_send_sms': can_send_sms, 'can_view_cloudcare': has_privilege(request, privileges.CLOUDCARE), 'has_mobile_workers': get_doc_count_in_domain_by_class(domain, CommCareUser) > 0, 'latest_released_version': get_latest_released_app_version(domain, app_id), 'sms_contacts': ( get_sms_autocomplete_context(request, domain)['sms_contacts'] if can_send_sms else [] ), 'build_profile_access': build_profile_access, 'application_profile_url': reverse(LanguageProfilesView.urlname, args=[domain, app_id]), 'lastest_j2me_enabled_build': CommCareBuildConfig.latest_j2me_enabled_config().label, 'fetchLimit': request.GET.get('limit', DEFAULT_FETCH_LIMIT), 'latest_build_id': get_latest_build_id(domain, app_id), 'prompt_settings_url': reverse(PromptSettingsUpdateView.urlname, args=[domain, app_id]), 'prompt_settings_form': prompt_settings_form, 'full_name': request.couch_user.full_name, 'can_manage_releases': can_manage_releases(request.couch_user, request.domain, app_id) } if not app.is_remote_app(): context.update({ 'enable_update_prompts': app.enable_update_prompts, }) if len(app.modules) == 0: context.update({'intro_only': True}) # Multimedia is not supported for remote applications at this time. try: multimedia_state = app.check_media_state() context.update({ 'multimedia_state': multimedia_state, }) except ReportConfigurationNotFoundError: pass return context
def get_releases_context(request, domain, app_id): app = get_app(domain, app_id) can_send_sms = domain_has_privilege(domain, privileges.OUTBOUND_SMS) build_profile_access = domain_has_privilege(domain, privileges.BUILD_PROFILES) prompt_settings_form = PromptUpdateSettingsForm.from_app(app, request_user=request.couch_user) context = { 'release_manager': True, 'can_send_sms': can_send_sms, 'can_view_cloudcare': has_privilege(request, privileges.CLOUDCARE), 'has_mobile_workers': get_doc_count_in_domain_by_class(domain, CommCareUser) > 0, 'latest_released_version': get_latest_released_app_version(domain, app_id), 'sms_contacts': ( get_sms_autocomplete_context(request, domain)['sms_contacts'] if can_send_sms else [] ), 'build_profile_access': build_profile_access, 'application_profile_url': reverse(LanguageProfilesView.urlname, args=[domain, app_id]), 'lastest_j2me_enabled_build': CommCareBuildConfig.latest_j2me_enabled_config().label, 'latest_build_id': get_latest_build_id(domain, app_id), 'prompt_settings_url': reverse(PromptSettingsUpdateView.urlname, args=[domain, app_id]), 'prompt_settings_form': prompt_settings_form, 'full_name': request.couch_user.full_name, 'can_manage_releases': can_manage_releases(request.couch_user, request.domain, app_id), 'can_edit_apps': request.couch_user.can_edit_apps(), } if not app.is_remote_app(): context.update({ 'enable_update_prompts': app.enable_update_prompts, }) if len(app.modules) == 0: context.update({'intro_only': True}) # Multimedia is not supported for remote applications at this time. try: multimedia_state = app.check_media_state() context.update({ 'multimedia_state': multimedia_state, }) except ReportConfigurationNotFoundError: pass return context
def unsubscribe(request, user_id): # todo in the future we should not require a user to be logged in to unsubscribe. from django.contrib import messages from corehq.apps.settings.views import MyAccountSettingsView messages.info(request, _('Check "Opt out of emails about new features ' 'and other CommCare updates" in your account ' 'settings and then click "Update Information" ' 'if you do not want to receive future emails ' 'from us.')) return HttpResponseRedirect(reverse(MyAccountSettingsView.urlname))
def export_ucr_async(report_export, download_id, user): use_transfer = settings.SHARED_DRIVE_CONF.transfer_enabled ascii_title = report_export.title.encode('ascii', 'replace').decode('utf-8') filename = '{}.xlsx'.format(ascii_title.replace('/', '?')) file_path = get_download_file_path(use_transfer, filename) report_export.create_export(file_path, Format.XLS_2007) expose_download(use_transfer, file_path, filename, download_id, 'xlsx', owner_ids=[user.get_id]) link = reverse("retrieve_download", args=[download_id], params={"get_file": '1'}, absolute=True) send_report_download_email(report_export.title, user.get_email(), link)
def export_ucr_async(report_export, download_id, user): use_transfer = settings.SHARED_DRIVE_CONF.transfer_enabled ascii_title = report_export.title.encode('ascii', 'replace').decode('utf-8') filename = '{}.xlsx'.format(ascii_title.replace('/', '?')) file_path = get_download_file_path(use_transfer, filename) report_export.create_export(file_path, Format.XLS_2007) expose_download(use_transfer, file_path, filename, download_id, 'xlsx') link = reverse("retrieve_download", args=[download_id], params={"get_file": '1'}, absolute=True) send_report_download_email(report_export.title, user.get_email(), link)
def deal_with_doc(doc, domain, doc_info_fn): if request.couch_user.is_superuser or (domain and request.couch_user.is_domain_admin(domain)): doc_info = doc_info_fn(doc) else: raise Http404() if redirect and doc_info.link: messages.info(request, _("We've redirected you to the %s matching your query") % doc_info.type_display) return HttpResponseRedirect(doc_info.link) elif request.couch_user.is_superuser: return HttpResponseRedirect('{}?id={}'.format(reverse('raw_couch'), doc.get('_id'))) else: return json_response(doc_info)
def _handle_list_view(request): try: res = get_list(request.domain, request.GET.dict()) except UserError as e: return JsonResponse({'error': str(e)}, status=400) if 'next' in res: res['next'] = reverse('case_api', args=[request.domain], params=res['next'], absolute=True) return JsonResponse(res)
def login(req): # this view, and the one below, is overridden because # we need to set the base template to use somewhere # somewhere that the login page can access it. if settings.SERVER_ENVIRONMENT == 'icds': login_url = reverse('domain_login', kwargs={'domain': 'icds-cas'}) return HttpResponseRedirect(login_url) req_params = req.GET if req.method == 'GET' else req.POST domain = req_params.get('domain', None) return _login(req, domain, "login_and_password/login.html")
def export_ucr_async(export_table, download_id, title, user): use_transfer = settings.SHARED_DRIVE_CONF.transfer_enabled filename = '{}.xlsx'.format(title.replace('/', '?')) file_path = get_download_file_path(use_transfer, filename) export_from_tables(export_table, file_path, Format.XLS_2007) expose_download(use_transfer, file_path, filename, download_id, 'xlsx') link = reverse("retrieve_download", args=[download_id], params={"get_file": '1'}, absolute=True) send_report_download_email(title, user, link)
def deal_with_doc(doc, domain, doc_info_fn): if request.couch_user.is_superuser or (domain and request.couch_user.is_member_of(domain)): doc_info = doc_info_fn(doc) else: raise Http404() if redirect and doc_info.link: messages.info(request, _("We've redirected you to the %s matching your query") % doc_info.type_display) return HttpResponseRedirect(doc_info.link) elif redirect and request.couch_user.is_superuser: return HttpResponseRedirect('{}?id={}'.format(reverse('raw_couch'), doc.get('_id'))) else: return json_response(doc_info)
def _login(req, domain_name, template_name): if req.user.is_authenticated and req.method == "GET": redirect_to = req.GET.get('next', '') if redirect_to: return HttpResponseRedirect(redirect_to) if not domain_name: return HttpResponseRedirect(reverse('homepage')) else: return HttpResponseRedirect(reverse('domain_homepage', args=[domain_name])) if req.method == 'POST' and domain_name and '@' not in req.POST.get('auth-username', '@'): req.POST._mutable = True req.POST['auth-username'] = format_username(req.POST['auth-username'], domain_name) req.POST._mutable = False req.base_template = settings.BASE_TEMPLATE context = {} custom_landing_page = getattr(settings, 'CUSTOM_LANDING_TEMPLATE', False) if custom_landing_page: template_name = custom_landing_page elif domain_name: domain = Domain.get_by_name(domain_name) req_params = req.GET if req.method == 'GET' else req.POST context.update({ 'domain': domain_name, 'hr_name': domain.display_name() if domain else domain_name, 'next': req_params.get('next', '/a/%s/' % domain), 'allow_domain_requests': domain.allow_domain_requests, 'current_page': {'page_name': _('Welcome back to %s!') % domain.display_name()} }) else: context.update({ 'current_page': {'page_name': _('Welcome back to CommCare HQ!')} }) auth_view = HQLoginView if not domain_name else CloudCareLoginView return auth_view.as_view(template_name=template_name, extra_context=context)(req)
def retrieve_download(req, domain, download_id, template="hqwebapp/includes/file_download.html"): next_url = req.GET.get('next', reverse('my_project_settings', args=[domain])) return soil_views.retrieve_download(req, download_id, template, extra_context={ 'domain': domain, 'next_url': next_url })
def release_build(request, domain, app_id, saved_app_id): is_released = request.POST.get('is_released') == 'true' ajax = request.POST.get('ajax') == 'true' saved_app = get_app(domain, saved_app_id) if saved_app.copy_of != app_id: raise Http404 saved_app.is_released = is_released saved_app.save(increment_version=False) from corehq.apps.app_manager.signals import app_post_release app_post_release.send(Application, application=saved_app) if ajax: return json_response({'is_released': is_released}) else: return HttpResponseRedirect(reverse('release_manager', args=[domain, app_id]))
def odk_install(request, domain, app_id, with_media=False): app = get_app(domain, app_id) qr_code_view = "odk_qr_code" if not with_media else "odk_media_qr_code" build_profile_id = request.GET.get('profile') profile_url = app.odk_profile_display_url if not with_media else app.odk_media_profile_display_url if build_profile_id is not None: profile_url += '?profile={profile}'.format(profile=build_profile_id) context = { "domain": domain, "app": app, "qr_code": reverse("corehq.apps.app_manager.views.%s" % qr_code_view, args=[domain, app_id], params={'profile': build_profile_id}), "profile_url": profile_url, } return render(request, "app_manager/odk_install.html", context)
def create_two_module_app(self, domain_name, app_name): app = Application.new_app(domain_name, app_name) app.add_module(Module.new_module('Module 1', None)) app.add_module(Module.new_module('Module 2', None)) for m_id in range(2): app.new_form(m_id, "Form", None) app.save() print "Application {app_name}: {app_url} created in domain {domain_name}".format( app_name=app_name, app_url=reverse('view_app', args=[domain_name, app._id], absolute=True), domain_name=domain_name )
def post(self, req, *args, **kwargs): email = self._get_email_message( post_params=req.POST, couch_user=req.couch_user, uploaded_file=req.FILES.get('report_issue')) email.send(fail_silently=False) if req.POST.get('five-hundred-report'): messages.success( req, _("Your CommCare HQ Issue Report has been sent. We are working quickly to resolve this problem." )) return HttpResponseRedirect(reverse('homepage')) return HttpResponse()
def odk_install(request, domain, app_id, with_media=False): app = get_app(domain, app_id) qr_code_view = "odk_qr_code" if not with_media else "odk_media_qr_code" build_profile_id = request.GET.get('profile') profile_url = app.odk_profile_display_url if not with_media else app.odk_media_profile_display_url if build_profile_id: profile_url += '?profile={profile}'.format(profile=build_profile_id) context = { "domain": domain, "app": app, "qr_code": reverse("corehq.apps.app_manager.views.%s" % qr_code_view, args=[domain, app_id], params={'profile': build_profile_id}), "profile_url": profile_url, } return render(request, "app_manager/odk_install.html", context)
def prepare_issnip_monthly_register_reports(domain, awcs, pdf_format, month, year, couch_user): selected_date = date(year, month, 1) report_context = { 'reports': [], 'user_have_access_to_features': icds_pre_release_features(couch_user), } pdf_files = [] report_data = ISSNIPMonthlyReport( config={ 'awc_id': awcs, 'month': selected_date, 'domain': domain }, icds_feature_flag=icds_pre_release_features(couch_user)).to_pdf_format if pdf_format == 'one': report_context['reports'] = report_data cache_key = create_pdf_file(report_context) else: for data in report_data: report_context['reports'] = [data] pdf_hash = create_pdf_file(report_context) pdf_files.append({ 'uuid': pdf_hash, 'location_name': data['awc_name'] }) cache_key = zip_folder(pdf_files) params = {'domain': domain, 'uuid': cache_key, 'format': pdf_format} return { 'domain': domain, 'uuid': cache_key, 'format': pdf_format, 'link': reverse('icds_download_pdf', params=params, absolute=True, kwargs={'domain': domain}) }
def get_url(cls, domain=None, render_as=None, relative=False, **kwargs): # NOTE: I'm pretty sure this doesn't work if you ever pass in render_as # but leaving as is for now, as it should be obvious as soon as that # breaks something if isinstance(cls, cls): domain = getattr(cls, 'domain') render_as = getattr(cls, 'rendered_as') if render_as is not None and render_as not in cls.dispatcher.allowed_renderings(): raise ValueError('The render_as parameter is not one of the following allowed values: %s' % ', '.join(cls.dispatcher.allowed_renderings())) url_args = [domain] if domain is not None else [] if render_as is not None: url_args.append(render_as+'/') if relative: return reverse(cls.dispatcher.name(), args=url_args + [cls.slug]) return absolute_reverse(cls.dispatcher.name(), args=url_args + [cls.slug])
def dropbox_upload(request, download_id): download = DownloadBase.get(download_id) if download is None: logging.error( "Download file request for expired/nonexistent file requested") raise Http404 if download.owner_ids and request.couch_user.get_id not in download.owner_ids: return no_permissions( request, message= _("You do not have access to this file. It can only be uploaded to dropbox by the user who created it" )) filename = download.get_filename() # Hack to get target filename from content disposition match = re.search('filename="([^"]*)"', download.content_disposition) dest = match.group(1) if match else 'download.txt' try: uploader = DropboxUploadHelper.create( request.session.get(DROPBOX_ACCESS_TOKEN), src=filename, dest=dest, download_id=download_id, user=request.user, ) except DropboxInvalidToken: return HttpResponseRedirect(reverse(DropboxAuthInitiate.slug)) except DropboxUploadAlreadyInProgress: uploader = DropboxUploadHelper.objects.get(download_id=download_id) messages.warning( request, 'The file is in the process of being synced to dropbox! It is {0:.2f}% ' 'complete.'.format(uploader.progress * 100)) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) uploader.upload() messages.success( request, _("Apps/{app}/{dest} is queued to sync to dropbox! You will receive an email when it" " completes.".format(app=settings.DROPBOX_APP_NAME, dest=dest))) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
def post(self, request, *args, **kwargs): base_application_form = self.base_application_form(data=self.request.POST) hq_application_form = self.hq_application_form(data=self.request.POST) if base_application_form.is_valid() and hq_application_form.is_valid(): base_application_form.instance.user = self.request.user base_application = base_application_form.save() HQOauthApplication.objects.create( application=base_application, **hq_application_form.cleaned_data, ) else: return self.render_to_response(self.get_context_data( forms=[base_application_form, hq_application_form] )) return HttpResponseRedirect(reverse('oauth2_provider:detail', args=[str(base_application.id)]))
def release_build(request, domain, app_id, saved_app_id): is_released = request.POST.get('is_released') == 'true' if not is_released: if (LatestEnabledBuildProfiles.objects.filter(build_id=saved_app_id, active=True).exists() or AppReleaseByLocation.objects.filter(build_id=saved_app_id, active=True).exists()): return json_response({ 'error': _('Please disable any enabled profiles/location restriction ' 'to un-release this build.') }) ajax = request.POST.get('ajax') == 'true' saved_app = get_app(domain, saved_app_id) if saved_app.copy_of != app_id: raise Http404 saved_app.is_released = is_released saved_app.last_released = datetime.datetime.utcnow( ) if is_released else None saved_app.is_auto_generated = False saved_app.save(increment_version=False) get_latest_released_app_versions_by_app_id.clear(domain) get_latest_released_build_id.clear(domain, app_id) from corehq.apps.app_manager.signals import app_post_release app_post_release.send(Application, application=saved_app) if is_released: if saved_app.build_profiles and domain_has_privilege( domain, privileges.BUILD_PROFILES): create_build_files_for_all_app_profiles.delay(domain, saved_app_id) _track_build_for_app_preview(domain, request.couch_user, app_id, 'User starred a build') if ajax: return json_response({ 'is_released': is_released, 'latest_released_version': get_latest_released_app_version(domain, app_id) }) else: return HttpResponseRedirect( reverse('release_manager', args=[domain, app_id]))
def toggle_build_profile(request, domain, build_id, build_profile_id): build = get_app_cached(request.domain, build_id) status = request.GET.get('action') == 'enable' try: LatestEnabledBuildProfiles.update_status(build, build_profile_id, status) except ValidationError as e: messages.error(request, e) else: latest_enabled_build_profile = LatestEnabledBuildProfiles.for_app_and_profile( build.copy_of, build_profile_id) if latest_enabled_build_profile: messages.success(request, _("Latest version for profile {} is now {}").format( build.build_profiles[build_profile_id].name, latest_enabled_build_profile.version )) else: messages.success(request, _("Latest release now available for profile {}").format( build.build_profiles[build_profile_id].name )) return HttpResponseRedirect(reverse('download_index', args=[domain, build_id]))
def release_build(request, domain, app_id, saved_app_id): is_released = request.POST.get('is_released') == 'true' ajax = request.POST.get('ajax') == 'true' saved_app = get_app(domain, saved_app_id) if saved_app.copy_of != app_id: raise Http404 saved_app.is_released = is_released saved_app.save(increment_version=False) from corehq.apps.app_manager.signals import app_post_release app_post_release.send(Application, application=saved_app) if is_released: if saved_app.build_profiles and domain_has_privilege(domain, privileges.BUILD_PROFILES): create_build_files_for_all_app_profiles.delay(domain, saved_app_id) _track_build_for_app_preview(domain, request.couch_user, app_id, 'User starred a build') if ajax: return json_response({'is_released': is_released}) else: return HttpResponseRedirect(reverse('release_manager', args=[domain, app_id]))
def get_releases_context(request, domain, app_id): app = get_app(domain, app_id) context = get_apps_base_context(request, domain, app) can_send_sms = domain_has_privilege(domain, privileges.OUTBOUND_SMS) build_profile_access = domain_has_privilege(domain, privileges.BUILD_PROFILES) context.update({ 'release_manager': True, 'can_send_sms': can_send_sms, 'has_mobile_workers': get_doc_count_in_domain_by_class(domain, CommCareUser) > 0, 'sms_contacts': (get_sms_autocomplete_context( request, domain)['sms_contacts'] if can_send_sms else []), 'build_profile_access': build_profile_access, 'application_profile_url': reverse(LanguageProfilesView.urlname, args=[domain, app_id]), 'lastest_j2me_enabled_build': CommCareBuildConfig.latest_j2me_enabled_config().label, 'fetchLimit': request.GET.get('limit', DEFAULT_FETCH_LIMIT), 'latest_build_id': get_latest_build_id(domain, app_id) }) if not app.is_remote_app(): if toggles.APP_MANAGER_V2.enabled(request.user.username) and len( app.modules) == 0: context.update({'intro_only': True}) # Multimedia is not supported for remote applications at this time. try: multimedia_state = app.check_media_state() context.update({ 'multimedia_state': multimedia_state, }) except ReportConfigurationNotFoundError: pass return context
def quick_find(request): query = request.GET.get('q') redirect = request.GET.get('redirect') != 'false' if not query: return HttpResponseBadRequest('GET param "q" must be provided') result = lookup_doc_id(query) if not result: raise Http404() is_member = result.domain and request.couch_user.is_member_of(result.domain, allow_mirroring=True) if is_member or request.couch_user.is_superuser: doc_info = get_doc_info(result.doc) else: raise Http404() if redirect and doc_info.link: messages.info(request, _("We've redirected you to the %s matching your query") % doc_info.type_display) return HttpResponseRedirect(doc_info.link) elif redirect and request.couch_user.is_superuser: return HttpResponseRedirect('{}?id={}'.format(reverse('raw_doc'), result.doc_id)) else: return JsonResponse(doc_info.to_json())
def prepare_issnip_monthly_register_reports(domain, awcs, pdf_format, month, year, couch_user): selected_date = date(year, month, 1) report_context = { 'reports': [], 'user_have_access_to_features': icds_pre_release_features(couch_user), } pdf_files = {} report_data = ISSNIPMonthlyReport(config={ 'awc_id': awcs, 'month': selected_date, 'domain': domain }, icds_feature_flag=icds_pre_release_features(couch_user)).to_pdf_format if pdf_format == 'one': report_context['reports'] = report_data cache_key = create_pdf_file(report_context) else: for data in report_data: report_context['reports'] = [data] pdf_hash = create_pdf_file(report_context) pdf_files.update({ pdf_hash: data['awc_name'] }) cache_key = zip_folder(pdf_files) params = { 'domain': domain, 'uuid': cache_key, 'format': pdf_format } return { 'domain': domain, 'uuid': cache_key, 'format': pdf_format, 'link': reverse('icds_download_pdf', params=params, absolute=True, kwargs={'domain': domain}) }
def dropbox_upload(request, download_id): download = DownloadBase.get(download_id) if download is None: logging.error("Download file request for expired/nonexistent file requested") raise Http404 else: filename = download.get_filename() # Hack to get target filename from content disposition match = re.search('filename="([^"]*)"', download.content_disposition) dest = match.group(1) if match else 'download.txt' try: uploader = DropboxUploadHelper.create( request.session.get(DROPBOX_ACCESS_TOKEN), src=filename, dest=dest, download_id=download_id, user=request.user, ) except DropboxInvalidToken: return HttpResponseRedirect(reverse(DropboxAuthInitiate.slug)) except DropboxUploadAlreadyInProgress: uploader = DropboxUploadHelper.objects.get(download_id=download_id) messages.warning( request, 'The file is in the process of being synced to dropbox! It is {0:.2f}% ' 'complete.'.format(uploader.progress * 100) ) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) uploader.upload() messages.success( request, _("Apps/{app}/{dest} is queued to sync to dropbox! You will receive an email when it" " completes.".format(app=settings.DROPBOX_APP_NAME, dest=dest)) ) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
def post(self, req, *args, **kwargs): report = dict([(key, req.POST.get(key, '')) for key in ( 'subject', 'username', 'domain', 'url', 'message', 'app_id', 'cc', 'email', '500traceback', 'sentry_id', )]) try: couch_user = req.couch_user full_name = couch_user.full_name if couch_user.is_commcare_user(): email = report['email'] else: email = couch_user.get_email() except Exception: full_name = None email = report['email'] report['full_name'] = full_name report['email'] = email or report['username'] if report['domain']: domain = report['domain'] elif len(couch_user.domains) == 1: # This isn't a domain page, but the user has only one domain, so let's use that domain = couch_user.domains[0] else: domain = "<no domain>" message = ("username: {username}\n" "full name: {full_name}\n" "domain: {domain}\n" "url: {url}\n").format(**report) domain_object = Domain.get_by_name( domain) if report['domain'] else None debug_context = { 'datetime': datetime.utcnow(), 'self_started': '<unknown>', 'scale_backend': '<unknown>', 'has_handoff_info': '<unknown>', 'project_description': '<unknown>', 'sentry_error': '{}{}'.format(getattr(settings, 'SENTRY_QUERY_URL', ''), report['sentry_id']) } if domain_object: current_project_description = domain_object.project_description if domain_object else None new_project_description = req.POST.get('project_description') if (domain_object and req.couch_user.is_domain_admin(domain=domain) and new_project_description and current_project_description != new_project_description): domain_object.project_description = new_project_description domain_object.save() message += (("software plan: {software_plan}\n").format( software_plan=Subscription.get_subscribed_plan_by_domain( domain), )) debug_context.update({ 'self_started': domain_object.internal.self_started, 'scale_backend': should_use_sql_backend(domain), 'has_handoff_info': bool(domain_object.internal.partner_contact), 'project_description': domain_object.project_description, }) subject = '{subject} ({domain})'.format(subject=report['subject'], domain=domain) cc = [el for el in report['cc'].strip().split(",") if el] if full_name and not any([c in full_name for c in '<>"']): reply_to = '"{full_name}" <{email}>'.format(**report) else: reply_to = report['email'] # if the person looks like a commcare user, fogbugz can't reply # to their email, so just use the default if settings.HQ_ACCOUNT_ROOT in reply_to: reply_to = settings.SERVER_EMAIL message += "Message:\n\n{message}\n".format(message=report['message']) if req.POST.get('five-hundred-report'): extra_message = ( "This message was reported from a 500 error page! " "Please fix this ASAP (as if you wouldn't anyway)...") extra_debug_info = ( "datetime: {datetime}\n" "Is self start: {self_started}\n" "Is scale backend: {scale_backend}\n" "Has Support Hand-off Info: {has_handoff_info}\n" "Project description: {project_description}\n" "Sentry Error: {sentry_error}\n").format(**debug_context) traceback_info = cache.cache.get( report['500traceback']) or 'No traceback info available' cache.cache.delete(report['500traceback']) message = "\n\n".join( [message, extra_debug_info, extra_message, traceback_info]) email = EmailMessage(subject=subject, body=message, to=self.recipients, headers={'Reply-To': reply_to}, cc=cc) uploaded_file = req.FILES.get('report_issue') if uploaded_file: filename = uploaded_file.name content = uploaded_file.read() email.attach(filename=filename, content=content) # only fake the from email if it's an @dimagi.com account is_icds_env = settings.SERVER_ENVIRONMENT in settings.ICDS_ENVS if re.search(r'@dimagi\.com$', report['username']) and not is_icds_env: email.from_email = report['username'] else: email.from_email = settings.CCHQ_BUG_REPORT_EMAIL email.send(fail_silently=False) if req.POST.get('five-hundred-report'): messages.success( req, "Your CommCare HQ Issue Report has been sent. We are working quickly to resolve this problem." ) return HttpResponseRedirect(reverse('homepage')) return HttpResponse()
def page_url(self): return reverse(self.urlname, args=[self.domain, self.first_app_id, self.second_app_id])
def _login(req, domain_name, custom_login_page, extra_context=None): extra_context = extra_context or {} if req.user.is_authenticated and req.method == "GET": redirect_to = req.GET.get('next', '') if redirect_to: return HttpResponseRedirect(redirect_to) if not domain_name: return HttpResponseRedirect(reverse('homepage')) else: return HttpResponseRedirect( reverse('domain_homepage', args=[domain_name])) if req.method == 'POST' and domain_name and '@' not in req.POST.get( 'auth-username', '@'): with mutable_querydict(req.POST): req.POST['auth-username'] = format_username( req.POST['auth-username'], domain_name) if 'auth-username' in req.POST: couch_user = CouchUser.get_by_username( req.POST['auth-username'].lower()) if couch_user: new_lang = couch_user.language old_lang = req.session.get(LANGUAGE_SESSION_KEY) update_session_language(req, old_lang, new_lang) req.base_template = settings.BASE_TEMPLATE context = {} context.update(extra_context) template_name = custom_login_page if custom_login_page else 'login_and_password/login.html' if not custom_login_page and domain_name: domain_obj = Domain.get_by_name(domain_name) req_params = req.GET if req.method == 'GET' else req.POST context.update({ 'domain': domain_name, 'hr_name': domain_obj.display_name(), 'next': req_params.get('next', '/a/%s/' % domain_name), 'allow_domain_requests': domain_obj.allow_domain_requests, 'current_page': { 'page_name': _('Welcome back to %s!') % domain_obj.display_name() }, }) else: commcare_hq_name = commcare_hq_names( req)['commcare_hq_names']["COMMCARE_HQ_NAME"] context.update({ 'current_page': { 'page_name': _('Welcome back to %s!') % commcare_hq_name }, }) if settings.SERVER_ENVIRONMENT in settings.ICDS_ENVS: auth_view = CloudCareLoginView else: auth_view = HQLoginView if not domain_name else CloudCareLoginView demo_workflow_ab_v2 = ab_tests.SessionAbTest(ab_tests.DEMO_WORKFLOW_V2, req) if settings.IS_SAAS_ENVIRONMENT: context['demo_workflow_ab_v2'] = demo_workflow_ab_v2.context response = auth_view.as_view(template_name=template_name, extra_context=context)(req) if settings.IS_SAAS_ENVIRONMENT: demo_workflow_ab_v2.update_response(response) return response
def page_url(self): return reverse(self.urlname)
def create_alert(request): from corehq.apps.hqwebapp.models import MaintenanceAlert alert_text = request.POST.get('alert_text') domains = request.POST.get('domains').split() or None MaintenanceAlert(active=False, text=alert_text, domains=domains).save() return HttpResponseRedirect(reverse('alerts'))
def deactivate_alert(request): from corehq.apps.hqwebapp.models import MaintenanceAlert ma = MaintenanceAlert.objects.get(id=request.POST.get('alert_id')) ma.active = False ma.save() return HttpResponseRedirect(reverse('alerts'))
def prepare_excel_reports(config, aggregation_level, include_test, beta, location, domain, file_format, indicator): if indicator == CHILDREN_EXPORT: data_type = 'Children' excel_data = ChildrenExport( config=config, loc_level=aggregation_level, show_test=include_test, beta=beta ).get_excel_data(location) elif indicator == PREGNANT_WOMEN_EXPORT: data_type = 'Pregnant_Women' excel_data = PregnantWomenExport( config=config, loc_level=aggregation_level, show_test=include_test ).get_excel_data(location) elif indicator == DEMOGRAPHICS_EXPORT: data_type = 'Demographics' excel_data = DemographicsExport( config=config, loc_level=aggregation_level, show_test=include_test, beta=beta ).get_excel_data(location) elif indicator == SYSTEM_USAGE_EXPORT: data_type = 'System_Usage' excel_data = SystemUsageExport( config=config, loc_level=aggregation_level, show_test=include_test ).get_excel_data(location) elif indicator == AWC_INFRASTRUCTURE_EXPORT: data_type = 'AWC_Infrastructure' excel_data = AWCInfrastructureExport( config=config, loc_level=aggregation_level, show_test=include_test, beta=beta, ).get_excel_data(location) elif indicator == BENEFICIARY_LIST_EXPORT: # this report doesn't use this configuration config.pop('aggregation_level', None) data_type = 'Beneficiary_List' excel_data = BeneficiaryExport( config=config, loc_level=aggregation_level, show_test=include_test, beta=beta ).get_excel_data(location) elif indicator == AWW_INCENTIVE_REPORT: data_type = 'AWW_Performance' excel_data = IncentiveReport( block=location, month=config['month'] ).get_excel_data() location_object = AwcLocationMonths.objects.filter( block_id=location, aggregation_level=3 ).first() if file_format == 'xlsx': cache_key = create_aww_performance_excel_file( excel_data, data_type, config['month'].strftime("%B %Y"), location_object.state_name, location_object.district_name, location_object.block_name, ) else: cache_key = create_excel_file(excel_data, data_type, file_format) if indicator != AWW_INCENTIVE_REPORT: if file_format == 'xlsx' and beta: cache_key = create_excel_file_in_openpyxl(excel_data, data_type) else: cache_key = create_excel_file(excel_data, data_type, file_format) params = { 'domain': domain, 'uuid': cache_key, 'file_format': file_format, 'data_type': data_type, } return { 'domain': domain, 'uuid': cache_key, 'file_format': file_format, 'data_type': data_type, 'link': reverse('icds_download_excel', params=params, absolute=True, kwargs={'domain': domain}) }
def _login(req, domain_name): if req.user.is_authenticated and req.method == "GET": redirect_to = req.GET.get('next', '') if redirect_to: return HttpResponseRedirect(redirect_to) if not domain_name: return HttpResponseRedirect(reverse('homepage')) else: return HttpResponseRedirect(reverse('domain_homepage', args=[domain_name])) if req.method == 'POST' and domain_name and '@' not in req.POST.get('auth-username', '@'): with mutable_querydict(req.POST): req.POST['auth-username'] = format_username(req.POST['auth-username'], domain_name) if 'auth-username' in req.POST: couch_user = CouchUser.get_by_username(req.POST['auth-username'].lower()) if couch_user: new_lang = couch_user.language old_lang = req.session.get(LANGUAGE_SESSION_KEY) update_session_language(req, old_lang, new_lang) req.base_template = settings.BASE_TEMPLATE context = {} template_name = 'login_and_password/login.html' custom_landing_page = settings.CUSTOM_LANDING_TEMPLATE if custom_landing_page: if isinstance(custom_landing_page, six.string_types): soft_assert_type_text(custom_landing_page) template_name = custom_landing_page else: template_name = custom_landing_page.get(req.get_host()) if template_name is None: template_name = custom_landing_page.get('default', template_name) elif domain_name: domain_obj = Domain.get_by_name(domain_name) req_params = req.GET if req.method == 'GET' else req.POST context.update({ 'domain': domain_name, 'hr_name': domain_obj.display_name(), 'next': req_params.get('next', '/a/%s/' % domain_name), 'allow_domain_requests': domain_obj.allow_domain_requests, 'current_page': {'page_name': _('Welcome back to %s!') % domain_obj.display_name()}, }) else: commcare_hq_name = commcare_hq_names(req)['commcare_hq_names']["COMMCARE_HQ_NAME"] context.update({ 'current_page': {'page_name': _('Welcome back to %s!') % commcare_hq_name}, }) if settings.SERVER_ENVIRONMENT in settings.ICDS_ENVS: auth_view = CloudCareLoginView else: auth_view = HQLoginView if not domain_name else CloudCareLoginView demo_workflow_ab_v2 = ab_tests.SessionAbTest(ab_tests.DEMO_WORKFLOW_V2, req) if settings.IS_SAAS_ENVIRONMENT: context['demo_workflow_ab_v2'] = demo_workflow_ab_v2.context response = auth_view.as_view(template_name=template_name, extra_context=context)(req) if settings.IS_SAAS_ENVIRONMENT: demo_workflow_ab_v2.update_response(response) return response
def section_url(self): return reverse('reports_home', args=(self.domain, ))
def url(self): return reverse(self.slug, args=[self.domain, self.report_config_id])
def retrieve_download(req, domain, download_id, template="hqwebapp/includes/file_download.html"): next_url = req.GET.get('next', reverse('my_project_settings', args=[domain])) return soil_views.retrieve_download(req, download_id, template, extra_context={'domain': domain, 'next_url': next_url})
def page_url(self): return reverse( self.urlname, args=[self.domain, self.first_app_id, self.second_app_id])
def parent_pages(self): return [{ 'title': self.spec.title, 'url': reverse(ConfigurableReportView.slug, args=[self.domain, self.report_config_id]), }]
def post(self, req, *args, **kwargs): report = dict([(key, req.POST.get(key, '')) for key in ( 'subject', 'username', 'domain', 'url', 'message', 'app_id', 'cc', 'email', '500traceback', 'sentry_id', )]) try: couch_user = req.couch_user full_name = couch_user.full_name if couch_user.is_commcare_user(): email = report['email'] else: email = couch_user.get_email() except Exception: full_name = None email = report['email'] report['full_name'] = full_name report['email'] = email or report['username'] if report['domain']: domain = report['domain'] elif len(couch_user.domains) == 1: # This isn't a domain page, but the user has only one domain, so let's use that domain = couch_user.domains[0] else: domain = "<no domain>" message = ( "username: {username}\n" "full name: {full_name}\n" "domain: {domain}\n" "url: {url}\n" ).format(**report) domain_object = Domain.get_by_name(domain) if report['domain'] else None debug_context = { 'datetime': datetime.utcnow(), 'self_started': '<unknown>', 'scale_backend': '<unknown>', 'has_handoff_info': '<unknown>', 'project_description': '<unknown>', 'sentry_error': '{}{}'.format(getattr(settings, 'SENTRY_QUERY_URL'), report['sentry_id']) } if domain_object: current_project_description = domain_object.project_description if domain_object else None new_project_description = req.POST.get('project_description') if (domain_object and req.couch_user.is_domain_admin(domain=domain) and new_project_description and current_project_description != new_project_description): domain_object.project_description = new_project_description domain_object.save() message += (( "software plan: {software_plan}\n" ).format( software_plan=Subscription.get_subscribed_plan_by_domain(domain), )) debug_context.update({ 'self_started': domain_object.internal.self_started, 'scale_backend': should_use_sql_backend(domain), 'has_handoff_info': bool(domain_object.internal.partner_contact), 'project_description': domain_object.project_description, }) subject = '{subject} ({domain})'.format(subject=report['subject'], domain=domain) cc = [el for el in report['cc'].strip().split(",") if el] if full_name and not any([c in full_name for c in '<>"']): reply_to = '"{full_name}" <{email}>'.format(**report) else: reply_to = report['email'] # if the person looks like a commcare user, fogbugz can't reply # to their email, so just use the default if settings.HQ_ACCOUNT_ROOT in reply_to: reply_to = settings.SERVER_EMAIL message += "Message:\n\n{message}\n".format(message=report['message']) if req.POST.get('five-hundred-report'): extra_message = ("This message was reported from a 500 error page! " "Please fix this ASAP (as if you wouldn't anyway)...") extra_debug_info = ( "datetime: {datetime}\n" "Is self start: {self_started}\n" "Is scale backend: {scale_backend}\n" "Has Support Hand-off Info: {has_handoff_info}\n" "Project description: {project_description}\n" "Sentry Error: {sentry_error}\n" ).format(**debug_context) traceback_info = cache.cache.get(report['500traceback']) or 'No traceback info available' cache.cache.delete(report['500traceback']) message = "\n\n".join([message, extra_debug_info, extra_message, traceback_info]) email = EmailMessage( subject=subject, body=message, to=self.recipients, headers={'Reply-To': reply_to}, cc=cc ) uploaded_file = req.FILES.get('report_issue') if uploaded_file: filename = uploaded_file.name content = uploaded_file.read() email.attach(filename=filename, content=content) # only fake the from email if it's an @dimagi.com account is_icds_env = settings.SERVER_ENVIRONMENT in settings.ICDS_ENVS if re.search(r'@dimagi\.com$', report['username']) and not is_icds_env: email.from_email = report['username'] else: email.from_email = settings.CCHQ_BUG_REPORT_EMAIL email.send(fail_silently=False) if req.POST.get('five-hundred-report'): messages.success( req, "Your CommCare HQ Issue Report has been sent. We are working quickly to resolve this problem." ) return HttpResponseRedirect(reverse('homepage')) return HttpResponse()
def page_url(self): return reverse(self.urlname, args=self.args, kwargs=self.kwargs)