Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Restricting View Access with the @login_required Decorator in Django

Tech May 14 2

In web application development, a common requirement is to ensure that specific views are accessible only to authenticated users. The desired behavior typically follows this flow:

  • Access to restricted pages is blocked for users who are not logged in.
  • If an unauthenticated user attempts to access a restricted URL, they are redirected to the login page.
  • After successfully logging in, the user is automatically forwarded to the URL they originally intended to visit.

Django provides a robust and simple way to implement this functionality using the built-in @login_required decorator. The implemantation involves modifying the view, updating the settings, and configuring the URL routing.

1. Configuring the View

To secure a specific view, import the login_required decorator from django.contrib.auth.decorators and apply it above the view function. If the user is not authenticated, the application will redirect them to the login URL.

from django.shortcuts import render
from django.contrib.auth.decorators import login_required

@login_required(login_url='/auth/sign-in/')
def member_dashboard(request):
    context = {}
    return render(request, 'dashboard.html', context)

In the example above, if an anonymous user tries to access member_dashboard, they will be sent to /auth/sign-in/. If the login_url parameter is omitted in the decorator, Django defaults to the value specified in the settings file.

2. Settings Configuration

In your settings.py file, define the LOGIN_URL. This is the global fallback location where unauthenticated users will be sent. Django automatically appends a next query parameter to this URL containing the original path (e.g., /auth/sign-in/?next=/dashboard/).

# settings.py
LOGIN_URL = '/auth/sign-in/'

3. URL Configuraton

Ensure your urls.py includes the correct routing for both your protected views and the login endpoint. Below is an example configuration.

from django.urls import path
from django.contrib import admin
from core import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('auth/sign-in/', views.login_view, name='login'),
    path('logout/', views.logout_view, name='logout'),
    path('dashboard/', views.member_dashboard, name='dashboard'),
]

Underlying Logic

The @login_required decerator acts as a wrapper around the user_passes_test utility. It verifies if request.user.is_authenticated returns True. If the check fails, it triggers a redirect to the login page. If the check passes, the view executes normally, allowing the developer to safely assume the user is logged in.

def login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """
    Decorator for views that checks that the user is logged in, redirecting
    to the log-in page if necessary.
    """
    actual_decorator = user_passes_test(
        lambda u: u.is_authenticated,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    return actual_decorator

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.