Skip to content

Amritpal Singh

  • About

authentication

November 8, 2017November 20, 2017 admin

Django login required middleware

Django provides a decorator called login_required that takes one of your views and prevents a user from seeing it unless they are logged in. Every time we need to add this decorator above view. Sometimes it’s a real pain to use the login_required decorator all over the views of your complicated site. What if you forget to add it to view that contains sensitive information?

Django allows you to write middleware that gets access to each request so you can add functionality that can be applied to your whole site. My middleware simply intercepts each request and redirects users to the site login page if they haven’t logged in. It also allows you to give of exceptions (in the form of regular expressions), i.e. pages that can be viewed without logging in.

Creates login_required_middleware.py file.

from django.http import HttpResponseRedirect
from django.conf import settings
from re import compile

EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
    EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]

class LoginRequiredMiddleware(object):
    """
    Middleware that requires a user to be authenticated to view any page other
    than LOGIN_URL. Exemptions to this requirement can optionally be specified
    in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which
    you can copy from your urls.py).
    Requires authentication middleware and template context processors to be
    loaded. You'll get an error if they aren't.
    """
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print "settings.DEBUG: ", settings.DEBUG
        assert hasattr(request, 'user'), "The Login Required middleware\
 requires authentication middleware to be installed. Edit your\
 MIDDLEWARE setting to insert\
 'django.contrib.auth.middleware.AuthenticationMiddleware'. If that doesn't\
 work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\
 'django.core.context_processors.auth'."
        if not request.user.is_authenticated():
            path = request.path_info.lstrip('/')
            if not any(m.match(path) for m in EXEMPT_URLS):
                return HttpResponseRedirect(settings.LOGIN_URL)
        return self.get_response(request)

Change or add settings.py file as given below:

# settings.py

LOGIN_URL = '/login/'

LOGIN_EXEMPT_URLS = (
 r'^$',
 r'^oauth/',
 r'^media/',
)

MIDDLEWARE_CLASSES = (
    # ...
    'python.path.to.LoginRequiredMiddleware',
)

Here is my login_required_middleware.py and settings.py file.

Source: http://onecreativeblog.com/post/59051248/django-login-required-middleware

https://docs.djangoproject.com/en/1.10/topics/http/middleware/#writing-your-own-middleware

 

November 15, 2016 admin

Power of Curl command

Download file which needs authentication of user and password from the server.

curl -O -u <user>:<password> <URL>

Enter your email address

Recent Posts

  • Comparison of reading IfcGloballyUniqueId from IFC in different OS
  • Git commands
  • Kill a process running on particular port in Linux
  • Deploy/Run a Django app with Apache and Gunicorn in Ubuntu
  • Deploy/Run a Django app with Nginx, Gunicorn and Supervisor in Ubuntu

Recent Comments

  • maillot de foot on Solving Differential Equation Representing Simple Harmonic Motion in SageMath
  • Elizabet Alward on Solving Differential Equation Representing Simple Harmonic Motion in SageMath
  • Jude Soloman on Solving Differential Equation Representing Simple Harmonic Motion in SageMath
  • Irina Ledec on Solving Differential Equation Representing Simple Harmonic Motion in SageMath
  • Harmanpreet Singh on Export drawing sheets of FreeCAD into PDF and SVG format from Python console – Done

Archives

  • March 2019
  • December 2017
  • November 2017
  • July 2017
  • March 2017
  • February 2017
  • January 2017
  • November 2016
  • September 2016
  • July 2016
  • June 2016
  • March 2016
  • February 2016
  • December 2015
  • October 2015
  • September 2015
  • August 2015
  • July 2015
  • June 2015

Archives

Recent Posts

  • Comparison of reading IfcGloballyUniqueId from IFC in different OS
  • Git commands
  • Kill a process running on particular port in Linux
  • Deploy/Run a Django app with Apache and Gunicorn in Ubuntu
  • Deploy/Run a Django app with Nginx, Gunicorn and Supervisor in Ubuntu
  • About