Django自定義用戶認(rèn)證示例詳解
前言
Django附帶的認(rèn)證對(duì)于大多數(shù)常見(jiàn)情況來(lái)說(shuō)已經(jīng)足夠了,但是如何在 Django 中使用自定義的數(shù)據(jù)表進(jìn)行用戶認(rèn)證,有一種較為笨蛋的辦法就是自定義好數(shù)據(jù)表后,使用OnetoOne來(lái)跟 Django 的表進(jìn)行關(guān)聯(lián),類似于這樣:
from django.contrib.auth.models import User class UserProfile(models.Model): """ 用戶賬號(hào)表 """ user = models.OneToOneField(User) name = models.CharField(max_length=32) def __str__(self): return self.name class Meta: verbose_name_plural = verbose_name = "用戶賬號(hào)" ordering = ['id']
這樣做雖然可以簡(jiǎn)單、快速的實(shí)現(xiàn),但是有一個(gè)問(wèn)題就是我們?cè)谧约旱谋碇袆?chuàng)建一個(gè)用戶就必須再跟 admin 中的一個(gè)用戶進(jìn)行關(guān)聯(lián),這簡(jiǎn)直是不可以忍受的。
admin代替默認(rèn)User model
寫(xiě)我們自定義的 models 類來(lái)創(chuàng)建用戶數(shù)據(jù)表來(lái)代替默認(rèn)的User model,而不與django admin的進(jìn)行關(guān)聯(lián),相關(guān)的官方文檔在這里
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class UserProfileManager(BaseUserManager):
def create_user(self, email, name, password=None):
"""
用戶創(chuàng)建,需要提供 email、name、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):
"""
超級(jí)用戶創(chuàng)建,需要提供 email、name、password
"""
user = self.create_user(
email,
password=password,
name=name,
)
user.is_admin = True
user.is_active = 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, verbose_name="用戶名稱")
phone = models.IntegerField("電話")
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserProfileManager()
USERNAME_FIELD = 'email' # 將email 作為登入用戶名
REQUIRED_FIELDS = ['name', 'phone']
def __str__(self):
return self.email
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
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
admin 配置
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 = models.UserProfile
fields = ('email', 'name')
def clean_password2(self):
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):
user = super(UserCreationForm, self).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 = models.UserProfile
fields = ('email', 'password', 'name', 'is_active', 'is_admin')
def clean_password(self):
return self.initial["password"]
class UserProfileAdmin(BaseUserAdmin):
form = UserChangeForm
add_form = UserCreationForm
list_display = ('email', 'name', 'is_admin', 'is_staff')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('name',)}),
('Permissions', {'fields': ('is_admin', 'is_active', 'roles', 'user_permissions', 'groups')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'name', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ('groups', 'user_permissions','roles')
2.Django允許您通過(guò)AUTH_USER_MODEL配置來(lái)引用自定義的model設(shè)置來(lái)覆蓋默認(rèn)User模型,這個(gè)配置的配置方法為在 settings 中加入:AUTH_USER_MODEL = "APP.model_class" ,例如本例中我們需要在 setting 中加入以下配置:
AUTH_USER_MODEL = "app1.UserProfile"
3.部署
python manage.py makemigrations python manage.py migrate
創(chuàng)建一個(gè)新用戶,此時(shí)我們就可以用這個(gè)用戶來(lái)登錄 admin 后臺(tái)了
python manage.py createsuperuser
效果如下:
自定義認(rèn)證
那如果我們需要使用我們自己的認(rèn)證系統(tǒng)呢,假如我們有一個(gè) login 頁(yè)面和一個(gè) home 頁(yè)面:
from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth import authenticate,login,logout
from app1 import models
from django.contrib.auth.decorators import login_required
def auth_required(auth_type):
# 認(rèn)證裝飾器
def wapper(func):
def inner(request, *args, **kwargs):
if auth_type == 'admin':
ck = request.COOKIES.get("login") # 獲取當(dāng)前登錄的用戶
if request.user.is_authenticated() and ck:
return func(request, *args, **kwargs)
else:
return redirect("/app1/login/")
return inner
return wapper
def login_auth(request):
# 認(rèn)證
if request.method == "GET":
return render(request, 'login.html')
elif request.method == "POST":
username = request.POST.get('username', None)
password = request.POST.get('password', None)
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
_next = request.GET.get("next",'/crm')
return redirect('_next')
else:
return redirect('/app1/login/')
else:
return redirect('/app1/login/')
else:
pass
def my_logout(request):
# 注銷
if request.method == 'GET':
logout(request)
return redirect('/app1/login/')
@login_required
def home(request):
# home page
path1, path2 = "Home", '主頁(yè)'
if request.method == "GET":
return render(request, 'home.html', locals())
elif request.method == "POST":
pass
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
Python中Yield的基本用法及Yield與return的區(qū)別解析
Python中有一個(gè)非常有用的語(yǔ)法叫做生成器,用到的關(guān)鍵字就是yield,這篇文章主要介紹了Python中Yield的基本用法及Yield與return的區(qū)別,需要的朋友可以參考下2022-10-10
關(guān)于Python字符編碼與二進(jìn)制不得不說(shuō)的一些事
這篇文章主要給大家介紹了關(guān)于Python字符編碼與二進(jìn)制不得不說(shuō)的一些事,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
python中復(fù)數(shù)的共軛復(fù)數(shù)知識(shí)點(diǎn)總結(jié)
在本篇內(nèi)容里小編給大家整理的是關(guān)于python中復(fù)數(shù)的共軛復(fù)數(shù)知識(shí)點(diǎn)總結(jié),有需要的朋友們可以學(xué)習(xí)下。2020-12-12
python 內(nèi)置庫(kù)wsgiref的使用(WSGI基礎(chǔ)入門(mén))
WSGI(web服務(wù)器網(wǎng)關(guān)接口)主要規(guī)定了服務(wù)器端和應(yīng)用程序之間的接口,即規(guī)定了請(qǐng)求的URL到后臺(tái)處理函數(shù)之間的映射該如何實(shí)現(xiàn)。wsgiref是一個(gè)幫助開(kāi)發(fā)者開(kāi)發(fā)測(cè)試的Python內(nèi)置庫(kù),程序員可以通過(guò)這個(gè)庫(kù)了解WSGI的基本運(yùn)行原理,但是不能把它用在生產(chǎn)環(huán)境上。2021-06-06

