Django User Authentication Component Explanation
- 2021-07-24 11:33:41
- OfStack
1. auth module
# Create Super User
python manage.py createsuperuser
from django.contrib import auth
Many methods are provided in django. contrib. auth:
authenticate()
Provides user authentication function, that is, to verify whether the user name and password are correct, 1 generally requires username, password two keyword parameters.
If the authentication is successful (the username and password are correct and valid), 1 User object is returned.
authenticate () sets a property on the User object to indicate that the backend has authenticated the user and that this information is required during subsequent login.
from django.contrib.auth import authenticate
user = authenticate(username="user",password="pwd")
login(HttpRequest, user)
This function accepts one HttpRequest object and one authenticated User object; This function realizes the function of logging in one user. It essentially generates relevant session data for the user at the back end.
from django.contrib.auth import authenticate, login
def log_in(request):
if request.method == "POST":
user = request.POST.get("username")
pwd = request.POST.get("password")
user = authenticate(username=user, password=pwd)
if user is not None:
login(request, user)
# Redirect to a success page
...
else:
# Return an "invalid login" error message.
...
return render(request, "login.html")
logout (request) Logoff User
This function accepts 1 HttpRequest object with no return value. When this function is called, all session information of the current request is cleared. Even if the user is not logged in, there will be no error when using this function.
from django.contrib.auth import logout
def log_out(request):
logout(request)
# Redirect to a success page.
2. User object
User Object Properties: username, password (required); password is saved to database by hashing algorithm
is_staff: Does the user have administrative privileges for the Web site
is_active: Whether to allow the user to log in. Set to "False" to prevent users from logging in without deleting them
is_authenticated()
If it is a real User object, the return value is always True;; Used to check whether the user has passed the authentication.
Authentication does not mean that the user has any privileges, nor does it even check whether the user is active, it only means that the user has successfully passed the authentication. This method is very important. In the background, use request.user.is_authenticated () to judge whether the user has logged in. If it is true, you can show request. user. name to the foreground.
Requirements:
Some pages can only be accessed after users log in If the user accesses this page without logging in, skip directly to the login page After the user completes the login in the jump login interface, the user automatically accesses and jumps to the previously accessed addressMethod 1:
def my_view(request):
if not request.user.is_authenticated():
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
Method 2:
django has designed a decorator for us in this case: login_requierd ()
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
...
Use login_requierd () Note:
If the user is not logged in, it will jump to the default login of django URL '/accounts/login/'; And pass the absolute path to the current access to url (which will be redirected after successful login).
If you need to customize the login URL, you need to modify it through LOGIN_URL in the settings. py file.
LOGIN_URL = "/login/" # This is configured as the route of the project login page
create_user () Create user
from django.contrib.auth.models import User
user = User.objects.create_user ( username="", password="", email="", ... )
create_superuser () Create superuser
from django.contrib.auth.models import User
user = User.objects.create_superuser ( username="", password="", email="", ... )
check_password(password)
A way to check whether the password is correct; The password returns True correctly, otherwise it returns False.
ret = user.check_password(" Password ")
set_password(password)
1 method to modify the password, and receive the new password to be set as a parameter.
Note: After setting 1, you must call the save method of the User object! ! !
from django.contrib.auth import authenticate
user = authenticate(username="user",password="pwd")
0
Example of changing passwords:
from django.contrib.auth import authenticate
user = authenticate(username="user",password="pwd")
1
3. Extend the default auth_user table
Define an Model class of your own by inheriting the built-in AbstractUser class. In this way, the user table can be designed flexibly according to the project requirements, and the powerful authentication system of Django can be used.
from django.contrib.auth import authenticate
user = authenticate(username="user",password="pwd")
2
Note:
After extending the built-in auth_user table as above, 1 must tell Django in settings. py that I now use my newly defined UserInfo table for user authentication:
# Quote Django Bring your own User Table, which needs to be set when inheriting and using
AUTH_USER_MODEL = "app Name .UserInfo"
1 Once we specify the table to be used by the new authentication system, we need to re-create the table in the database instead of using the original default auth_user table.
4. Examples
views.py
from django.contrib.auth import authenticate
user = authenticate(username="user",password="pwd")
4
The sign_up function section originally used User. objects, but because the UserInfo table is used instead of the auth_user table built into django, it needs to be changed to models. UserInfo. objects
login.html
from django.contrib.auth import authenticate
user = authenticate(username="user",password="pwd")
5
register.html
from django.contrib.auth import authenticate
user = authenticate(username="user",password="pwd")
6
index.html
from django.contrib.auth import authenticate
user = authenticate(username="user",password="pwd")
7