コード例 #1
0
ファイル: tests.py プロジェクト: 756613351/django
 def test_get_token_for_requires_csrf_token_view(self):
     """
     Check that get_token works for a view decorated solely with requires_csrf_token
     """
     req = self._get_GET_csrf_cookie_request()
     resp = requires_csrf_token(token_view)(req)
     self._check_token_present(resp)
コード例 #2
0
ファイル: route.py プロジェクト: ejplatform/django-boogie
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
コード例 #3
0
ファイル: tests.py プロジェクト: Justes/learndj
 def test_get_token_for_requires_csrf_token_view(self):
     """
     Check that get_token works for a view decorated solely with requires_csrf_token
     """
     req = self._get_GET_csrf_cookie_request()
     resp = requires_csrf_token(token_view)(req)
     self._check_token_present(resp)
コード例 #4
0
    def password_change(self, request):
        """ Return 'password_change' view.
        This resolves the view with the name 'password_change'.

        Overwrite this method when needed.
        """
        view_func, args, kwargs = resolve(self.change_password_path)

        if 'password_change_form' in kwargs:
            assert issubclass(kwargs['password_change_form'],
                              StrictPasswordChangeForm), (
                "Use django_auth_policy StrictPasswordChangeForm for password "
                "changes.")

        # Provide extra context to be used in the password_change template
        if 'extra_context' in kwargs:
            kwargs['extra_context']['password_change_enforce'] = \
                request.session.get('password_change_enforce')
            kwargs['extra_context']['password_change_enforce_msg'] = \
                request.session.get('password_change_enforce_msg')

        # Run 'requires_csrf_token' because CSRF middleware might have been
        # skipped over here
        resp = requires_csrf_token(view_func)(request, *args, **kwargs)
        update_password(request.session, request.user)
        return resp
コード例 #5
0
    def process_request(self, request):
        if not hasattr(request, 'user'):
            raise Exception('Install Authentication middleware before '
                            'LoginRequiredMiddleware')

        if request.user.is_authenticated():
            return None

        # Do not require authentication for certain URLs
        if request.path in self.public_urls:
            return None

        # Django should not serve STATIC files in production, but for
        # development this should be no problem
        if (settings.STATIC_URL and
                request.path.startswith(settings.STATIC_URL)):

            if settings.DEBUG:
                return None
            else:
                return http.HttpResponseForbidden('Login required')

        # When serving MEDIA files through Django we will not display a login
        # form, but instead return HTTP 403 Forbidden
        if (settings.MEDIA_URL and
                request.path.startswith(settings.MEDIA_URL)):

            return http.HttpResponseForbidden('Login required')

        view_func, args, kwargs = resolve(self.login_path)
        return requires_csrf_token(view_func)(request, *args, **kwargs)
コード例 #6
0
ファイル: middleware.py プロジェクト: mugaya/cpims-v2.4
    def password_change(self, request):
        """Return 'password_change' view.

        This resolves the view with the name 'password_change'.
        Overwrite this method when needed.
        """
        view_func, args, kwargs = resolve(self.change_password_path)

        if 'password_change_form' in kwargs:
            """Check if been flagged."""
            assert issubclass(
                kwargs['password_change_form'], StrictPasswordChangeForm), (
                    "Use cpovc_access StrictPasswordChangeForm for password "
                    "changes.")

        # Provide extra context to be used in the password_change template
        if 'extra_context' in kwargs:
            kwargs['extra_context']['password_change_enforce'] = \
                request.session.get('password_change_enforce')
            kwargs['extra_context']['password_change_enforce_msg'] = \
                request.session.get('password_change_enforce_msg')

        # Run 'requires_csrf_token' because CSRF middleware might have been
        # skipped over here
        resp = requires_csrf_token(view_func)(request, *args, **kwargs)
        update_password(request.session, request.user)
        return resp
コード例 #7
0
ファイル: route.py プロジェクト: davidCarlos/django-boogie
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
コード例 #8
0
ファイル: csrf.py プロジェクト: ebpetway/django-daydreamer
 def as_view(cls, **kwargs):
     """
     Optionally decorates the base view function with
     django.views.decorators.csrf.requires_csrf_token().
     
     """
     view = super(RequiresCsrfToken, cls).as_view(**kwargs)
     return (
         csrf.requires_csrf_token(view)
             if cls.requires_csrf_token
             else view)
コード例 #9
0
ファイル: decorators.py プロジェクト: ttocsneb/BlueWeather
 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
