Authentication in Django

Authentication and authorization in django?

What is Authentication?

Authentication is the process of verifying a user's identity by checking their username and password. In Django, it compares the entered credentials with those stored in the database to grant access. Once authenticated, Django uses sessions to maintain the user's logged-in state across multiple requests.

What is Authorization?

Authorization is the process of determining what actions or resources a user is allowed to access after they've been authenticated. It controls what a user can do, such as viewing certain pages, editing content, or accessing specific data, based on their roles or permissions.

It determines access control based on:

User permissions: Permissions define what actions a user can take, like view, edit, or delete.

Group memberships: Groups assign shared permissions to users based on roles like admin or editor.

Staff/superuser status: Staff can access the admin panel and superusers have complete system control.

Components of Django Authentication System

An authentication system typically includes user registration, login, and password management to verify a user's identity. It also involves token-based or session-based mechanisms for maintaining user sessions and access control.

Here are the main components of an authentication system:

  • User Model
  • Authentication Backend
  • Sessions
User Model:

Django provides a default User model through django.contrib.auth.models.User, which is designed to manage common user-related fields. Here's a breakdown of the key attributes it includes:

username: A unique identifier for the user, typically used for login.

email: The user's email address.

first_name, last_name: The user's first and last names.

password: Stores the user's password in a hashed form for security.

is_staff: Indicates if the user has staff privileges to access the Django admin.

is_superuser: Marks if the user has superuser privileges (full access to all parts of the application)

is_active: Specifies whether the user's account is active or inactive.

last_login: Records the date and time of the user's last login.

date_joined: The date and time when the user account was created.

Create User Example
# views.py
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model

# Get the user model (you can use your custom user model if defined)
MyUser = get_user_model()

# Creating a new user
user = User.objects.create_user(
    username='john_doe', 
    email='john@example.com', 
    password='john@123'
)

# Updating user details
user.first_name = 'John'
user.is_active = True
user.save()

# Accessing user details
print(user.first_name)  # Output: John
print(user.is_active)  # Output: True
Authentication Backend:

In Django, authentication backends are classes that handle the authentication and authorization of users. They define how Django should authenticate users and retrieve their permissions.

Authentication Backend Example
# Default Django authentication backend
'django.contrib.auth.backends.ModelBackend'

# Custom authentication backend for mobile number login
AUTHENTICATION_BACKENDS = ['yourapp.backends.MobileBackend']

from django.contrib.auth.backends import BaseBackend
from django.contrib.auth import get_user_model

class MobileBackend(BaseBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        User = get_user_model()
        try:
            # Find the user by mobile number (username)
            user = User.objects.get(mobile=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        User = get_user_model()
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
Sessions:

Sessions in Django are used to store and retrieve user-specific data across requests, typically for managing user login states. They work by assigning a unique session ID to each user, which is stored in a cookie and linked to session data on the server.

Session Example
# Add item to the shopping cart in the session
def add_to_cart(request, item_id):
    cart = request.session.get('cart', [])
    cart.append(item_id)
    request.session['cart'] = cart
    return HttpResponse("Item added to cart.")

# View the shopping cart from the session
def view_cart(request):
    cart = request.session.get('cart', [])
    return HttpResponse(f"Your cart: {cart}")

What is a Group in Django?

A group in Django is a way to assign multiple users the same set of permissions, simplifying the management of permissions for users with similar roles like Admin or Editor. It is essentially a Django model; treat it like any other model to create, update, and manage it, giving you full control over group operations and permissions.

Group Example
from django.contrib.auth.models import Group, Permission
from django.contrib.auth import get_user_model

MyUser = get_user_model()

# Create a new group
group = Group.objects.create(name='Editors')

# Assign permissions to the group
permission_add = Permission.objects.get(codename='add_post')
permission_change = Permission.objects.get(codename='change_post')
group.permissions.add(permission_add, permission_change)

# Add the user to the group
user = request.user
user.groups.add(group)

# Check if the user has permission to add MyModel
if user.has_perm('core.add_post'):
    print("User can add Post.")
else:
    print("User cannot add Post.")

# Update the group's permissions (e.g., removing one and adding another)
permission_delete = Permission.objects.get(codename='delete_post')
group.permissions.remove(permission_add)
group.permissions.add(permission_delete)

What are Permissions in Django?

Permissions in Django are a way to restrict access to specific actions or resources within an application. They are typically used to manage what users can and cannot do, such as adding, changing, or deleting objects. Permissions can be assigned to users or groups to control access to various parts of the application.

Permissions Example
from django.contrib.auth.models import Permission
from django.contrib.auth import get_user_model

MyUser = get_user_model()

# Create a new permission (you can create your own permissions or get existing ones)
permission_add = Permission.objects.get(codename='add_post')
permission_change = Permission.objects.get(codename='change_post')

# get the user
user = request.user

# Assign permissions directly to the user
user.user_permissions.add(permission_add, permission_change)

# Check if the user has permission
if user.has_perm('core.add_post'):
    pass
else:
    pass

Exercise

  1. Fill in the Blanks:
    • - The process of verifying a user's identity in Django is called __________.
    • - __________ is used to determine what actions or resources a user can access after authentication.
    • - In Django, the function __________ returns the custom user model if one is defined.
    • - o check if a user has a specific permission in Django, you can use the __________ method.
    • - To assign a user to a group in Django, you use the method __________.