Django user login & logout

Prerequisites

User login

  • User login is the process that allows users to authenticate themselves when accessing a system or application.
  • This process typically involves users providing credentials, such as a username and password, to verify their identity.
  • Once authenticated, users gain access to resources or functionality that are restricted to authorized users.

User login process

  • Credential Submission

    • When a user wants to access a restricted area of an application, they are usually prompted to enter their credentials.
    • This commonly involves a login form where the user inputs their username and password.
  • Authentication

    • The system takes the submitted credentials and checks them against the stored user data in the database. This involves:
      • Validating the username: Ensuring the username exists in the system.
      • Password verification: Comparing the entered password with the one stored in the database, which is typically hashed for security purposes.
  • Session Creation

    • If the credentials are correct, the system creates a session for the user.
    • A session is a way to track the user's state and identity across multiple requests.
    • This session is usually maintained using a session ID stored in a cookie on the user's browser.
  • Access Control

    • After authentication, the system determines what resources or actions the user is authorized to access based on their role or permissions.
    • For instance, a logged-in user might access their dashboard, account settings, or exclusive content, while a non-logged-in user cannot.
  • Session Maintenance

    • Throughout the user's interaction with the system, the session is used to ensure that the user remains authenticated without needing to log in repeatedly.
    • This session persists until the user logs out or the session expires.
  • Logout:

    • When the user logs out, the session is terminated, effectively ending their authenticated state
    • This prevents unauthorized access if someone else tries to use the same device or browser.

Importance of User Login

  • Security: Ensures that only authorized users can access certain areas of the application.
  • Personalization: Logged-in users can have personalized experiences, such as accessing their profile, settings, or saved data.
  • Data Integrity: Protects user data by preventing unauthorized access to sensitive information.

Coding - Django login

Create login form

  • Requirements:

    • Ask user for username and password
    • Do basic field validation for username and password
  • open file my_app/forms.py and add the below code to it.

from django import forms

class UserLoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)
  • Above form takes the inputs username and password

add template login.html to templates directory

  • creat the file templates/login.html and add below code to it.

    templates/login.html

<html>
    <title>User Login</title>
    <body>
        <h1>User login</h1>
        <form action="" method="POST">
            {% csrf_token %}
            {{ form.as_p }}
            <p>{{error}}</p>
            <input type="submit" value="submit" />
        </form>
    </body>
</html>

create login & logout views

  • Requirements for login view:

    • Greet user if the user already logged in [i.e Hello username]
    • Render login form to the user if not logged in.
    • If user posts in the username and password then validate it and login the user if credentials are correct.
    • If credentials are incorrect then render the form with error messages.
  • Requirements for logout view:

    • Just logout the user by destroying the user session.
  • open file my_app/view.py and add below code to it.

from django.contrib.auth import login, logout, authenticate
from django.http.response import HttpResponse
from django.shortcuts import render
from .forms import UserLoginForm

def login_user(request):
    if request.user.is_authenticated:
        return HttpResponse(f"Hello {request.user.username}")
    error = ""
    if request.method == "POST":
        form = UserLoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password")
            user = authenticate(username=username, password=password)
            if user and user.is_active:
                login(request, user)
                return HttpResponse(f"Hello {request.user.username}.")
            elif user and not user.is_active:
                error = "User account is inactive"
            else:
                error = "Invalid credentials"
    else:
        form = UserLoginForm()
    template = "login.html"
    context = {"form": form, "error": error}
    return render(request, template, context)

def logout_user(request):
    logout(request)
    return HttpResponse("User logged out")
  • lets talk about imported auth functions

    • authenticate - it validates the username and password and returns the user object
    • login - create the new session for the logged in user.
    • logout - delete th user session.

configure the login view to urls.py

  • Lets create the file my_app/urls.py and add below code to it.
  • Configure the urls 1. login/ and 2. logout/
from django.urls import path
from . import views

urlpatterns = [
    ...
    path("login/", views.login_user),
    path("logout/", views.logout_user)
    ...
]

Test the login & logout views