Login

login_required decorator that doesn't redirect

Author:
brutasse
Posted:
February 15, 2011
Language:
Python
Version:
1.2
Score:
3 (after 3 ratings)

A login_required decorator that wraps the login view instead of redirecting to it.

This prevents your site from leaking login information with HTTP status codes as explained here.

This is the way Django's admin is protected, the difference being that it checks for is_active and is_staff instead of is_authenticated.

With this decorators, users directly see a login form (no redirect), post it to LOGIN_URL and are redirected to the page they first tried to see.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from functools import wraps  # adapt if you need python 2.4 support

from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.views import login


def login_required(view_callable):
    def check_login(request, *args, **kwargs):
        if request.user.is_authenticated():
            return view_callable(request, *args, **kwargs)

        assert hasattr(request, 'session'), "Session middleware needed."
        login_kwargs = {
            'extra_context': {
                REDIRECT_FIELD_NAME: request.get_full_path(),
            },
        }
        return login(request, **login_kwargs)
    return wraps(view_callable)(check_login)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.