SoFunction
Updated on 2024-12-19

The use of auth module user authentication in Django

What is the auth module

The auth module is a user authentication module that comes with django.

  • Development of a website, the inevitable need to design and implement the site's user system. At this time, we need to realize including user registration, user login, user authentication, logout, change password and other functions.
  • Django has a strong built-in user authentication system, auth, which uses the auth_user table to store user data by default.

Common methods of the auth module

authenticate()

Provides a user authentication function, that is, to verify the user name and password is correct, generally need username, password two keyword parameters.
If the authentication is successful (username and password are correct and valid), a User object is returned.
authenticate() sets an attribute on the User object that identifies that the backend has authenticated the user and that this information is required for subsequent logins.

usage

user = authenticate(username='usernamer', password='password')    # User name and password authentication successfully returns a user object.

login(HttpRequest, user)

  • The function accepts an HttpRequest object, and an authenticated User object.
  • This function implements a user login. It essentially generates the relevant session data for that user on the backend.

usage

from  import authenticate, login


def my_view(request):  # Define a function for authentication that gets the username and password entered by the user.
    username = ['username']
    password = ['password']
    user = authenticate(username=username, password=password)  # Get the username and password by authenticate() to get the user counterpart.
    if user is not None:  # When the user object exists, it means that the authentication is successful and returns a user object, and if the authentication is a bar, it returns a none.
        login(request, user)  # Pass in the user object returned from a successful login, so that you can record the user's login status, (in the global storage of user information, in any view function can be taken out), people have any parameters to pass what
        # Redirect to a success page.
        ...
    else:
        # Return an 'invalid login' error message.
        ...

logout(request)

This function accepts an HttpRequest object with no return value.
When this function is called, all session information for the current request is cleared. Even if the user is not logged in, using this function will not report an error.

usage

user.set_password(password='')
()  # Be sure to save your password when you're done changing it

from  import logout

def logout_view(request):
  logout(request)  # Log out of the login state, this is to delete the session information.
  # Redirect to a success page.

is_authenticated()

Used to determine if the current request has passed authentication.

usage

def my_view(request):
    if not .is_authenticated():  # Determine whether the current user object is authenticated and whether the user is logged in.
        return redirect('%s?next=%s' % (settings.LOGIN_URL, ))  # No user authentication, then we redirect the user to the login page before re-login

login_requierd()

auth provides us with a decorator tool to quickly add login checks to a view, login_requierd has a parameter, login_url when we are not logged in can let him jump to the url we specify.
If the user is not logged in, it will jump to django's default login URL '/accounts/login/ ' and pass the absolute path of the currently accessed url (to which it will be redirected after a successful login).
If you need to customize the login URL, you need to change it in the file via LOGIN_URL.

LOGIN_URL = '/login/'  # Configure this as the route for your project's login page, globally

usage

from  import login_required
  
@login_required  # Add a login validation decorator that will only go below if the login is successful, otherwise it will jump to the django default login
def my_view(request):
  ...

create_user()&create_superuser()

auth provides a way to create a new user with the necessary parameters (username, password) etc.

Usage:

from  import User

user = .create_user(username='Username',password='Password',email='Mailbox',...)  # Create regular users
user1 = .create_superuser(username='alan',password='alan123',email='alan@')  
# Creating Super Users,We can log in to the administrator backend with a super username and password

check_password(password)

auth provides a method of checking whether a password is correct, requiring the password of the currently requesting user.
Returns True if the password is correct, False otherwise.

Usage:

ok = user.check_password('Password')  # Check if the password is correct, return a true or false

set_password(password)

auth provides a method to change a password, receiving the new password to be set as an argument.

Usage:

user.set_password(password='')  # Reset password
()  # Be sure to save the password change, otherwise the new password will not be created successfully, and the database will still contain the old password as an encrypted string.

Applications:

@login_required  # Perform login verification before setting password
def set_password(request):  # Wraps a function that sets a password
    user =   # Get the users
    err_msg = ''
    if  == 'POST':
        old_password = ('old_password', '')  # Get the old code
        new_password = ('new_password', '')  # Got a new password
        repeat_password = ('repeat_password', '')
        # Check old passwords for correctness
        if user.check_password(old_password):  # Verify that the old password is correct, and then determine whether the new password is empty and whether the two new password settings are consistent.
            if not new_password:
                err_msg = 'New password cannot be empty'
            elif new_password != repeat_password:
                err_msg = 'Two passwords don't match'
            else:
                user.set_password(new_password)  # This is the new password
                ()  # Be sure to save your new password after you set it
                return redirect("/login/")  # Save the completion of the redirection to the landing page, enter the new password to log in, log in successfully means that the new password is set successfully
        else:
            err_msg = 'Original password entry error'
    content = {
        'err_msg': err_msg,
    }  #
    return render(request, 'set_password.html', content)  # If the original password entry fails,then the failure message is rendered to the front-end page to tell the user that the original password was entered incorrectly

Properties of the User object

  • User object properties: username, password
  • is_staff : Whether the user has administrative privileges for the site.
  • is_active : whether to allow users to log in, set to False, you can prohibit users from logging in without deleting them.

Extending the default auth_user table

Define a Model class of your own by inheriting from the built-in AbstractUser class. This enables the creation of a new table to be associated with the built-in auth_user table on a one-to-one basis.

from  import AbstractUser


class UserInfo(AbstractUser):  # Inherit AbstractUser
    """
    User Information Sheet
    """
    nid = (primary_key=True)  # This is the equivalent of being able to derive new fields in your own class
    phone = (max_length=11, null=True, unique=True)

    def __str__(self):
        return   # output the string as is

After extending the built-in auth_user table as above, be sure to tell Django in that I am now using my newly defined UserInfo table for user authentication.

# Reference to Django comes with the User table, inheritance of the use of the need to set up, do not add the database can not be migrated
AUTH_USER_MODEL = "appname.UserInfo"

to this article on the use of Django auth module user authentication article is introduced to this, more related Django auth module user authentication content please search my previous posts or continue to browse the following related articles I hope you will support me in the future more!