17 Django advanced Auth

Posted by tomharding on Sun, 05 Dec 2021 02:47:51 +0100

1 what is the auth module

Auth module is Django's own user authentication module:

When we develop a website, we inevitably need to design and implement the user system of the website. At this time, we need to realize the functions including user registration, user login, user authentication, logout and password modification. This is really a troublesome thing.

As the ultimate framework of a perfectionist, Django will certainly think of these pain points of users. It has built-in powerful user authentication system - auth, which is used by default_ User table to store user data.

2. Common methods of auth module

from django.contrib import auth

authenticate()

It provides user authentication function, that is, to verify whether the user name and password are correct. Generally, two keyword parameters username and password are required.

If the authentication is successful (the User name and password are correct and valid), a User object is returned.

authenticate() will set a property on the User object to identify that the back end has authenticated the User, and this information is required in the subsequent login process.

Usage:

user = authenticate(username='usernamer',password='password')

login(HttpRequest, user)

This function accepts an HttpRequest object and an authenticated User object.

This function implements the function of user login. In essence, it will generate relevant session data for the user on the back end.

Usage:

from django.contrib.auth import authenticate, login
   
def my_view(request):
  username = request.POST['username']
  password = request.POST['password']
  user = authenticate(username=username, password=password)
  if user is not None:
    login(request, user)
    # 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 the currently requested session information will be cleared. Even if the user is not logged in, there will be no error when using this function.

Usage:

from django.contrib.auth import logout
   
def logout_view(request):
  logout(request)
  # Redirect to a success page.

is_authenticated()

Used to determine whether the current request has passed authentication.

Usage:

def my_view(request):
  if not request.user.is_authenticated():
    return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))

login_requierd()

auth provides us with a decorator tool to quickly add login verification to a view.

Usage:

from django.contrib.auth.decorators import login_required
      
@login_required
def my_view(request):
  ...

If the user does not log in, it will jump to django's default login url '/ accounts/login /' and pass the absolute path of the current url (after successful login, it will be redirected to this path).

If you need to customize the login URL, you need to use login in the settings.py file_ Modify the URL.

Example:

LOGIN_URL = '/login/'  # This is configured as the route of your project login page

create_user()

auth provides a method to create a new user. You need to provide the necessary parameters (username, password, etc.).

Usage:

from django.contrib.auth.models import User
user = User.objects.create_user(username='user name',password='password',email='mailbox',...)

create_superuser()

auth provides a method to create a new super user. You need to provide the necessary parameters (username, password, etc.).

Usage:

from django.contrib.auth.models import User
user = User.objects.create_superuser(username='user name',password='password',email='mailbox',...)

check_password(password)

auth provides a method to check whether the password is correct. You need to provide the password of the current requesting user.

If the password is correct, return True; otherwise, return False.

Usage:

ok = user.check_password('password')

set_password(password)

auth provides a method to modify the password, and receives the new password to be set as a parameter.

Note: after setting, you must call the save method of the user object!!!

Usage:

user.set_password(password='')
user.save()
@login_required
def set_password(request):
    user = request.user
    err_msg = ''
    if request.method == 'POST':
        old_password = request.POST.get('old_password', '')
        new_password = request.POST.get('new_password', '')
        repeat_password = request.POST.get('repeat_password', '')
        # Check whether the old password is correct
        if user.check_password(old_password):
            if not new_password:
                err_msg = 'New password cannot be empty'
            elif new_password != repeat_password:
                err_msg = 'The two passwords are inconsistent'
            else:
                user.set_password(new_password)
                user.save()
                return redirect("/login/")
        else:
            err_msg = 'Original password input error'
    content = {
        'err_msg': err_msg,
    }
    return render(request, 'set_password.html', content)

Properties of the User object

User object properties: username, password

is_staff: whether the user has the management authority of the website

is_active: whether to allow the user to log in. Set to False to prohibit the user from logging in without deleting the user.

3. Extend the default auth_user table

The built-in authentication system works so well, but auth_ The fields in the user table are fixed. I can't use them directly in the project!

For example, what if I want to add a field to store the user's mobile phone number?

Smart, you might want to create another table and use one-to-one and built-in auth_user table Association, which can meet the requirements, but is there a better implementation?

The answer is, of course.

We can define our own Model class by inheriting the built-in AbstractUser class.

In this way, we can not only design the user table flexibly according to the project requirements, but also use Django's powerful authentication system.

from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser):
    """
    User information table
    """
    nid = models.AutoField(primary_key=True)
    phone = models.CharField(max_length=11, null=True, unique=True)
    
    def __str__(self):
        return self.username

be careful:

The built-in auth is extended as above_ After the user table, be sure to tell Django in settings.py that I now use my newly defined UserInfo table for user authentication. It is written as follows:

# It refers to the User table provided by Django. It needs to be set when inheriting and using
AUTH_USER_MODEL = "app name.UserInfo"

Note again:

Once we specify the table used by the new authentication system, we need to re create the table in the database instead of using the original default auth_ The user table.