Once we have django-elevate installed and configured, we need to decide which views should be secured.


The meat of django-elevate comes from decorating your views with @elevate_required much in the same way that @login_required works.

Let’s pretend that we have a page on our site that has sensitive information that we want to make extra sure that a user is allowed to see it:

from elevate.decorators import elevate_required

@login_required  # Make sure they're at least logged in
@elevate_required  # On top of being logged in, are you in Elevate mode?
def super_secret_stuff(request):
    return HttpResponse('your social security number')

That’s it! When a user visits this page and they don’t have the correct permission, they’ll be redirected to a page and prompted for their password. After entering their password, they’ll be redirected back to this page to continue on what they were trying to do.

class elevate.mixins.ElevateMixin

ElevateMixin provides an easy way to elevate a class-based view. Any view that inherits from this mixin is automatically wrapped by the @elevate_required decorator.

This works well with the LoginRequiredMixin from django-braces:

from django.views import generic
from braces.views import LoginRequiredMixin
from elevate.mixins import ElevateMixin

class SuperSecretView(LoginRequiredMixin, ElevateMixin, generic.TemplateView):
    template_name = 'secret/super-secret.html'

Returns a boolean to indicate if the current request is in Elevate mode or not. This gets added on by the ElevateMiddleware. This is an shortcut for calling has_elevated_privileges() directly.

class elevate.middleware.ElevateMiddleware

By default, you just need to add this to your MIDDLEWARE list.

has_elevated_privileges(self, request)

Subclass and override has_elevated_privileges() if you’d like to override the default behavior of request.is_elevated().

process_request(self, request)

Adds is_elevated() to the request.

process_response(self, request, response)

Controls the behavior of setting and deleting the Elevate cookie for the browser.

elevate.utils.grant_elevated_privileges(request, max_age=ELEVATE_COOKIE_AGE)

Assigns a random token to the user’s session that allows them to have elevated permissions.

from elevate.utils import grant_elevated_privileges
token = grant_elevated_privileges(request)

Revoke elevated privileges from a request explicitly

from elevate.utils import revoke_elevated_privileges

Check if a request is allowed to perform elevated actions.

from elevate.utils import has_elevated_privileges
has_elevate = has_elevated_privileges(request)