コード例 #10
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        if not hasattr(request, 'user'):
            raise Exception('Install Authentication middleware before '
                            'LoginRequiredMiddleware')

        if request.user.is_authenticated():
            return None

        # Do not require authentication for certain URLs
        if request.path in self.public_urls:
            return None

        # Per-view exceptions
        if getattr(view_func, LOGIN_NOT_REQUIRED_MARKER, False):
            return None

        # Django should not serve STATIC files in production, but for
        # DEBUG mode this should be no problem (development)
        if settings.STATIC_URL and \
                request.path.startswith(settings.STATIC_URL):

            if settings.DEBUG:
                return None
            else:
                return http.HttpResponse('Unauthenticated', status=401)

        # When serving MEDIA files through Django we will not display a login
        # form, but instead return HTTP 401, but for DEBUG mode this should be
        # no problem (development)
        if settings.MEDIA_URL and \
                request.path.startswith(settings.MEDIA_URL):

            if settings.DEBUG:
                return None
            else:
                return http.HttpResponse('Unauthenticated', status=401)

        # Ajax views should not display a login form, we use HTTP 401 to
        # indicate an unauthorized request, like a session timeout
        if request.is_ajax():
            return http.HttpResponse('Unauthenticated', status=401)

        view_func, args, kwargs = resolve(self.login_path)
        return requires_csrf_token(view_func)(request, *args, **kwargs)
コード例 #11
0
    def process_view(self, request, view_func, view_args, view_kwargs):
        if not hasattr(request, 'user'):
            raise Exception('Install Authentication middleware before '
                            'LoginRequiredMiddleware')

        if request.user.is_authenticated():
            return None

        # Do not require authentication for certain URLs
        if request.path in self.public_urls:
            return None

        # Per-view exceptions
        if getattr(view_func, LOGIN_NOT_REQUIRED_MARKER, False):
            return None

        # Django should not serve STATIC files in production, but for
        # DEBUG mode this should be no problem (development)
        if settings.STATIC_URL and \
                request.path.startswith(settings.STATIC_URL):

            if settings.DEBUG:
                return None
            else:
                return http.HttpResponse('Unauthenticated', status=401)

        # When serving MEDIA files through Django we will not display a login
        # form, but instead return HTTP 401, but for DEBUG mode this should be
        # no problem (development)
        if settings.MEDIA_URL and \
                request.path.startswith(settings.MEDIA_URL):

            if settings.DEBUG:
                return None
            else:
                return http.HttpResponse('Unauthenticated', status=401)

        # Ajax views should not display a login form, we use HTTP 401 to
        # indicate an unauthorized request, like a session timeout
        if request.is_ajax():
            return http.HttpResponse('Unauthenticated', status=401)

        view_func, args, kwargs = resolve(self.login_path)
        return requires_csrf_token(view_func)(request, *args, **kwargs)
コード例 #12
0
ファイル: urls.py プロジェクト: rnvarma/IXEDU
from django.conf.urls import include, url
from django.views.decorators.csrf import ensure_csrf_cookie, requires_csrf_token

from university.views import *

urlpatterns = [
    url(r'^uni/(?P<u_id>[a-zA-Z0-9_.-]+)$', UniversityProfile.as_view()),
    url(r'^uni/(?P<u_id>[a-zA-Z0-9_.-]+)/form$', UniversityForm.as_view()),
    url(r'^uni/(?P<u_id>[a-zA-Z0-9_.-]+)/editresources$',
        UniversityResources.as_view()),
    url(r'^removeresource$',
        requires_csrf_token(UniversityRemoveResources.as_view())),
    url(r'^addresource$',
        requires_csrf_token(UniversityAddResources.as_view())),
    url(r'^changeresource$',
        requires_csrf_token(UniversityChangeResource.as_view())),
    url(r'^changeresourceorder$',
        requires_csrf_token(UniversityChangeResourceOrder.as_view())),
    url(r'^uploadphoto$', requires_csrf_token(UniversityPhoto.as_view())),
    url(r'^editmetadata$', requires_csrf_token(UniversityMetaData.as_view())),
    url(r'^changeuniadmin$',
        requires_csrf_token(UniversityChangeAdmins.as_view())),
    url(r'^removeuniadmin$',
        requires_csrf_token(UniversityRemoveAdmin.as_view())),
    url(r'^adduniadmin$', requires_csrf_token(UniversityAddAdmin.as_view())),
]