def process_response(self, request, response): language = translation.get_language() language_from_path = translation.get_language_from_path(request.path_info) urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF) i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf) if response.status_code == 404 and not language_from_path and i18n_patterns_used: language_path = '/%s%s' % (language, request.path_info) path_valid = is_valid_path(language_path, urlconf) path_needs_slash = ( not path_valid and ( settings.APPEND_SLASH and not language_path.endswith('/') and is_valid_path('%s/' % language_path, urlconf) ) ) if path_valid or path_needs_slash: script_prefix = get_script_prefix() # Insert language after the script prefix and before the # rest of the URL language_url = request.get_full_path(force_append_slash=path_needs_slash).replace( script_prefix, '%s%s/' % (script_prefix, language), 1 ) return self.response_redirect_class(language_url) if not (i18n_patterns_used and language_from_path): patch_vary_headers(response, ('Accept-Language',)) if 'Content-Language' not in response: response['Content-Language'] = language return response
def test_anonymous_redirect(self): url = reverse('banktransactions:list', kwargs={ 'bankaccount_pk': self.bankaccount.pk, }) login_url = resolve_url(settings.LOGIN_URL) admin_base_url = get_script_prefix() + settings.MYMONEY['ADMIN_BASE_URL'] # Anonymous should be redirect to login url. response = self.client.get(url, follow=True) self.assertEqual(response.request['PATH_INFO'], login_url) self.assertEqual( urlunquote(response.request['QUERY_STRING']), 'next=' + url ) # Check explicit infinite loop with anonymous. response = self.client.get(login_url, follow=True) self.assertEqual(response.request['PATH_INFO'], login_url) # However, check that anonymous could access back-office response = self.client.get(admin_base_url, follow=True) self.assertEqual(response.request['PATH_INFO'], admin_base_url + '/login/') # Authentificated user are not redirected. self.client.force_login(self.owner) response = self.client.get(url, follow=True) self.assertEqual(response.request['PATH_INFO'], url) # Check explicit infinite loop after log out. logout_url = resolve_url(settings.LOGOUT_URL) response = self.client.get(logout_url, follow=True) self.assertEqual(response.request['PATH_INFO'], login_url)
def get_language_from_request(request: HttpRequest) -> str: """ Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. """ global _supported if _supported is None: _supported = OrderedDict(settings.LANGUAGES) if request.path.startswith(get_script_prefix() + 'control'): return ( get_language_from_user_settings(request) or get_language_from_session_or_cookie(request) or get_language_from_browser(request) or get_language_from_event(request) or get_default_language() ) else: return ( get_language_from_session_or_cookie(request) or get_language_from_user_settings(request) or get_language_from_browser(request) or get_language_from_event(request) or get_default_language() )
def to_internal_value(self, data): try: http_prefix = data.startswith(('http:', 'https:')) except AttributeError: self.fail('incorrect_type', data_type=type(data).__name__) input_data = data if http_prefix: # If needed convert absolute URLs to relative path data = urlparse(data).path prefix = get_script_prefix() if data.startswith(prefix): data = '/' + data[len(prefix):] try: match = self.resolve(data) except Resolver404: self.fail('no_match') if match.view_name not in self.view_names: self.fail('incorrect_match', input=input_data) self._setup_field(match.view_name) try: return self.get_object(match.view_name, match.args, match.kwargs) except (ObjectDoesNotExist, TypeError, ValueError): self.fail('does_not_exist') return data
def add_preserved_filters(context, url, popup=False, to_field=None): opts = context.get('opts') preserved_filters = context.get('preserved_filters') parsed_url = list(urlparse(url)) parsed_qs = dict(parse_qsl(parsed_url[4])) merged_qs = {} if opts and preserved_filters: preserved_filters = dict(parse_qsl(preserved_filters)) match_url = '/%s' % url.partition(get_script_prefix())[2] try: match = resolve(match_url) except Resolver404: pass else: current_url = '%s:%s' % (match.app_name, match.url_name) changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name) if changelist_url == current_url and '_changelist_filters' in preserved_filters: preserved_filters = dict(parse_qsl(preserved_filters['_changelist_filters'])) merged_qs.update(preserved_filters) if popup: from django.contrib.admin.options import IS_POPUP_VAR merged_qs[IS_POPUP_VAR] = 1 if to_field: from django.contrib.admin.options import TO_FIELD_VAR merged_qs[TO_FIELD_VAR] = to_field merged_qs.update(parsed_qs) parsed_url[4] = urlencode(merged_qs) return urlunparse(parsed_url)
def to_internal_value(self, data): request = self.context.get('request', None) try: http_prefix = data.startswith(('http:', 'https:')) except AttributeError: self.fail('incorrect_type', data_type=type(data).__name__) if http_prefix: # If needed convert absolute URLs to relative path data = urlparse.urlparse(data).path prefix = get_script_prefix() if data.startswith(prefix): data = '/' + data[len(prefix):] data = uri_to_iri(data) try: match = resolve(data) except Resolver404: self.fail('no_match') try: expected_viewname = request.versioning_scheme.get_versioned_viewname( self.view_name, request ) except AttributeError: expected_viewname = self.view_name if match.view_name != expected_viewname: self.fail('incorrect_match') try: return self.get_object(match.view_name, match.args, match.kwargs) except (ObjectDoesNotExist, TypeError, ValueError): self.fail('does_not_exist')
def process_request(self, request: HttpRequest): language = get_language_from_request(request) # Normally, this middleware runs *before* the event is set. However, on event frontend pages it # might be run a second time by pretix.presale.EventMiddleware and in this case the event is already # set and can be taken into account for the decision. if hasattr(request, 'event') and not request.path.startswith(get_script_prefix() + 'control'): if language not in request.event.settings.locales: firstpart = language.split('-')[0] if firstpart in request.event.settings.locales: language = firstpart else: language = request.event.settings.locale for lang in request.event.settings.locales: if lang.startswith(firstpart + '-'): language = lang break translation.activate(language) request.LANGUAGE_CODE = translation.get_language() tzname = None if hasattr(request, 'event'): tzname = request.event.settings.timezone elif request.user.is_authenticated: tzname = request.user.timezone if tzname: try: timezone.activate(pytz.timezone(tzname)) request.timezone = tzname except pytz.UnknownTimeZoneError: pass else: timezone.deactivate()
def generate_js(default_urlresolver): js_var_name = getattr(settings, 'JS_REVERSE_JS_VAR_NAME', JS_VAR_NAME) if not JS_IDENTIFIER_RE.match(js_var_name.upper()): raise ImproperlyConfigured( 'JS_REVERSE_JS_VAR_NAME setting "%s" is not a valid javascript identifier.' % (js_var_name)) js_global_object_name = getattr(settings, 'JS_REVERSE_JS_GLOBAL_OBJECT_NAME', JS_GLOBAL_OBJECT_NAME) if not JS_IDENTIFIER_RE.match(js_global_object_name.upper()): raise ImproperlyConfigured( 'JS_REVERSE_JS_GLOBAL_OBJECT_NAME setting "%s" is not a valid javascript identifier.' % ( js_global_object_name)) minfiy = getattr(settings, 'JS_REVERSE_JS_MINIFY', JS_MINIFY) if not isinstance(minfiy, bool): raise ImproperlyConfigured( 'JS_REVERSE_JS_MINIFY setting "%s" is not a valid. Needs to be set to True or False.' % (minfiy)) script_prefix_via_config = getattr(settings, 'JS_REVERSE_SCRIPT_PREFIX', None) if script_prefix_via_config: script_prefix = script_prefix_via_config if not script_prefix.endswith('/'): script_prefix = '{0}/'.format(script_prefix) else: script_prefix = urlresolvers.get_script_prefix() data = generate_json(default_urlresolver, script_prefix) js_content = loader.render_to_string('django_js_reverse/urls_js.tpl', { 'data': _safe_json(data), 'js_name': '.'.join([js_global_object_name, js_var_name]), }) if minfiy: js_content = rjsmin.jsmin(js_content) return js_content
def _page_not_found(self): # Since this view acts as a catch-all, give better error messages # when mistyping an admin URL. Don't mention anything about CMS pages in /admin. try: full_path = get_script_prefix() + self.path.lstrip('/') if full_path.startswith(reverse('admin:index')): raise Http404(u"No admin page found at '{0}'\n(raised by fluent_pages catch-all).".format(self.path)) except NoReverseMatch: # Admin might not be loaded. pass if settings.DEBUG and self.model.objects.published().count() == 0 and self.path == '/': # No pages in the database, present nice homepage. return self._intro_page() else: fallback = _get_fallback_language(self.language_code) if fallback: languages = (self.language_code, fallback) tried_msg = u" (language '{0}', fallback: '{1}')".format(*languages) else: tried_msg = u", language '{0}'".format(self.language_code) if self.path == '/': raise Http404(u"No published '{0}' found for the path '{1}'{2}. Use the 'Override URL' field to make sure a page can be found at the root of the site.".format(self.model.__name__, self.path, tried_msg)) else: raise Http404(u"No published '{0}' found for the path '{1}'{2}.".format(self.model.__name__, self.path, tried_msg))
def get_via_uri(self, uri, request=None): """ This pulls apart the salient bits of the URI and populates the resource via a ``obj_get``. Optionally accepts a ``request``. If you need custom behavior based on other portions of the URI, simply override this method. """ prefix = get_script_prefix() chomped_uri = uri if prefix and chomped_uri.startswith(prefix): chomped_uri = chomped_uri[len(prefix) - 1:] try: view, args, kwargs = resolve(chomped_uri) resource_name = kwargs['resource_name'] resource_class = self.resource_mapping[resource_name] except (Resolver404, KeyError): raise NotFound("The URL provided '%s' was not a link to a valid resource." % uri) parent_resource = resource_class(api_name=self._meta.api_name) kwargs = parent_resource.remove_api_resource_names(kwargs) bundle = Bundle(request=request) return parent_resource.obj_get(bundle, **kwargs)
def process_response(self, request, response): language = translation.get_language() language_from_path = translation.get_language_from_path(request.path_info) if response.status_code == 404 and not language_from_path and self.is_language_prefix_patterns_used: urlconf = getattr(request, "urlconf", None) language_path = "/%s%s" % (language, request.path_info) path_valid = is_valid_path(language_path, urlconf) path_needs_slash = not path_valid and ( settings.APPEND_SLASH and not language_path.endswith("/") and is_valid_path("%s/" % language_path, urlconf) ) if path_valid or path_needs_slash: script_prefix = get_script_prefix() # Insert language after the script prefix and before the # rest of the URL language_url = request.get_full_path(force_append_slash=path_needs_slash).replace( script_prefix, "%s%s/" % (script_prefix, language), 1 ) return self.response_redirect_class(language_url) if not (self.is_language_prefix_patterns_used and language_from_path): patch_vary_headers(response, ("Accept-Language",)) if "Content-Language" not in response: response["Content-Language"] = language return response
def __call__(self, request): """Redirect if ?lang query parameter is valid.""" query_lang = request.GET.get('lang') if not (query_lang and query_lang in get_kuma_languages()): # Invalid or no language requested, so don't redirect. return self.get_response(request) # Check if the requested language is already embedded in URL language = get_language_from_request(request) script_prefix = get_script_prefix() lang_prefix = '%s%s/' % (script_prefix, language) full_path = request.get_full_path() # Includes querystring old_path = urlsplit(full_path).path new_prefix = '%s%s/' % (script_prefix, query_lang) if full_path.startswith(lang_prefix): new_path = old_path.replace(lang_prefix, new_prefix, 1) else: new_path = old_path.replace(script_prefix, new_prefix, 1) # Redirect to same path with requested language and without ?lang new_query = dict((smart_str(k), v) for k, v in request.GET.items() if k != 'lang') if new_query: new_path = urlparams(new_path, **new_query) response = HttpResponseRedirect(new_path) add_shared_cache_control(response) return response
def appid(self): path = self.request.path elementy = path.split('/') base_url = get_script_prefix() nr = base_url.count('/') if elementy[nr]=='schwiki': return elementy[nr+1] else: return elementy[nr]
def login_user(request, redirect_field_name=REDIRECT_FIELD_NAME): username = password = message = '' message_class = 'danger' redirect_url = request.GET.get(redirect_field_name, '') if len(redirect_url) == 0: redirect_url = reverse_lazy('labcirs_home') if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) if user.is_superuser: return redirect('admin:index') elif hasattr(user, 'reviewer'): if user.reviewer.departments.count() > 0: return redirect('admin:index') else: message = MISSING_DEPARTMENT_MSG logout(request) elif hasattr(user, 'reporter'): if hasattr(user.reporter, 'department'): return redirect('incidents_for_department', dept=user.reporter.department.label) else: message = MISSING_DEPARTMENT_MSG logout(request) else: message = MISSING_ROLE_MSG logout(request) else: message = _('Your account is not active, please contact the admin.') message_class = 'warning' else: message = _("""Your username and/or password were incorrect. Please check the information below!""") context = {'message': message, 'message_class': message_class, 'username': username, redirect_field_name: redirect_url, } try: # Resolve seems not to work if django project is not run from web root. prefix = get_script_prefix() match = resolve(redirect_url.replace(prefix, '/')) context['department'] = match.kwargs['dept'] context['labcirs_config'] = LabCIRSConfig.objects.get( department__label=match.kwargs['dept']) except Exception as e: pass #print e #traceback.print_exc() return render(request, 'cirs/login.html', context)
def app_reverse(viewname, urlconf=None, args=None, kwargs=None, *vargs, **vkwargs): """ Reverse URLs from application contents Works almost like Django's own reverse() method except that it resolves URLs from application contents. The second argument, ``urlconf``, has to correspond to the URLconf parameter passed in the ``APPLICATIONS`` list to ``Page.create_content_type``:: app_reverse('mymodel-detail', 'myapp.urls', args=...) or app_reverse('mymodel-detail', 'myapp.urls', kwargs=...) The second argument may also be a request object if you want to reverse an URL belonging to the current application content. """ # First parameter might be a request instead of an urlconf path, so # we'll try to be helpful and extract the current urlconf from it extra_context = getattr(urlconf, "_feincms_extra_context", {}) appconfig = extra_context.get("app_config", {}) urlconf = appconfig.get("urlconf_path", urlconf) appcontent_class = ApplicationContent._feincms_content_models[0] cache_key = appcontent_class.app_reverse_cache_key(urlconf) url_prefix = cache.get(cache_key) if url_prefix is None: content = appcontent_class.closest_match(urlconf) if content is not None: if urlconf in appcontent_class.ALL_APPS_CONFIG: # We have an overridden URLconf app_config = appcontent_class.ALL_APPS_CONFIG[urlconf] urlconf = app_config["config"].get("urls", urlconf) prefix = content.parent.get_absolute_url() prefix += "/" if prefix[-1] != "/" else "" url_prefix = (urlconf, prefix) cache.set(cache_key, url_prefix, timeout=APP_REVERSE_CACHE_TIMEOUT) if url_prefix: # vargs and vkwargs are used to send through additional parameters # which are uninteresting to us (such as current_app) prefix = get_script_prefix() try: set_script_prefix(url_prefix[1]) return reverse( viewname, url_prefix[0], args=args, kwargs=kwargs, *vargs, **vkwargs ) finally: set_script_prefix(prefix) raise NoReverseMatch("Unable to find ApplicationContent for %r" % urlconf)
def render(self, context): text = super(NoPrefixURLNode, self).render(context) prefix = get_script_prefix() parts = urllib.parse.urlsplit(text) if not parts.path.startswith(prefix): logger.error("Path %s doesn't start with prefix %s", text, prefix) new_parts = list(parts) new_parts[2] = parts.path[len(prefix) - 1:] return urllib.parse.urlunsplit(new_parts)
def process_response(self, request, response): """Add Content-Language, convert some 404s to locale redirects.""" language = get_language() language_from_path = get_language_from_path(request.path_info) urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF) # Kuma: assume locale-prefix patterns, including default language if response.status_code == 404 and not language_from_path: # Maybe the language code is missing in the URL? Try adding the # language prefix and redirecting to that URL. language_path = '/%s%s' % (language, request.path_info) path_valid = is_valid_path(language_path, language, urlconf) path_needs_slash = ( not path_valid and ( settings.APPEND_SLASH and not language_path.endswith('/') and is_valid_path('%s/' % language_path, language, urlconf) ) ) if path_valid or path_needs_slash: script_prefix = get_script_prefix() # Insert language after the script prefix and before the # rest of the URL language_url = ( request.get_full_path(force_append_slash=path_needs_slash) .replace( script_prefix, '%s%s/' % (script_prefix, language), 1 )) # Kuma: Add caching headers to redirect if request.path_info == '/': # Only the homepage should be redirected permanently. redirect = HttpResponsePermanentRedirect(language_url) else: redirect = HttpResponseRedirect(language_url) add_shared_cache_control(redirect) return redirect # Kuma: Do not add 'Accept-Language' to Vary header # if not (i18n_patterns_used and language_from_path): # patch_vary_headers(response, ('Accept-Language',)) # Kuma: Add a pragma, since never skipped # No views set this header, so the middleware always sets it. The code # could be replaced with an assertion, but that would deviate from # Django's version, and make the code brittle, so using a pragma # instead. And a long comment. if 'Content-Language' not in response: # pragma: no cover response['Content-Language'] = language return response
def __init__(self, urlpatterns, app, views_module=None): """Constructor Args: urlpatterns - app - application views_module - module """ self.urlpatterns = urlpatterns self.app = app self.base_url = get_script_prefix() self.views_module = views_module
def process_request(self, request): url = resolve(request.path_info) url_name = url.url_name if not request.path.startswith(get_script_prefix() + 'control'): # This middleware should only touch the /control subpath return if hasattr(request, 'organizer'): # If the user is on a organizer's subdomain, he should be redirected to pretix return redirect(urljoin(settings.SITE_URL, request.get_full_path())) if url_name in self.EXCEPTIONS: return if not request.user.is_authenticated: return self._login_redirect(request) try: # If this logic is updated, make sure to also update the logic in pretix/api/auth/permission.py assert_session_valid(request) except SessionInvalid: logout(request) return self._login_redirect(request) except SessionReauthRequired: if url_name not in ('user.reauth', 'auth.logout'): return redirect(reverse('control:user.reauth') + '?next=' + quote(request.get_full_path())) if 'event' in url.kwargs and 'organizer' in url.kwargs: request.event = Event.objects.filter( slug=url.kwargs['event'], organizer__slug=url.kwargs['organizer'], ).select_related('organizer').first() if not request.event or not request.user.has_event_permission(request.event.organizer, request.event, request=request): raise Http404(_("The selected event was not found or you " "have no permission to administrate it.")) request.organizer = request.event.organizer if request.user.has_active_staff_session(request.session.session_key): request.eventpermset = SuperuserPermissionSet() else: request.eventpermset = request.user.get_event_permission_set(request.organizer, request.event) elif 'organizer' in url.kwargs: request.organizer = Organizer.objects.filter( slug=url.kwargs['organizer'], ).first() if not request.organizer or not request.user.has_organizer_permission(request.organizer, request=request): raise Http404(_("The selected organizer was not found or you " "have no permission to administrate it.")) if request.user.has_active_staff_session(request.session.session_key): request.orgapermset = SuperuserPermissionSet() else: request.orgapermset = request.user.get_organizer_permission_set(request.organizer)
def get_breadcrumbs(url, request=None): """ Given a url returns a list of breadcrumbs, which are each a tuple of (name, url). """ from rest_framework.reverse import preserve_builtin_query_params from rest_framework.views import APIView def breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen): """ Add tuples of (name, url) to the breadcrumbs list, progressively chomping off parts of the url. """ try: (view, unused_args, unused_kwargs) = resolve(url) except Exception: pass else: # Check if this is a REST framework view, # and if so add it to the breadcrumbs cls = getattr(view, 'cls', None) initkwargs = getattr(view, 'initkwargs', {}) if cls is not None and issubclass(cls, APIView): # Don't list the same view twice in a row. # Probably an optional trailing slash. if not seen or seen[-1] != view: c = cls(**initkwargs) c.suffix = getattr(view, 'suffix', None) name = c.get_view_name() insert_url = preserve_builtin_query_params(prefix + url, request) breadcrumbs_list.insert(0, (name, insert_url)) seen.append(view) if url == '': # All done return breadcrumbs_list elif url.endswith('/'): # Drop trailing slash off the end and continue to try to # resolve more breadcrumbs url = url.rstrip('/') return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen) # Drop trailing non-slash off the end and continue to try to # resolve more breadcrumbs url = url[:url.rfind('/') + 1] return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen) prefix = get_script_prefix().rstrip('/') url = url[len(prefix):] return breadcrumbs_recursive(url, [], prefix, [])
def home_slug(): """ Returns the slug arg defined for the ``home`` urlpattern, which is the definitive source of the ``url`` field defined for an editable homepage object. """ prefix = get_script_prefix() slug = reverse("home") if slug.startswith(prefix): slug = '/' + slug[len(prefix):] try: return resolve(slug).kwargs["slug"] except KeyError: return slug
def process_view(self, request, view_func, view_args, view_kwargs): if request.user.is_anonymous: path = request.get_full_path() resolved_login_url = resolve_url(settings.LOGIN_URL) # /login, /login?next=foo or /admin must skip redirect. whitelist = ( resolved_login_url, get_script_prefix() + settings.MYMONEY['ADMIN_BASE_URL'], ) if path.startswith(whitelist): return return redirect_to_login(path, resolved_login_url)
def __call__(self, request): # Return default response if USE_I18N is not enabled or if # FALLBACK_PREFIX_PATTERN does not match. if not settings.USE_I18N: return self.get_response(request) match = FALLBACK_PREFIX_PATTERN.match(request.path_info) if not match: return self.get_response(request) lang = match.group('lang') fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang] script_prefix = get_script_prefix() path = request.get_full_path().replace( script_prefix + lang, script_prefix + fallback, 1, ) return self.response_redirect_class(path)
def generate_json(default_urlresolver, script_prefix=None): if script_prefix is None: script_prefix = urlresolvers.get_script_prefix() urls = sorted(list(prepare_url_list(default_urlresolver))) return { 'urls': [ [ force_text(name), [ [force_text(path), [force_text(arg) for arg in args]] for path, args in patterns ], ] for name, patterns in urls ], 'prefix': script_prefix, }
def _add_script_prefix(value): """ Add SCRIPT_NAME prefix to relative paths. Useful when the app is being served at a subpath and manually prefixing subpath to STATIC_URL and MEDIA_URL in settings is inconvenient. """ # Don't apply prefix to valid URLs. try: URLValidator()(value) return value except (ValidationError, AttributeError): pass # Don't apply prefix to absolute paths. if value.startswith('/'): return value from django.urls import get_script_prefix return '%s%s' % (get_script_prefix(), value)
def process_request(self, request: HttpRequest): language = get_language_from_request(request) # Normally, this middleware runs *before* the event is set. However, on event frontend pages it # might be run a second time by pretix.presale.EventMiddleware and in this case the event is already # set and can be taken into account for the decision. if not request.path.startswith(get_script_prefix() + 'control'): if hasattr(request, 'event'): if language not in request.event.settings.locales: firstpart = language.split('-')[0] if firstpart in request.event.settings.locales: language = firstpart else: language = request.event.settings.locale for lang in request.event.settings.locales: if lang.startswith(firstpart + '-'): language = lang break if '-' not in language and request.event.settings.region: language += '-' + request.event.settings.region elif hasattr(request, 'organizer'): if '-' not in language and request.organizer.settings.region: language += '-' + request.organizer.settings.region else: gs = global_settings_object(request) if '-' not in language and gs.settings.region: language += '-' + gs.settings.region translation.activate(language) request.LANGUAGE_CODE = get_language_without_region() tzname = None if hasattr(request, 'event'): tzname = request.event.settings.timezone elif request.user.is_authenticated: tzname = request.user.timezone if tzname: try: timezone.activate(pytz.timezone(tzname)) request.timezone = tzname except pytz.UnknownTimeZoneError: pass else: timezone.deactivate()
def to_internal_value_by_url(self, origin_data): request = self.context.get('request', None) try: data = origin_data.get("url") http_prefix = data.startswith(('http:', 'https:')) except AttributeError: self.fail('incorrect_type', data_type=type(origin_data).__name__) if http_prefix: # If needed convert absolute URLs to relative path data = urlparse(data).path prefix = get_script_prefix() if data.startswith(prefix): data = '/' + data[len(prefix):] data = uri_to_iri(data) try: match = resolve(data) except Resolver404: self.fail('no_match') try: expected_viewname = request.versioning_scheme.get_versioned_viewname( self.view_name, request ) except AttributeError: expected_viewname = self.view_name if match.view_name != expected_viewname: self.fail('incorrect_match') try: obj = self.get_object(match.view_name, match.args, match.kwargs) if self.is_save: serializer = self.serializer_class(obj, data=origin_data, context={'request': self.context["request"]}) serializer.is_valid(raise_exception=True) serializer.save() return serializer.instance else: return obj except (ObjectDoesNotExist, TypeError, ValueError): self.fail('does_not_exist')
def get(self, request, version="", *args, **kwargs): if self._is_openapi_v2: version = request.version or version or "" if isinstance(request.accepted_renderer, _SpecRenderer): generator = self.generator_class( getattr(self, "info", swagger_settings.DEFAULT_INFO), version, None, None, None, ) else: generator = self.generator_class( getattr(self, "info", swagger_settings.DEFAULT_INFO), version, None, patterns=[], ) schema = generator.get_schema(request, self.public) if schema is None: raise exceptions.PermissionDenied() # pragma: no cover return Response(schema) # serve the staticically included V3 schema SCHEMA_PATH = self.get_schema_path() with open(SCHEMA_PATH, "r") as infile: schema = yaml_sane_load(infile) # fix the servers for server in schema["servers"]: split_url = urlsplit(server["url"]) if split_url.netloc: continue prefix = get_script_prefix() if prefix.endswith("/"): prefix = prefix[:-1] server_path = f"{prefix}{server['url']}" server["url"] = request.build_absolute_uri(server_path) return Response(data=schema, headers={"X-OAS-Version": schema["openapi"]})
def reverse_route(route_name, args=None, kwargs=None): args = args or [] kwargs = kwargs or {} prefix = get_script_prefix() try: route = Route.objects.filter(name=route_name).get() except Route.DoesNotExist: msg = ("Reverse for '%s' not found." % (route_name)) raise NoReverseMatch(msg) converters = _route_to_regex(route.path)[1] for result, params in normalize(_route_to_regex(route.path)[0]): if args: if len(args) != len(params): continue candidate_subs = dict(zip(params, args)) else: if set(kwargs).symmetric_difference(params): continue candidate_subs = kwargs text_candidate_subs = {} for k, v in candidate_subs.items(): if k in converters: text_candidate_subs[k] = converters[k].to_url(v) else: text_candidate_subs[k] = str(v) candidate_pat = prefix.replace('%', '%%') + result url = urllib.parse.quote(candidate_pat % text_candidate_subs, safe=RFC3986_SUBDELIMS + '/~:@') return escape_leading_slashes(url) if args: arg_msg = "arguments '%s'" % (args, ) elif kwargs: arg_msg = "keyword arguments '%s'" % (kwargs, ) else: arg_msg = "no arguments" msg = ("Reverse for '%s' with %s not matched." % (route_name, arg_msg)) raise NoReverseMatch(msg)
def __call__(self, request): if DEBUG: print("Lighttpd Middleware Incoming:") print("\t{}: {}".format('SCRIPT_NAME', request.environ['SCRIPT_NAME'])) print("\t{}: {}".format('PATH_INFO', request.environ['PATH_INFO'])) request.path = request.environ.get( 'SCRIPT_NAME', '') + request.environ.get('PATH_INFO', '') if request.path == '//': request.path = '/' # By the time a WSGIRequest object is built by Django there is an unclear duplicity between # environ and META and for our two important values, attributes. So we try to deck all three # places these are stored. One of the drawbacks of doing this in middleware clearly. Alas. request.path_info = request.path request.script_name = '' request.environ['PATH_INFO'] = request.path_info request.environ['SCRIPT_NAME'] = '' request.META['PATH_INFO'] = request.path_info request.META['SCRIPT_NAME'] = '' # While I think fixing this in middleware is the appropriate thing to do it is not # quite as easy as fixing the wsgi interface because middleware is called a little later # in the cycle, in fact after the WSGIRequest object that is provided here as request, # is built, and in its construction Django squirrels away the SCRIPT_NAME already in an # internal buffer that it later uses to build urls. Grrrr. So we have to ask it to set # that internal buffered value as well. set_script_prefix(request.script_name) if DEBUG: print("Lighttpd Middleware Fixed:") print("\t{}: {} and {} and {}".format( 'SCRIPT_NAME', request.environ['SCRIPT_NAME'], request.script_name, get_script_prefix())) print("\t{}: {} and {}".format('PATH_INFO', request.environ['PATH_INFO'], request.path_info)) response = self.get_response(request) return response
def process_response(self, request, response): language = translation.get_language() language_from_path = translation.get_language_from_path(request.path_info) urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) ( i18n_patterns_used, prefixed_default_language, ) = is_language_prefix_patterns_used(urlconf) if ( response.status_code == 404 and not language_from_path and i18n_patterns_used and prefixed_default_language ): # Maybe the language code is missing in the URL? Try adding the # language prefix and redirecting to that URL. language_path = "/%s%s" % (language, request.path_info) path_valid = is_valid_path(language_path, urlconf) path_needs_slash = not path_valid and ( settings.APPEND_SLASH and not language_path.endswith("/") and is_valid_path("%s/" % language_path, urlconf) ) if path_valid or path_needs_slash: script_prefix = get_script_prefix() # Insert language after the script prefix and before the # rest of the URL language_url = request.get_full_path( force_append_slash=path_needs_slash ).replace(script_prefix, "%s%s/" % (script_prefix, language), 1) # Redirect to the language-specific URL as detected by # get_language_from_request(). HTTP caches may cache this # redirect, so add the Vary header. redirect = self.response_redirect_class(language_url) patch_vary_headers(redirect, ("Accept-Language", "Cookie")) return redirect if not (i18n_patterns_used and language_from_path): patch_vary_headers(response, ("Accept-Language",)) response.headers.setdefault("Content-Language", language) return response
def add_preserved_filters(context, url, popup=False, to_field=None): opts = context.get("opts") preserved_filters = context.get("preserved_filters") parsed_url = list(urlparse(url)) parsed_qs = dict(parse_qsl(parsed_url[4])) merged_qs = {} if opts and preserved_filters: preserved_filters = dict(parse_qsl(preserved_filters)) match_url = "/%s" % url.partition(get_script_prefix())[2] try: match = resolve(match_url) except Resolver404: pass else: current_url = "%s:%s" % (match.app_name, match.url_name) changelist_url = "admin:%s_%s_changelist" % ( opts.app_label, opts.model_name, ) if (changelist_url == current_url and "_changelist_filters" in preserved_filters): preserved_filters = dict( parse_qsl(preserved_filters["_changelist_filters"])) merged_qs.update(preserved_filters) if popup: from django.contrib.admin.options import IS_POPUP_VAR merged_qs[IS_POPUP_VAR] = 1 if to_field: from django.contrib.admin.options import TO_FIELD_VAR merged_qs[TO_FIELD_VAR] = to_field merged_qs.update(parsed_qs) parsed_url[4] = urlencode(merged_qs) return urlunparse(parsed_url)
def __call__(self, request): if request.path.startswith(get_script_prefix() + 'control' ) and request.user.is_authenticated: if is_hijacked(request): hijack_history = request.session.get('hijack_history', False) hijacker = get_object_or_404(User, pk=hijack_history[0]) ss = hijacker.get_active_staff_session( request.session.get('hijacker_session')) if ss: ss.logs.create(url=request.path, method=request.method, impersonating=request.user) else: ss = request.user.get_active_staff_session( request.session.session_key) if ss: ss.logs.create(url=request.path, method=request.method) response = self.get_response(request) return response
def get_canonical_path(resource_key, pk=None): """ Return canonical resource path. Arguments: resource_key - Canonical resource key i.e. Serializer.get_resource_key(). pk - (Optional) Object's primary key for a single-resource URL. Returns: Absolute URL as string. """ if resource_key not in resource_map: # Note: Maybe raise? return None base_path = get_script_prefix() + resource_map[resource_key]['path'] if pk: return '%s/%s/' % (base_path, pk) else: return base_path
def generate_js(default_urlresolver): js_var_name = getattr(settings, 'JS_REVERSE_JS_VAR_NAME', JS_VAR_NAME) if not JS_IDENTIFIER_RE.match(js_var_name.upper()): raise ImproperlyConfigured( 'JS_REVERSE_JS_VAR_NAME setting "%s" is not a valid javascript identifier.' % (js_var_name)) js_global_object_name = getattr(settings, 'JS_REVERSE_JS_GLOBAL_OBJECT_NAME', JS_GLOBAL_OBJECT_NAME) if not JS_IDENTIFIER_RE.match(js_global_object_name.upper()): raise ImproperlyConfigured( 'JS_REVERSE_JS_GLOBAL_OBJECT_NAME setting "%s" is not a valid javascript identifier.' % (js_global_object_name)) minfiy = getattr(settings, 'JS_REVERSE_JS_MINIFY', JS_MINIFY) if not isinstance(minfiy, bool): raise ImproperlyConfigured( 'JS_REVERSE_JS_MINIFY setting "%s" is not a valid. Needs to be set to True or False.' % (minfiy)) script_prefix_via_config = getattr(settings, 'JS_REVERSE_SCRIPT_PREFIX', None) if script_prefix_via_config: script_prefix = script_prefix_via_config if not script_prefix.endswith('/'): script_prefix = '{0}/'.format(script_prefix) else: script_prefix = urlresolvers.get_script_prefix() js_content = loader.render_to_string( 'django_js_reverse/urls_js.tpl', { 'urls': sorted(list(prepare_url_list(default_urlresolver))), 'url_prefix': script_prefix, 'js_var_name': js_var_name, 'js_global_object_name': js_global_object_name, }) if minfiy: js_content = rjsmin.jsmin(js_content) return js_content
def get_language_from_request(request: HttpRequest) -> str: """ Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. """ global _supported if _supported is None: _supported = OrderedDict(settings.LANGUAGES) if request.path.startswith(get_script_prefix() + 'control'): return (get_language_from_user_settings(request) or get_language_from_session_or_cookie(request) or get_language_from_browser(request) or get_language_from_event(request) or get_default_language()) else: return (get_language_from_session_or_cookie(request) or get_language_from_user_settings(request) or get_language_from_browser(request) or get_language_from_event(request) or get_default_language())
def dispatch(self, request, user, suffix="", **slug_path): course = get_object_or_404( Course.objects.by_slug_path( **slug_path).visible(user).distinct().filter(is_static=False). select_related("study_course").prefetch_related( "editors", "students")) acl = course.get_git_acl(user) # Instruct webserver to forward the request to git-http-backend response = HttpResponse() response["MS-Git-Auth"] = ( user.username + ":" + json.dumps({ "acl": acl, # Internal URL to access uWSGI directly, without nginx "push_notify_url": "http://" + request.META["SERVER_NAME"] + ":" + request.META["SERVER_PORT"] + "/" + reverse("git_push_notify", kwargs={"course_pk": course.pk}) [len(get_script_prefix()):].lstrip("/"), })) return response
def common_add_preserved_filters(context, url, popup=False, to_field=None): opts = context.get('opts') preserved_filters = context.get('preserved_filters') parsed_url = list(urlparse(url)) parsed_qs = dict(parse_qsl(parsed_url[4])) merged_qs = dict() if opts and preserved_filters: preserved_filters = dict(parse_qsl(preserved_filters)) match_url = '/%s' % url.partition(get_script_prefix())[2] try: match = resolve(match_url) except Resolver404: pass else: current_url = '%s:%s' % (match.app_name, match.url_name) namespace = 'common' if context.get('site_namespace'): namespace = context.get('site_namespace') changelist_url = '%s:%s_%s_changelist' % ( namespace, opts.app_label, opts.model_name) if changelist_url == current_url and '_changelist_filters' in preserved_filters: preserved_filters = dict( parse_qsl(preserved_filters['_changelist_filters'])) merged_qs.update(preserved_filters) if popup: from django.contrib.admin.options import IS_POPUP_VAR merged_qs[IS_POPUP_VAR] = 1 if to_field: from django.contrib.admin.options import TO_FIELD_VAR merged_qs[TO_FIELD_VAR] = to_field merged_qs.update(parsed_qs) parsed_url[4] = urlencode(merged_qs) return urlunparse(parsed_url)
def absolute_resolve(url): """ An extension of Django's `resolve()` that handles absolute URLs *or* relative paths. Mostly copied from rest_framework.serializers.HyperlinkedRelatedField. """ try: http_prefix = url.startswith(('http:', 'https:')) except AttributeError: # `url` is not a string?! raise TypeError if http_prefix: path = urlparse(url).path prefix = get_script_prefix() if path.startswith(prefix): path = '/' + path[len(prefix):] else: path = url path = uri_to_iri(path) return resolve(path)
def __call__(self, request): if request.path.startswith(get_script_prefix() + 'control') and request.user.is_authenticated: if is_hijacked(request): hijack_history = request.session.get('hijack_history', False) hijacker = get_object_or_404(User, pk=hijack_history[0]) ss = hijacker.get_active_staff_session(request.session.get('hijacker_session')) if ss: ss.logs.create( url=request.path, method=request.method, impersonating=request.user ) else: ss = request.user.get_active_staff_session(request.session.session_key) if ss: ss.logs.create( url=request.path, method=request.method ) response = self.get_response(request) return response
def bulk_destroy(self, request, *args, **kwargs): if not request.data: return Response(status=status.HTTP_400_BAD_REQUEST) qs = self.get_queryset() ids = [] for url in request.data: try: http_prefix = url.startswith(('http:', 'https:')) except AttributeError: return Response(status=status.HTTP_400_BAD_REQUEST) if http_prefix: # If needed convert absolute URLs to relative path url = urlparse(url).path prefix = get_script_prefix() if url.startswith(prefix): url = '/' + url[len(prefix):] try: match = resolve(url) except Resolver404: return Response(status=status.HTTP_400_BAD_REQUEST) try: pk = int(match.kwargs.get('pk')) except (ValueError, TypeError): return Response(status=status.HTTP_400_BAD_REQUEST) ids.append(pk) if not ids: return Response(status=status.HTTP_400_BAD_REQUEST) qs.filter(id__in=ids).delete() return Response(status=status.HTTP_204_NO_CONTENT)
def configure_from_settings(self, settings): # Default configuration self.autorefresh = settings.DEBUG self.use_finders = settings.DEBUG self.static_prefix = urlparse(settings.STATIC_URL or "").path script_prefix = get_script_prefix().rstrip("/") if script_prefix: if self.static_prefix.startswith(script_prefix): self.static_prefix = self.static_prefix[len(script_prefix):] if settings.DEBUG: self.max_age = 0 # Allow settings to override default attributes for attr in self.config_attrs: settings_key = f"WHITENOISE_{attr.upper()}" try: value = getattr(settings, settings_key) except AttributeError: pass else: value = decode_if_byte_string(value) setattr(self, attr, value) self.static_prefix = ensure_leading_trailing_slash(self.static_prefix) self.static_root = decode_if_byte_string(settings.STATIC_ROOT)
def login_redirect(request): """ Returns the redirect response for login/signup. Favors: - next param - LOGIN_REDIRECT_URL setting - homepage """ ignorable_nexts = ("",) if "mezzanine.accounts" in settings.INSTALLED_APPS: from mezzanine.accounts import urls ignorable_nexts += (urls.SIGNUP_URL, urls.LOGIN_URL, urls.LOGOUT_URL) next = next_url(request) or "" if next in ignorable_nexts: next = settings.LOGIN_REDIRECT_URL if next == "/accounts/profile/": # Use the homepage if LOGIN_REDIRECT_URL is Django's defaut. next = get_script_prefix() else: try: next = reverse(next) except NoReverseMatch: pass return redirect(next)
def login_redirect(request): """ Returns the redirect response for login/signup. Favors: - next param - LOGIN_REDIRECT_URL setting - homepage """ ignorable_nexts = ("", ) if "mezzanine.accounts" in settings.INSTALLED_APPS: from mezzanine.accounts import urls ignorable_nexts += (urls.SIGNUP_URL, urls.LOGIN_URL, urls.LOGOUT_URL) next = next_url(request) or "" if next in ignorable_nexts: next = settings.LOGIN_REDIRECT_URL if next == "/accounts/profile/": # Use the homepage if LOGIN_REDIRECT_URL is Django's defaut. next = get_script_prefix() else: try: next = reverse(next) except NoReverseMatch: pass return redirect(next)
def to_internal_value(self, data): request = self.context.get('request', None) try: data = json.loads(data).get("url") http_prefix = data.startswith(('http:', 'https:')) except AttributeError: self.fail('incorrect_type', data_type=type(data).__name__) if http_prefix: # If needed convert absolute URLs to relative path data = urlparse(data).path prefix = get_script_prefix() if data.startswith(prefix): data = '/' + data[len(prefix):] data = uri_to_iri(data) try: match = resolve(data) except Resolver404: self.fail('no_match') try: expected_viewname = request.versioning_scheme.get_versioned_viewname( self.view_name, request ) except AttributeError: expected_viewname = self.view_name if match.view_name != expected_viewname: self.fail('incorrect_match') try: return self.get_object(match.view_name, match.args, match.kwargs) except (ObjectDoesNotExist, TypeError, ValueError): self.fail('does_not_exist')
def to_internal_value(self, data): self.source_attrs = [self.field_source_name] # Must set # Was the value already entered? if isinstance( data, tuple(model for model, field in self.models.values())): return data try: http_prefix = data.startswith(('http:', 'https:')) except AttributeError: self.fail('incorrect_type', data_type=type(data).__name__) if http_prefix: # If needed convert absolute URLs to relative path data = parse.urlparse(data).path prefix = get_script_prefix() if data.startswith(prefix): data = '/' + data[len(prefix):] data = uri_to_iri(data) try: match = resolve(data) except Resolver404: self.fail('no_match') self.model = { view: model for view, (model, field) in self.models.items() }[match.view_name] try: return self.get_object(match.view_name, match.args, match.kwargs) except self.model.DoesNotExist: self.fail('does_not_exist')
def process_response(self, request, response): language = translation.get_language() # language = 'en' # print("language.....process_response................",language) language_from_path = translation.get_language_from_path(request.path_info) urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF) i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf) if (response.status_code == 404 and not language_from_path and i18n_patterns_used and prefixed_default_language): # Maybe the language code is missing in the URL? Try adding the # language prefix and redirecting to that URL. language_path = '/%s%s' % (language, request.path_info) path_valid = is_valid_path(language_path, urlconf) path_needs_slash = ( not path_valid and ( settings.APPEND_SLASH and not language_path.endswith('/') and is_valid_path('%s/' % language_path, urlconf) ) ) if path_valid or path_needs_slash: script_prefix = get_script_prefix() # Insert language after the script prefix and before the # rest of the URL language_url = request.get_full_path(force_append_slash=path_needs_slash).replace( script_prefix, '%s%s/' % (script_prefix, language), 1 ) return self.response_redirect_class(language_url) if not (i18n_patterns_used and language_from_path): patch_vary_headers(response, ('Accept-Language',)) if 'Content-Language' not in response: response['Content-Language'] = language return response
def django_url_fetcher(url, *args, **kwargs): # load file:// paths directly from disk if url.startswith('file:'): mime_type, encoding = mimetypes.guess_type(url) url_path = urlparse(url).path data = { 'mime_type': mime_type, 'encoding': encoding, 'filename': Path(url_path).name, } default_media_url = settings.MEDIA_URL in ('', get_script_prefix()) if not default_media_url and url_path.startswith(settings.MEDIA_URL): path = url_path.replace(settings.MEDIA_URL, settings.MEDIA_ROOT, 1) data['file_obj'] = default_storage.open(path) return data elif settings.STATIC_URL and url_path.startswith(settings.STATIC_URL): path = url_path.replace(settings.STATIC_URL, '', 1) data['file_obj'] = open(find(path), 'rb') return data # fall back to weasyprint default fetcher return weasyprint.default_url_fetcher(url, *args, **kwargs)
def get_absolute_url(self): # Handle script prefix manually because we bypass reverse() return iri_to_uri(get_script_prefix().rstrip('/') + self.url)
def script_prefix(request): return { 'SCRIPT_PREFIX': get_script_prefix(), }
def enable(self): self.old_prefix = get_script_prefix() set_script_prefix(self.prefix)
except ImproperlyConfigured: from .management.utils import Helpers export_settings = Helpers.export_settings exec(export_settings()) from django.conf import settings from django.shortcuts import resolve_url from django.urls import get_script_prefix from django.utils.functional import lazy from pathlib import Path # noqa # Lazy-evaluate URLs so including app.urls in root urlconf works resolve_url = lazy(resolve_url, str) # Get script prefix for apps not mounted under / _SCRIPT_PREFIX = get_script_prefix() # ---------------------------------------------------------------------------------- # Set your relevant paths to allow Djangular-Serve, find templates and static # This is one way. Do it in whatever way it works for you. # ---------------------------------------------------------------------------------- # Build paths inside the project like this: APP_DIR / 'subdir'. # BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Absolute root path # APP_DIR = Path(__file__).resolve(strict=True).parent # 'example' project # URL = os.path.relpath(APP_DIR / "static") # example/static # ANGULAR_DIR = os.path.join(BASE_DIR, ".") # root/ngservetest """ Angular project root. """ NG_ROOT_PATH = getattr(settings, 'NG_ROOT_PATH', '') """ Static root to distribute Angular app as static.
def _default_context(request): try: url = resolve(request.path_info) except Resolver404: return {} if not request.path.startswith(get_script_prefix() + 'control'): return {} ctx = { 'url_name': url.url_name, 'settings': settings, 'django_settings': settings, 'DEBUG': settings.DEBUG, } _html_head = [] if hasattr(request, 'event') and request.user.is_authenticated: for receiver, response in html_head.send(request.event, request=request): _html_head.append(response) ctx['html_head'] = "".join(_html_head) _js_payment_weekdays_disabled = '[]' if getattr(request, 'event', None) and hasattr( request, 'organizer') and request.user.is_authenticated: ctx['nav_items'] = get_event_navigation(request) if request.event.settings.get('payment_term_weekdays'): _js_payment_weekdays_disabled = '[0,6]' ctx['has_domain'] = get_event_domain(request.event, fallback=True) is not None if not request.event.testmode: with scope(organizer=request.organizer): complain_testmode_orders = request.event.cache.get( 'complain_testmode_orders') if complain_testmode_orders is None: complain_testmode_orders = request.event.orders.filter( testmode=True).exists() request.event.cache.set('complain_testmode_orders', complain_testmode_orders, 30) ctx['complain_testmode_orders'] = complain_testmode_orders else: ctx['complain_testmode_orders'] = False if not request.event.live and ctx['has_domain']: child_sess = request.session.get('child_session_{}'.format( request.event.pk)) s = SessionStore() if not child_sess or not s.exists(child_sess): s['pretix_event_access_{}'.format( request.event.pk)] = request.session.session_key s.create() ctx['new_session'] = s.session_key request.session['child_session_{}'.format( request.event.pk)] = s.session_key request.session['event_access'] = True else: ctx['new_session'] = child_sess request.session['event_access'] = True if request.GET.get('subevent', ''): # Do not use .get() for lazy evaluation ctx['selected_subevents'] = request.event.subevents.filter( pk=request.GET.get('subevent')) elif getattr(request, 'organizer', None) and request.user.is_authenticated: ctx['nav_items'] = get_organizer_navigation(request) elif request.user.is_authenticated: ctx['nav_items'] = get_global_navigation(request) ctx['js_payment_weekdays_disabled'] = _js_payment_weekdays_disabled _nav_topbar = [] if request.user.is_authenticated: for receiver, response in nav_topbar.send(request, request=request): _nav_topbar += response ctx['nav_topbar'] = sorted(_nav_topbar, key=lambda n: n['label']) ctx['js_datetime_format'] = get_javascript_format('DATETIME_INPUT_FORMATS') ctx['js_date_format'] = get_javascript_format('DATE_INPUT_FORMATS') ctx['js_long_date_format'] = get_javascript_output_format('DATE_FORMAT') ctx['js_time_format'] = get_javascript_format('TIME_INPUT_FORMATS') ctx['js_locale'] = get_moment_locale() ctx['select2locale'] = get_language()[:2] ctx['warning_update_available'] = False ctx['warning_update_check_active'] = False gs = GlobalSettingsObject() ctx['global_settings'] = gs.settings if request.user.is_staff: if gs.settings.update_check_result_warning: ctx['warning_update_available'] = True if not gs.settings.update_check_ack and 'runserver' not in sys.argv: ctx['warning_update_check_active'] = True if request.user.is_authenticated: ctx['staff_session'] = request.user.has_active_staff_session( request.session.session_key) ctx['staff_need_to_explain'] = ( StaffSession.objects.filter( user=request.user, date_end__isnull=False).filter( Q(comment__isnull=True) | Q(comment="")) if request.user.is_staff and settings.PRETIX_ADMIN_AUDIT_COMMENTS else StaffSession.objects.none()) return ctx
def setUp(self): self._initial_prefix = get_script_prefix()
def __str__(self): return get_script_prefix() + self[1:] if self.startswith('/') else self
def obj_update(self, bundle, **kwargs): """ Update an object in CRITs. Should be overridden by each individual top-level resource. :returns: NotImplementedError if the resource doesn't override. """ import crits.actors.handlers as ah import crits.core.handlers as coreh import crits.objects.handlers as objh import crits.relationships.handlers as relh import crits.services.handlers as servh import crits.signatures.handlers as sigh import crits.indicators.handlers as indh actions = { 'Common': { 'add_object': objh.add_object, 'add_releasability': coreh.add_releasability, 'forge_relationship': relh.forge_relationship, 'run_service': servh.run_service, 'status_update' : coreh.status_update, 'ticket_add' : coreh.ticket_add, 'ticket_update' : coreh.ticket_update, 'ticket_remove' : coreh.ticket_remove, 'source_add_update': coreh.source_add_update, 'source_remove': coreh.source_remove, 'action_add' : coreh.action_add, 'action_update' : coreh.action_update, 'action_remove' : coreh.action_remove, 'description_update' : coreh.description_update, }, 'Actor': { 'update_actor_tags': ah.update_actor_tags, 'attribute_actor_identifier': ah.attribute_actor_identifier, 'set_identifier_confidence': ah.set_identifier_confidence, 'remove_attribution': ah.remove_attribution, 'set_actor_name': ah.set_actor_name, 'update_actor_aliases': ah.update_actor_aliases, }, 'Backdoor': {}, 'Campaign': {}, 'Certificate': {}, 'Domain': {}, 'Email': {}, 'Event': {}, 'Exploit': {}, 'Indicator': { 'modify_attack_types' : indh.modify_attack_types, 'modify_threat_types' : indh.modify_threat_types, 'activity_add' : indh.activity_add, 'activity_update' : indh.activity_update, 'activity_remove' : indh.activity_remove, 'ci_update' : indh.ci_update }, 'IP': {}, 'PCAP': {}, 'RawData': {}, 'Sample': {}, 'Signature': { 'update_dependency': sigh.update_dependency, 'update_min_version': sigh.update_min_version, 'update_max_version': sigh.update_max_version, 'update_signature_data': sigh.update_signature_data, 'update_signature_type': sigh.update_signature_type, 'update_title': sigh.update_title }, 'Target': {}, } prefix = get_script_prefix() uri = bundle.request.path if prefix and uri.startswith(prefix): uri = uri[len(prefix)-1:] view, args, kwargs = resolve(uri) type_ = kwargs['resource_name'].title() if type_ == "Raw_Data": type_ = "RawData" if type_[-1] == 's': type_ = type_[:-1] if type_ in ("Pcap", "Ip"): type_ = type_.upper() id_ = kwargs['pk'] content = {'return_code': 0, 'type': type_, 'message': '', 'id': id_} # Make sure we have an appropriate action. action = bundle.data.get("action", None) atype = actions.get(type_, None) if atype is None: content['return_code'] = 1 content['message'] = "'%s' is not a valid resource." % type_ self.crits_response(content) action_type = atype.get(action, None) if action_type is None: atype = actions.get('Common') action_type = atype.get(action, None) if action_type: data = bundle.data # Requests don't need to have an id_ as we will derive it from # the request URL. Override id_ if the request provided one. data['id_'] = id_ # Override type (if provided) data['type_'] = type_ # Override user (if provided) with the one who made the request. data['user'] = bundle.request.user.username try: results = action_type(**data) if not results.get('success', False): content['return_code'] = 1 # TODO: Some messages contain HTML and other such content # that we shouldn't be returning here. message = results.get('message', None) content['message'] = message else: content['message'] = "success!" except Exception, e: content['return_code'] = 1 content['message'] = str(e)
def __init__(self, newpath): self.newpath = newpath self.oldprefix = get_script_prefix()