Django自帶用戶認證系統,這個系統支持訪問控制、注冊用戶、關聯創建者和內容等;在開發用戶認證功能時的時候,可以使用django中的django.contrib.auth 中封裝了注冊、認證,登錄登出方法,可以直接使用;
相關表
在使用"python manage.py makemigrationss"和"python manage.py migrate"遷移完成數據庫之后
根據配置文件settings.py中的數據庫段生成的數據表中已經包含了6張進行認證的數據表,分別是
- auth_user
- auth_group
- auth_group_permissions
- auth_permission
- auth_user_groups
- auth_user_user_permissions
自帶用戶認證系統,進行用戶認證的數據表為auth_user(用戶的數據保存在這個表里)
一、登陸功能:
authenticate():提供了用戶認證,即驗證用戶名以及密碼是否正確,一般需要username和password兩個關鍵字參數
如果通過認證,authenticate()
函數會返回一個User對象。當我們試圖登陸一個從數據庫中直接取出來不經過authenticate()
的User對象時會報錯。
1.登陸 auth.authenticate(username=name值, password=password值)
2.驗證用戶名和密碼 auth.login(request, user) 這個函數使用Django的session框架給某個已認證的用戶附加上session_id信息。
from
django.shortcuts
import
render,redirect,HttpResponse
from
django.contrib.auth
import
authenticate,login
def
auth_view(request):
username
=
request.POST.GET(
"usernmae"
)
# 獲取用戶名
password
=
request.POST.GET(
"password"
)
# 獲取用戶的密碼
user
=
authenticate(username
=
username,password
=
password)
# 驗證用戶名和密碼,返回用戶對象
if
user:
# 如果用戶對象存在
login(request,user)
# 用戶登陸
return
redirect(
"/index/"
)
else
:
return
HttpResponse(
"用戶名或密碼錯誤"
)
當用戶登陸成功時,會生成一個sessionid保存在cookies中,可以在數據庫django_session中查看,當用戶訪問其他頁面時,可以通過sessionid判斷用戶是否已經登陸。


二、注冊功能
django自帶User模型,導入方法:from django.contrib.auth.models import User
User是auth模塊中維護用戶信息的關系模式,在數據庫中被命名為auth_user,使用migrate會自動生成.
user對象
User對象屬性:username,password為必填項
password用哈希算法保存到數據庫中
- is_staff:判斷用戶是否擁有網站的管理權限
- is_active:判斷是否允許用戶登陸,設置為“False”時可以不用刪除用戶來禁止用戶登陸
- 用create_user輔助函數創建用戶
a、create_user創建用戶
create_user是django封裝好的用於創建用戶的方法(注意使用該方法注冊的用戶才能處理密碼明文存密文到數據庫的問題),
創建方法:User.objects.create_user(username=name, password=password)此處的User是django中自帶的User模型from django.contrib.auth.models import User
def regist(request): name = request.POST.get('name') password = request.POST.get('password') User.objects.create_user(username=name, password=password)
三、退出登陸auth.logout(request)
這個函數接受一個HttpResponse對象,無返回值。當調用該函數時,當前請求的session信息全部被清除。即使當前用戶沒有登陸,調用該函數也不會報錯。
def logout(request): if request.method == 'GET': auth.logout(request)
四、登陸態驗證
login_required() 若在訪問某頁面時,需要確認用戶登陸成功才能訪問,可以在url中用login_required方法進行驗證,如果登陸成功就執行,如果用戶未登陸,自動跳轉登陸頁面。
a.login_requierd()
裝飾器
配置跳轉路徑,,當用戶未登陸訪問其他頁面時,自動跳轉到指定的url
url(r'^index/', login_required(views.index)), url(r'^addstu/', login_required(views.addStu), name='astu'), url(r'^stupage/', login_required(views.stuPage)),
值得注意的是,一旦加上login_required方法,在用戶未登陸時訪問頁面會出現如下的404錯誤,所需還需要在setting.py進行配置LOGIN_URL。
login_requierd()
裝飾器

配置跳轉路徑,當用戶未登陸訪問其他頁面時,自動跳轉到登陸頁面
LOGIN_URL = '/login/'
裝飾器也可以加到view方法前
from
django.contrib.auth.decorators
import
login_required
@login_required
def
views(request):
pass
五、修改存儲自定義認證中的User表
用戶也可以不使用自帶用戶認證系統默認的數據表auth_user,通過以下方式可以將用戶數據保存到自己定義的表中
from
django.contrib.auth.models
import
User
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE) # django自帶用戶表User模塊和自定義的用戶關聯
name = models.CharField(max_length=32)
def __str__(self):
return self.name
六、自定義用戶認證系統
Django 自帶的用戶認證系統已經可以滿足大部分的情況,但是有時候我們需要某些特定的需求。Django 支持使用其他認證系統、也可以擴展Django的User模塊,完全自定義新的認證模塊。
參考:https://docs.djangoproject.com/en/2.0/topics/auth/customizing/
a、拷貝以下代碼到model文件中:
from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser )
class MyUserManager(BaseUserManager):
def create_user(self, email, name, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
name=name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, name, password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
email,
password=password,
name=name,
)
user.is_admin = True
user.save(using=self._db)
return user
class UserProfile(AbstractBaseUser):
'''賬號表'''
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
name = models.CharField(max_length=32)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
注意:email, name等字段都是可以自定義的
b、在admin.py中添加如下代碼:
from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from customauth.models import MyUser class UserCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = MyUser fields = ('email', 'date_of_birth') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ password = ReadOnlyPasswordHashField() class Meta: model = MyUser fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial["password"] class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserChangeForm add_form = UserCreationForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('email', 'date_of_birth', 'is_admin') list_filter = ('is_admin',) fieldsets = ( (None,