Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Django - Authentication

Back


Overview


Installation


Authentication in web requests

if request.user.is_authenticated:
    # Do something for authenticated users.
else:
    # Do something for anonymous users.

Log in a User

from django.contrib.auth import authenticate, login


def my_view(request):
    username = request.POST["username"]
    password = request.POST["password"]
    # authenticate the user with username and pwd by the current seesion.
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)    # attach the authenticated user to the current session.
        # Redirect to a success page.
    else:
        # Return an 'invalid login' error message.

Log out a User

from django.contrib.auth import logout

def logout_view(request):
    logout(request)
    # Redirect to a success page.

Limiting access to logged-in users

# login page
from django.conf import settings
from django.shortcuts import redirect


def my_view(request):
    if not request.user.is_authenticated:
        return redirect(f"{settings.LOGIN_URL}?next={request.path}")
    # ...

# display an error message.
from django.shortcuts import render


def my_view(request):
    if not request.user.is_authenticated:
        return render(request, "myapp/login_error.html")
    # ...


from django.contrib.auth.decorators import login_required


@login_required
def my_view(request):
    pass

Limiting access to logged-in users that pass a test

from django.shortcuts import redirect


def my_view(request):
    # this view checks to make sure the user has an email in the desired domain and if not, redirects to the login page
    if not request.user.email.endswith("@example.com"):
        return redirect("/login/?next=%s" % request.path)
from django.contrib.auth.decorators import user_passes_test


def email_check(user):
    return user.email.endswith("@example.com")


@user_passes_test(email_check)
def my_view(request):
from django.contrib.auth.decorators import permission_required


@permission_required("polls.add_choice")
def my_view(request):
  pass

TOP