Auth module is a standard permission management system provided by Django. It can provide user identity authentication, user group management, and can be used in combination with admin module. Add 'django.contrib.auth' in installed Apus to use the app, and the auth module is enabled by default
model
from django.contrib.auth.models import User
# The name of the table in the database is auth? User
CREATE TABLE "auth_user" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"password" varchar(128) NOT NULL, "last_login" datetime NULL,
"is_superuser" bool NOT NULL,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL,
"email" varchar(254) NOT NULL,
"is_staff" bool NOT NULL,
"is_active" bool NOT NULL,
"date_joined" datetime NOT NULL,
"username" varchar(30) NOT NULL UNIQUE
)
New user
user = User.objects.create_user(username, email, password)
user.save()
# Store a Hash value instead of user password plaintext
Certified user
from django.contrib.auth import authenticate
user = authenticate(username=username, password=password)
# If the password of the authenticated user is valid, the user object representing the user will be returned if it is valid, and if it is invalid, None will be returned
# This method does not check the is active flag bit
Change Password
user.set_password(new_password)
# In the following example, the password can be changed only after the authentication is passed
user = auth.authenticate(username=username, password=old_password)
if user is not None:
user.set_password(new_password)
user.save()
Sign in
from django.contrib.auth import login
# login adds the session key to the session to facilitate the tracking of users:
'login(request, user)'
# login does not authenticate or check the is "active flag bit
# Example
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
Sign out
# logout removes the user information from the request and refreshes the session
from django.contrib.auth import logout
def logout_view(reque
Only logged in users are allowed access
@The view function decorated by the login? Required modifier will first check whether the user is logged in through the session key. The logged in user can perform normal operations. The user who is not logged in will be redirected to the location specified by the login? URL. If the login? URL parameter is not specified, it will be redirected to the settings.login? URL
from django.contrib.auth.decorators import login_required
@login_required(login_url='/accounts/login/')
def userinfo(request):
...
# settings configuration
LOGIN_URL = '/index/'
# views
@login_required
def userinfo(request):
...