def process_response(self, request, response): if response.status_code != 404: # Don't check for a form if another request succeeds return response try: path = request.path_info form_model = None try: form_model = FormModel.objects.get(submit_url=path) viewfunc = csrf_protect(DynamicFormView.as_view()) except FormModel.DoesNotExist: # success_url is not unique form_models = FormModel.objects.filter(success_url=path).all() if not form_models: raise Http404 form_model = form_models[0] viewfunc = csrf_protect(DynamicTemplateView.as_view()) new_resp = viewfunc(request, model=form_model) if hasattr(new_resp, 'render') and callable(new_resp.render): new_resp.render() return new_resp except Http404: # Return the original response if no form can be found return response except Exception as exc: if settings.DEBUG: raise exc # Return the original response if any error occurs return response
def urlpatterns(self): urlpatterns = super(PasswordMultiView, self).urlpatterns if self.password_reset_page_id and self.password_reset_confirmation_email_id and self.password_set_page_id: urlpatterns += patterns('', url(r'^password/reset$', csrf_protect(self.password_reset), name='password_reset'), url(r'^password/reset/(?P<uidb36>\w+)/(?P<token>[^/]+)$', self.password_reset_confirm, name='password_reset_confirm'), ) if self.password_change_page_id: urlpatterns += patterns('', url(r'^password/change$', csrf_protect(self.login_required(self.password_change)), name='password_change'), ) return urlpatterns
def admin_view(self, view, cacheable=False): """ Override superclass admin_view to provide our own auth flow. Specifically: * Return 403 if authenticated and has_permission returns False * Redirect to login if not authenticated """ def inner(request, *args, **kwargs): if not self.has_permission(request): if request.path == reverse('admin:logout', current_app=self.name): index_path = reverse('admin:index', current_app=self.name) return HttpResponseRedirect(index_path) # Inner import to prevent django.contrib.admin (app) from # importing django.contrib.auth.models.User (unrelated model). from django.contrib.auth.views import redirect_to_login # Begin overriden portion here if not request.user.is_authenticated(): return redirect_to_login( request.get_full_path(), reverse('admin:login', current_app=self.name)) else: return HttpResponseForbidden(_('Permission Denied.')) # End overriden portion return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def admin_view(self, view, cacheable=False): """ Decorator to create an admin view attached to this ``AdminSite``. This wraps the view and provides permission checking by calling ``self.has_permission``. You'll want to use this from within ``AdminSite.get_urls()``: class MyAdminSite(AdminSite): def get_urls(self): from django.conf.urls.defaults import patterns, url urls = super(MyAdminSite, self).get_urls() urls += patterns('', url(r'^my_view/$', self.admin_view(some_view)) ) return urls By default, admin_views are marked non-cacheable using the ``never_cache`` decorator. If the view can be safely cached, set cacheable=True. """ def inner(request, *args, **kwargs): if not self.has_permission(request): return self.login(request) return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def wrapped(request, *args, **kwargs): if request.REQUEST.get('api_key'): if request.REQUEST['api_key'] != settings.ZUMANJI_CONFIG.get( 'API_KEY', NOTSET): return HttpResponseForbidden('Invalid api_key') return func(request, *args, **kwargs) return csrf_protect(func)(request, *args, **kwargs)
def call_plugin_view(self, request, mod_name, func_name, method_kwargs): """ Call a plugin view used for pylucid-get-views and lucidTag calls """ plugin_callable = self.get_callable(mod_name, func_name) # Add info for pylucid_project.apps.pylucid.context_processors.pylucid request.plugin_name = self.name request.method_name = func_name csrf_exempt = getattr(plugin_callable, 'csrf_exempt', False) if func_name == "http_get_view" and not csrf_exempt: # Use csrf_protect only in pylucid get views and not für lucidTag calls plugin_callable = csrf_protect(plugin_callable) # call the plugin view method response = plugin_callable(request, **method_kwargs) if not (isinstance(response, (HttpResponse, basestring)) or response is None): msg = "Plugin view '%s.%s.%s' must return None or basestring or HttpResponse! (returned: %r)" % ( self.pkg_string, mod_name, func_name, type(response)) raise TypeError(msg) if csrf_exempt and isinstance(response, HttpResponse): response.csrf_exempt = True request.plugin_name = None request.method_name = None # del(request.plugin_name) # del(request.method_name) return response
def admin_view(self, view, cacheable=False): # not everything can take extra_context excludes = [ 'password_change', 'password_change_done', 'i18n_javascript', 'login', 'logout', 'user_change_password', ] def inner(request, *args, **kwargs): if not self.has_permission(request): return self.login(request) if view.__name__ not in excludes: extra_context = kwargs.get('extra_context', {}) extra_context = self.annotate_context(extra_context) kwargs['extra_context'] = extra_context return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def admin_view(view, cacheable=False): def inner(request, *args, **kwargs): if not request.user.is_active and not request.user.is_staff: raise Http404() if not request.user.is_anonymous and request.user.can_escalate_to_priveleged: if not request.user.is_privileged: return redirect("sudo") try: return view(request, *args, **kwargs) except EntitlementViolation: return HttpResponse("Not permitted to do that", status=404, content_type="text/plain") context = { "title": "View history", } if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, "csrf_exempt", False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def call_plugin_view(self, request, mod_name, func_name, method_kwargs): """ Call a plugin view used for pylucid-get-views and lucidTag calls """ plugin_callable = self.get_callable(mod_name, func_name) # Add info for pylucid_project.apps.pylucid.context_processors.pylucid request.plugin_name = self.name request.method_name = func_name csrf_exempt = getattr(plugin_callable, 'csrf_exempt', False) if func_name == "http_get_view" and not csrf_exempt: # Use csrf_protect only in pylucid get views and not für lucidTag calls plugin_callable = csrf_protect(plugin_callable) # call the plugin view method response = plugin_callable(request, **method_kwargs) if not (isinstance(response, (HttpResponse, basestring)) or response is None): msg = "Plugin view '%s.%s.%s' must return None or basestring or HttpResponse! (returned: %r)" % ( self.pkg_string, mod_name, func_name, type(response) ) raise TypeError(msg) if csrf_exempt and isinstance(response, HttpResponse): response.csrf_exempt = True request.plugin_name = None request.method_name = None # del(request.plugin_name) # del(request.method_name) return response
def as_view(self, view, cacheable=False, extra_permission=None): """ Wraps a view in authentication/caching logic extra_permission can be used to require an extra permission for this view, such as a module permission """ @wraps(view) def inner(request, *args, **kwargs): if not user_is_authenticated(request.user): return self.login(request) elif not self.has_permission(request, extra_permission): raise PermissionDenied() return view(request, *args, **kwargs) # Mark it as never_cache if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) inner = ensure_csrf_cookie(inner) return update_wrapper(inner, view)
def _process_request_if_configured(self, request): """ Block the request if it is a login attempt to which a throttling delay is applicable. """ if request.method != "POST": return for url, template_name in self.logins: if request.path[1:] != url: continue delay = self._throttling_delay(request) if delay <= 0: request.META["login_request_permitted"] = True return form = _ThrottlingForm(delay, request) redirect_url = request.REQUEST.get(self.redirect_field_name, "") current_site = get_current_site(request) # Template-compatible with 'django.contrib.auth.views.login'. return csrf_protect( lambda request: render_to_response( template_name, { "form": form, self.redirect_field_name: redirect_url, "site": current_site, "site_name": current_site.name, }, context_instance=RequestContext(request), ) )(request)
def call_plugin_view(self, request, mod_name, func_name, method_kwargs): """ Call a plugin view used for pylucid-get-views and lucidTag calls """ callable = self.get_callable(mod_name, func_name) # Add info for pylucid_project.apps.pylucid.context_processors.pylucid request.plugin_name = self.name request.method_name = func_name csrf_exempt = getattr(callable, "csrf_exempt", False) if func_name == "http_get_view" and not csrf_exempt: # Use csrf_protect only in pylucid get views and not für lucidTag calls callable = csrf_protect(callable) # call the plugin view method response = callable(request, **method_kwargs) if csrf_exempt and isinstance(response, HttpResponse): response.csrf_exempt = True request.plugin_name = None request.method_name = None # del(request.plugin_name) # del(request.method_name) return response
def disconnect_view(func): @wraps(func) def wrapper(request, *args, **kwargs): return func(request, *args, **kwargs) if setting('SOCIAL_AUTH_FORCE_POST_DISCONNECT'): wrapper = require_POST(csrf_protect(wrapper)) return wrapper
def apply_decorators( # noqa: C901 view=None, login=False, staff=False, perms=None, cache=None, gzip=False, xframe=None, csrf=None, decorators=(), ): """ Apply decorators to view function. Can also be used as a decorator. """ if view is None: kwargs = locals() kwargs.pop("view") return lambda view: apply_decorators(view, **kwargs) # Cache control if cache is False: view = never_cache(view) elif cache is not None: view = cache_control(**cache)(view) # Permissions # (We keep the implementation here, but those options are not handled by # this decorator anymore). if login: view = login_required(view) if perms: view = permission_required(perms)(view) if staff: view = staff_required(view) # Compression if gzip: view = gzip_page(view) # Security if xframe is False: view = xframe_options_exempt(view) elif xframe == "deny": view = xframe_options_deny(view) elif xframe == "sameorigin": view = xframe_options_sameorigin(view) if csrf is False: view = csrf_exempt(view) elif csrf == "cookie": view = ensure_csrf_cookie(view) elif csrf == "token": view = requires_csrf_token(view) elif csrf is True: view = csrf_protect(view) # Apply final decorators for decorator in reversed(decorators): view = decorator(view) return view
def admin_view(self,view): def no_wrap(request,*args,**kwargs): return view(request,*args,**kwargs) from django.views.decorators.csrf import csrf_protect from django.utils.functional import update_wrapper no_wrap = csrf_protect(no_wrap) return update_wrapper(no_wrap, view)
def admin_view(self, view, cacheable=False): """Decorator to create an admin view attached to this AdminSite. This wraps the view and provides permission checking by calling self.has_permission (except for the logout page). """ def inner(request, * args, ** kwargs): if not self.has_permission(request) and view != self.logout: if not request.user.is_authenticated(): return self.login(request) else: return render_to_response('shibsso/no_permission.html', { 'title': _('Site administration') }, context_instance=RequestContext(request)) return view(request, * args, ** kwargs) if not cacheable: inner = never_cache(inner) try: # Backwards-compatibility for Django 1.1.1 if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) except: pass return update_wrapper(inner, view)
def admin_view(self, view, cacheable=False): # not everything can take extra_context excludes = [ 'password_change', 'password_change_done', 'i18n_javascript', 'login', 'logout', ] def inner(request, *args, **kwargs): if not self.has_permission(request): return self.login(request) if view.__name__ not in excludes: extra_context = kwargs.get('extra_context', {}) extra_context = self.annotate_context(extra_context) kwargs['extra_context'] = extra_context return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def admin_staff_member_required( view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login', cacheable=False ): """ Decorator for views that checks that the user is logged in and is a staff member, redirecting to the login page if necessary. Also it make csrf_protect for each view and if need mark as chachable """ actual_decorator = user_passes_test( lambda u: u.is_active and u.is_staff, login_url=login_url, redirect_field_name=redirect_field_name ) view_func = actual_decorator(view_func) # make views as non chached if not cacheable: view_func = never_cache(view_func) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view_func, 'csrf_exempt', False): view_func = csrf_protect(view_func) return view_func
def admin_view(self, view, cacheable=False): """ Override superclass admin_view to provide our own auth flow. Specifically: * Return 403 if authenticated and has_permission returns False * Redirect to login if not authenticated """ def inner(request, *args, **kwargs): if not self.has_permission(request): if request.path == reverse('admin:logout', current_app=self.name): index_path = reverse('admin:index', current_app=self.name) return HttpResponseRedirect(index_path) # Inner import to prevent django.contrib.admin (app) from # importing django.contrib.auth.models.User (unrelated model). from django.contrib.auth.views import redirect_to_login # Begin overriden portion here if not request.user.is_authenticated(): return redirect_to_login( request.get_full_path(), reverse('admin:login', current_app=self.name) ) else: return HttpResponseForbidden(_('Permission Denied.')) # End overriden portion return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def as_view(self, view, cacheable=False, extra_permission=None): """ Wraps a view in authentication/caching logic extra_permission can be used to require an extra permission for this view, such as a module permission """ def inner(request, *args, **kwargs): if not self.has_permission(request, extra_permission): # show login pane return self.login(request) return view(request, *args, **kwargs) # Mark it as never_cache if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, "csrf_exempt", False): inner = csrf_protect(inner) inner = ensure_csrf_cookie(inner) return update_wrapper(inner, view)
def logged_in(view): """View decorator that ensures the user is correctly logged in.""" view = csrf_protect(view) @wraps(view) def fn(request, trader_id_str, *args, **kargs): try: trader_id = int(trader_id_str) if is_logged_in(request.session, trader_id): # Render the response with some HTTP-headers added. response = view(request, trader_id, *args, **kargs) if 'Cache-Control' not in response: response['Cache-Control'] = 'no-cache' response['X-Frame-Options'] = 'deny' return response else: return HttpResponseRedirect(reverse('users-login')) except curiousorm.PgError, e: if (getattr(e, 'pgcode', '')==curiousorm.RAISE_EXCEPTION and A_TURN_IS_RUNNING.search(getattr(e, 'pgerror', ''))): # Render "turn is running" page with CSRF protection. c = {'settings': settings, 'trader_id': trader_id } c.update(csrf(request)) return render_to_response(settings.CMBARTER_TURN_IS_RUNNING_TEMPLATE, c) else: raise
def logged_in(view): """View decorator that ensures the user is correctly logged in.""" view = csrf_protect(view) @wraps(view) def fn(request, trader_id_str, *args, **kargs): try: trader_id = int(trader_id_str) if is_logged_in(request.session, trader_id): # Render the response with some HTTP-headers added. response = view(request, trader_id, *args, **kargs) if 'Cache-Control' not in response: response['Cache-Control'] = 'no-cache' response['X-Frame-Options'] = 'deny' return response else: return HttpResponseRedirect(reverse('users-login')) except curiousorm.PgError, e: if (getattr(e, 'pgcode', '') == curiousorm.RAISE_EXCEPTION and A_TURN_IS_RUNNING.search(getattr(e, 'pgerror', ''))): # Render "turn is running" page with CSRF protection. c = {'settings': settings, 'trader_id': trader_id} c.update(csrf(request)) return render_to_response( settings.CMBARTER_TURN_IS_RUNNING_TEMPLATE, c) else: raise
def _process_request_if_configured(self, request): """ Block the request if it is a login attempt to which a throttling delay is applicable. """ if request.method != "POST": return for url, template_name in self.logins: if request.path[1:] != url: continue delay = self._throttling_delay(request) if delay <= 0: request.META["login_request_permitted"] = True return form = _ThrottlingForm(delay, request) redirect_url = request.REQUEST.get(self.redirect_field_name, "") current_site = get_current_site(request) # Template-compatible with 'django.contrib.auth.views.login'. return csrf_protect(lambda request: render_to_response(template_name, {"form": form, self.redirect_field_name: redirect_url, "site": current_site, "site_name": current_site.name}, context_instance= RequestContext(request)) )(request)
def admin_view(self, view, cacheable=False): # [BEGIN] SAML Customization def inner(request, *args, **kwargs): session = request.session if 'SAML_REDIRECTION' not in session: if not self.has_permission(request): if request.path == reverse('admin:logout', current_app=self.name): index_path = reverse('admin:index', current_app=self.name) return HttpResponseRedirect(index_path) # Inner import to prevent django.contrib.admin (app) from # importing django.contrib.auth.models.User (unrelated model). from django.contrib.auth.views import redirect_to_login return redirect_to_login( request.get_full_path(), reverse('admin:login', current_app=self.name)) if 'SAML_REDIRECTION' in session and session['SAML_REDIRECTION'] is True and \ request.session['SAML_USER'] is not None: user = User.objects.get(username=request.session['SAML_USER']) request.user = user return view(request, *args, **kwargs) # [END] SAML Customization if not cacheable: inner = never_cache(inner) if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def as_view(cls, **kwargs): """ Optionally decorates the base view function with django.views.decorators.csrf.csrf_protect(). """ view = super(CsrfProtect, cls).as_view(**kwargs) return csrf.csrf_protect(view) if cls.csrf_protect else view
def urlpatterns(self): urlpatterns = super(RegistrationMultiView, self).urlpatterns if self.register_page_id and self.register_confirmation_email_id: urlpatterns += patterns('', url(r'^register$', csrf_protect(self.register), name='register'), url(r'^register/(?P<uidb36>\w+)/(?P<token>[^/]+)$', self.register_confirm, name='register_confirm') ) return urlpatterns
def admin_view(self, view): def no_wrap(request, *args, **kwargs): return view(request, *args, **kwargs) from django.views.decorators.csrf import csrf_protect from django.utils.functional import update_wrapper no_wrap = csrf_protect(no_wrap) return update_wrapper(no_wrap, view)
def wrapper(req, *args, **kwargs): if req.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): return (ensure_csrf_cookie(func))(req, *args, **kwargs) # Default cookie by CSRF_COOKIE_NAME in settings is 'csrftoken' # submit back in either req.form['csrfmiddlewaretoken'] or req['X-CSRFToken'] # the latter often used by Ajax and can be configured by CSRF_HEADER_NAME in settings else: func.csrf_exempt = False # reset csrf_exempt set by @csrf_exempt during @service return (csrf_protect(func))(req, *args, **kwargs)
def apply_decorators( view=None, login=False, staff=False, perms=None, # noqa: C901 cache=None, gzip=False, xframe=None, csrf=None, decorators=()): """ Apply decorators to view function. Can also be used as a decorator. """ if view is None: kwargs = locals() kwargs.pop('view') return lambda view: apply_decorators(view, **kwargs) # Cache control if cache is False: view = never_cache(view) elif cache is not None: view = cache_control(**cache)(view) # Permissions if login: view = login_required(view) if perms: view = permission_required(perms)(view) if staff: view = staff_required(view) # Compression if gzip: view = gzip_page(view) # Security if xframe is False: view = xframe_options_exempt(view) elif xframe == 'deny': view = xframe_options_deny(view) elif xframe == 'sameorigin': view = xframe_options_sameorigin(view) if csrf is False: view = csrf_exempt(view) elif csrf == 'cookie': view = ensure_csrf_cookie(view) elif csrf == 'token': view = requires_csrf_token(view) elif csrf is True: view = csrf_protect(view) # Apply final decorators for decorator in reversed(decorators): view = decorator(view) return view
def verify_and_call(*args, **kwargs): request = args[0] if request.COOKIES.get(settings.JWT_COOKIE_NAME): ret = csrf_protect(func)(*args, **kwargs) else: ret = func(*args, **kwargs) if isinstance(ret, Promise): ret = ret.get() return ret
def with_perms(self, view, cacheable=False): def inner(request, *args, **kwargs): if not self.has_permission(request): return self.login(request) return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def generic_ajax_func(func): return require_POST( csrf_protect( serialize_as_json( param_from_post( func ) ) ) )
def api_view(self, view, cacheable=False): def inner(request, *args, **kwargs): return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def stats_view(self, view): def inner(request, *args, **kwargs): if not self.has_permission(request): raise PermissionDenied return view(request, *args, **kwargs) if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def admin_view(self, view, cacheable=False): """ Decorator to apply common decorators to views for this admin. """ # FIXME: prohibit caching? def inner(request, *args, **kwargs): if not self.has_permission(request): return self.login(request, *args, **kwargs) return view(request, *args, **kwargs) inner = csrf_protect(inner) return inner
def admin_view(self, view, cacheable=False): def inner(request, *args, **kwargs): request.user = self.dummy_user if not self.has_permission(request): return HttpResponseForbidden() return view(request, *args, **kwargs) if not getattr(view, "csrf_exempt", False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def admin_view(self, view, cacheable=False): def inner(request, *args, **kwargs): if not self.has_permission(request): raise PermissionDenied return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. inner = csrf_protect(inner) return update_wrapper(inner, view)
def admin_view(self, view, cacheable=False): def inner(request, *args, **kwargs): request.user = DummyUser() if not self.has_permission(request): return HttpResponseForbidden() return view(request, *args, **kwargs) if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def urlpatterns(self): urlpatterns = super(RegistrationMultiView, self).urlpatterns if self.register_page_id and self.register_confirmation_email_id: urlpatterns += patterns( '', url(r'^register$', csrf_protect(self.register), name='register'), url(r'^register/(?P<uidb36>\w+)/(?P<token>[^/]+)$', self.register_confirm, name='register_confirm')) return urlpatterns
def CheckAuthorization(request: HttpRequest): key, auth = _authorize(request, permissions) print("key, auth %s %s" % (key, auth)) # Pass the view if a valid key was provided if key: return requires_csrf_token(fn)(request) # Protect the view from csrf if only logged in if auth: return csrf_protect(fn)(request) # Fail the authorization if fail_view is not None: return fail_view(request) raise PermissionDenied
def urlpatterns(self): urlpatterns = super(PasswordMultiView, self).urlpatterns if self.password_reset_page_id and self.password_reset_confirmation_email_id and self.password_set_page_id: urlpatterns += patterns( '', url(r'^password/reset$', csrf_protect(self.password_reset), name='password_reset'), url(r'^password/reset/(?P<uidb36>\w+)/(?P<token>[^/]+)$', self.password_reset_confirm, name='password_reset_confirm'), ) if self.password_change_page_id: urlpatterns += patterns( '', url(r'^password/change$', csrf_protect(self.login_required(self.password_change)), name='password_change'), ) return urlpatterns
def admin_view(self, view, cacheable=False): """Injects the `public_admin.sites.DummyUser` in every request in this admin site.""" def inner(request, *args, **kwargs): request.user = self.dummy_user if not self.has_permission(request): return HttpResponseForbidden() return view(request, *args, **kwargs) if not getattr(view, "csrf_exempt", False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def admin_view(self, view, cacheable=False): """ Decorator to create an admin view attached to this ``AdminSite``. This wraps the view and provides permission checking by calling ``self.has_permission``. You'll want to use this from within ``AdminSite.get_urls()``: class MyAdminSite(AdminSite): def get_urls(self): <<<<<<< HEAD from django.conf.urls import url urls = super(MyAdminSite, self).get_urls() urls += [ url(r'^my_view/$', self.admin_view(some_view)) ======= from django.urls import path urls = super().get_urls() urls += [ path('my_view/', self.admin_view(some_view)) >>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435 ] return urls By default, admin_views are marked non-cacheable using the ``never_cache`` decorator. If the view can be safely cached, set cacheable=True. """ def inner(request, *args, **kwargs): if not self.has_permission(request): if request.path == reverse('admin:logout', current_app=self.name): index_path = reverse('admin:index', current_app=self.name) return HttpResponseRedirect(index_path) # Inner import to prevent django.contrib.admin (app) from # importing django.contrib.auth.models.User (unrelated model). from django.contrib.auth.views import redirect_to_login return redirect_to_login( request.get_full_path(), reverse('admin:login', current_app=self.name) ) return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def _maybe_decorate_csrf(self, handler): '''csrf related decorators''' # csrf are simple, but usually # you want protect and occasionally exempt, # which exempt has precedence if self.use_csrf_protect_decorator and \ not self.use_csrf_exempt_decorator: handler = csrf_protect(handler) if self.debug_dispatch_method: logger.debug("csrf_protect decoration done") elif self.use_csrf_exempt_decorator: handler = csrf_exempt(handler) if self.debug_dispatch_method: logger.debug("csrf_exempt decoration done")
def dispatch(self, request, *args, **kwargs): # parse JSON and populate the request._json_data parameter # so that auth workflow can already access it _attempt_parse_json(request, self.api._logger) if not self.auth(request, *args, **kwargs): return JsonResponse( {'auth_error_info': self.auth_errors}, status=403 ) try: # attempt to set language, with the user's # language as the default whenever available lang = _get_raw_param(request, 'lang') if not lang and request.user.is_authenticated: lang = request.user.lang translation.activate(lang or settings.LANGUAGE_CODE) handler, kwargs_to_pass = self.extract_handler_kwargs(request) self.pre_call_log(request, kwargs_to_pass) if self.auth_result.issuer.csrf_exempt: response = handler(request, *args, **kwargs_to_pass) else: response = csrf_protect(handler)( request, *args, **kwargs_to_pass ) return response except APIError as e: self.log( logging.INFO, msg='API error response: %(msg)s, status %(status)d' % { 'msg': e.raw_message, 'status': e.status }, ) if self.gui_view: # GUI views should handle error conditions # themselves. Failing to do so => an automatic 500 # (details will appear in the logs anyway) return render(request, '500.html', status=500) else: return JsonResponse( {API_ERROR_FIELD: str(e)}, status=e.status ) except Exception as e: self.log( logging.CRITICAL, 'Server error during API call: %s' % str(e), exc_info=1 ) if self.gui_view: return render(request, '500.html', status=500) else: return SERVER_ERROR_RESPONSE
def admin_view(self, view, cacheable=False): """ Decorator to create an admin view attached to this ``AdminSite``. This wraps the view and provides permission checking by calling ``self.has_permission``. You'll want to use this from within ``AdminSite.get_urls()``: class MyAdminSite(AdminSite): def get_urls(self): from django.conf.urls import patterns, url urls = super(MyAdminSite, self).get_urls() urls += patterns('', url(r'^my_view/$', self.admin_view(some_view)) ) return urls By default, admin_views are marked non-cacheable using the ``never_cache`` decorator. If the view can be safely cached, set cacheable=True. """ def inner(request, *args, **kwargs): if not self.has_permission(request): country = get_country_from_url(request.get_full_path()) if request.path == reverse(country+':logout',current_app=self.name): index_path = reverse(country+':index', current_app=self.name) return HttpResponseRedirect(index_path) if not "/password/" in request.path: return self.login(request) else: if "/password/reset/done/" in request.path: return self.pwd_reset_done(request) elif "/password/reset/confirm/complete/" in request.path: return self.pwd_reset_confirm_complete(request) elif "/password/reset/confirm/" in request.path: return self.pwd_reset_confirm(request) else: return self.pwd_reset(request) return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def admin_view(self, view, cacheable=False): """ Override to pass kwargs to self.login so we can pass in URL variables """ def inner(request, *args, **kwargs): if not self.has_permission(request): return self.login(request, *args, **kwargs) return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def admin_view(self, view, cacheable = False): def inner(request, *args, **kwargs): if not self.has_permission(request): if request.path == reverse('logout', current_app=self.name): index_path = reverse('index', current_app=self.name) return HttpResponseRedirect(index_path) return self.login(request) return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def admin_view(self, view, cacheable=False): def inner(request, *args, **kwargs): if not self.has_permission(request): if request.path == reverse('admin:logout', current_app=self.name): index_path = reverse('admin:index', current_app=self.name) return HttpResponseRedirect(index_path) return redirect_to_login(request.get_full_path(), '/user/login.html') return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def new_view_func(request): print('Cookies: ',request.COOKIES,'\n\n\n',request.META) if request.method == 'POST': if request.META.get('HTTP_MOBILE',False): print('\n\nData: ',request.body,'\n\n') #temp = str(request.body)[2:-1].split('&') #try: request.POST = json.loads(request.body.decode('utf-8'))#.replace('\0', '')) #except: # request.POST = { i.split('=')[0] : convert(i.split('=')[1]) for i in temp } print("%s is about to be called"%view_func.__name__) ret = csrf_protect(view_func)(request) print("%s was called"%view_func.__name__) return ret
def admin_view(self, view, cacheable=False): def inner(request, *args, **kwargs): if not self.has_permission(request): if request.path == reverse('admin:logout', current_app=self.name): index_path = reverse('admin:index', current_app=self.name) return HttpResponseRedirect(index_path) return HttpResponseRedirect(settings.LOGIN_URL) return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def wrapp_view(self, meth): def wrapper(request, *args, **kwargs): view = login_required(meth, login_url=reverse('djoe_client:login')) return view(request, *args, **kwargs) if getattr(meth, 'jsonable', False): wrapper = self.json_decor(wrapper) if not getattr(meth, 'cacheable', False): wrapper = never_cache(wrapper) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(meth, 'csrf_exempt', False): wrapper = csrf_protect(wrapper) return wrapper
def new_view_func(request): print('Cookies: ', request.COOKIES, '\n\n\n', request.META) if request.method == 'POST': if request.META.get('HTTP_MOBILE', False): print('\n\nData: ', request.body, '\n\n') #temp = str(request.body)[2:-1].split('&') #try: request.POST = json.loads( request.body.decode('utf-8')) #.replace('\0', '')) #except: # request.POST = { i.split('=')[0] : convert(i.split('=')[1]) for i in temp } print("%s is about to be called" % view_func.__name__) ret = csrf_protect(view_func)(request) print("%s was called" % view_func.__name__) return ret
def admin_view(self, view, cacheable=False): """ Decorator to create an admin view attached to this ``AdminSite``. This wraps the view and provides permission checking by calling ``self.has_permission``. You'll want to use this from within ``AdminSite.get_urls()``: class MyAdminSite(AdminSite): def get_urls(self): from django.conf.urls import url urls = super(MyAdminSite, self).get_urls() urls += [ url(r'^my_view/$', self.admin_view(some_view)) ] return urls By default, admin_views are marked non-cacheable using the ``never_cache`` decorator. If the view can be safely cached, set cacheable=True. """ def inner(request, *args, **kwargs): if not self.has_permission(request): if request.path == reverse('admin:logout', current_app=self.name): index_path = reverse('admin:index', current_app=self.name) return HttpResponseRedirect(index_path) # Inner import to prevent django.contrib.admin (app) from # importing django.contrib.auth.models.User (unrelated model). from django.contrib.auth.views import redirect_to_login return redirect_to_login( request.get_full_path(), reverse('admin:login', current_app=self.name) ) return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)
def as_view(self, view, cacheable=False): "Wraps a view in authentication/caching logic" def inner(request, *args, **kwargs): if not self.has_permission(request): # show login pane return self.login(request, *args, **kwargs) return view(request, *args, **kwargs) # Mark it as never_cache if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view)