All technological notes.
Django authentication system
authentication and authorization.Authentication
Authorization
The term authentication is used to refer to both tasks.
UsersPermissions
Groups
django.contrib.auth.
settings.py generated by django-admin startproject, these consist of two items listed in your INSTALLED_APPS setting:
'django.contrib.auth':
'django.contrib.contenttypes':MIDDLEWARE setting:
SessionMiddleware:
AuthenticationMiddleware:
manage.py migrate creates the necessary database tables for auth related models and permissions for any models defined in your installed apps.Django uses sessions and middleware to hook the authentication system into request objects.
.user attribute represents the current user.
AnonymousUser.User.is_authenticated attribute can tell apart.if request.user.is_authenticated:
# Do something for authenticated users.
else:
# Do something for anonymous users.
login(request, user) to attatch an authenticated user to the current session.
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.
logout(request) to log out the logged user.
logout() doesn’t throw any errors if the user wasn’t logged in.logout(), the session data for the current request is completely cleaned out. All existing data is removed.from django.contrib.auth import logout
def logout_view(request):
logout(request)
# Redirect to a success page.
request.user.is_authenticated and either redirect to a login page or display an error message.# 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")
# ...
Using login_required decorator
login_required():
settings.LOGIN_URL, passing the current absolute path in the query string. Example: /accounts/login/?next=/polls/3/.redirect_field_name:
next parameter in query stringlogin_url:
settings.LOGIN_URLfrom django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
pass
run test on request.user in the view directly using user_passes_test()
Example:
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)
@user_passes_test decoratorfrom 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):
permission_required() decorator
from django.contrib.auth.decorators import permission_required
@permission_required("polls.add_choice")
def my_view(request):
pass