Sobes.tech
Middle
207

How does the authentication system work in Django?

Answer from AI

sobes.tech AI

In Django, authentication is based on an pluggable backend that handles users, groups, and permissions.

Main components:

  • Users: The django.contrib.auth.models.User model stores user information (name, hashed password, email, etc.).
  • Groups: The django.contrib.auth.models.Group model groups users for easier permission management.
  • Permissions: The django.contrib.auth.models.Permission model defines what actions a user is allowed to perform (view, add, change, delete models).
  • Authentication Backends: Classes that implement methods for authentication (authenticate) and authorization (get_user, has_perm, has_module_perms). By default, django.contrib.auth.backends.ModelBackend is used.

Authentication process:

  1. The user submits login and password (usually via a form).
  2. Django calls the authenticate() method of configured backends, passing the credentials.
  3. The backend searches for the user by login.
  4. If the user is found, the backend checks the password (comparing hashes).
  5. If the check is successful, authenticate() returns the user object.
  6. Django calls login() (in the view or middleware), which sets the session for the user.

Example usage in a view:

# views.py
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect

def login_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            return redirect('some_success_page')
        else:
            # Handle authentication error
            pass
    return render(request, 'login.html')

Main functions and decorators for authentication and permission checks:

  • @login_required: Decorator for views that require user authentication.
  • @permission_required('app_label.permission_code'): Decorator for views that require a specific permission.
  • user.is_authenticated: Checks if the user is authenticated.
  • user.has_perm('app_label.permission_code'): Checks if the user has a specific permission.
  • user.has_module_perms('app_label'): Checks if the user has permissions for a model in a specific app.

Configuration:

  • AUTHENTICATION_BACKENDS: List of registered backends. Defaults to ['django.contrib.auth.backends.ModelBackend'].
  • LOGIN_URL: URL to redirect unauthenticated users when using @login_required.
  • LOGIN_REDIRECT_URL: URL to redirect after successful login.