django authentication system

Authentication system

author module

from django.contrib import auth

authenticate()  

Account verification typically used for landing

usage

user = authenticate(username='theuser',password='thepassword')

login(HttpRequest, user) 

Realization landing features for user-generated session data

Log in and verified by example

from django.contrib.auth import authenticate, login
   
def my_view(request):
  username = request.POST['username']
  password = request.POST['password']
  user_obj = authenticate(username=username, password=password)
  if user_obj:
    login(request, user_obj)
    # Redirect to a success page.
    ...
  else:
    # Return an 'invalid login' error message.
    ...

Note: After using login (request, user_obj), request.user able to get the user object is currently logged on. Otherwise request.user get is an anonymous user object (AnonymousUser Object).

logout(request) 

This function takes a HttpRequest object, no return value.

When the function is called, the current request will clear all session information. Even if the user is not logged in, use this function also does not complain.

Usage: Use when logging off

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

is_authenticated()

Determine whether the current user is certified

usage:

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

login_requierd()

As a decorator, check whether the user login

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

If the user is not logged, it will jump to the django default login URL '/ accounts / login /' and pass the current url to access the absolute path (after a successful landing, will be redirected to the path).

If you want to customize the login URL, you need to be modified by LOGIN_URL in settings.py file.

Set landing route

= LOGIN_URL ' / the Login / '   # here configured to route the login page of your project

create_user()

Way to create a new user auth offer, it is necessary to provide the necessary parameters (username, password) and so on.

usage:

from django.contrib.auth.models import User
user = User.objects.create_user(username='用户名',password='密码',email='邮箱',...)

create_superuser()

Create a super user, you need to provide the necessary parameters (username, password) and so on.

usage:

from django.contrib.auth.models Import the User 
USER_OBJ = User.objects.create_superuser (username = ' username ' , password = ' password ' , Email = ' E-mail ' , ...)

check_password(raw_password)

The correct way to check whether a password auth offer, you need to provide the current request the user's password. The password is correct return True, otherwise False.

usage

user_obj.check_password = OK ( ' password ' )

Or direct the original password is correct for the user objects check current request:

ok = request.user.check_password(raw_password='原密码')

set_password(raw_password)

auth provides a method to modify the password, set to receive a new password as a parameter.

Note : After setting sure to call the save method for user objects! ! !

usage:

user_obj.set_password ( ' new password ' ) 
user_obj.save ()

Password change function example

@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 the old password is correct#)
        
        IF user.check_password (old_password):
             IF  not new_password: 
                ERR_MSG = ' The new password can not be empty ' 
            elif new_password =! repeat_password: 
                ERR_MSG = ' two passwords do not match ' 
            the else : 
                user.set_password (new_password) 
                user.save () 
                return redirect ( " / Login / " )
         the else : 
            ERR_MSG = ' old password input error ' 
    Content = {
        ' ERR_MSG ' : ERR_MSG, 
    } 
    return the render (Request, ' set_password.html ' , Content) 

modified password examples
View Code

The user object attributes

is_staff: whether the user has administrative rights website

is_active: set to false will not allow users to log in, prevents users from logging in without deletion.

Extend the default table auth_user

1. Design table

from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser):
    """
    用户信息表
    """
    nid = models.AutoField(primary_key=True)
    phone = models.CharField(max_length=11, null=True, unique=True)
    
    def __str__(self):
        return self.username

2. Enable Registration

# Cited Django comes with the User table, you need to set when inheritance using 
AUTH_USER_MODEL = " App name .UserInfo "

use:

Create a regular user

UserInfo.objects.create_user (username = ' username ' , password = ' password ' )

Creating a superuser

UserInfo.objects.create_superuser (username = ' username ' , password = ' password ' )

Note : Once we specify table new authentication system used, we need to re-create the table in the database, but can not continue to use the original default auth_user the table.

Guess you like

Origin www.cnblogs.com/huay/p/11799062.html