Django 用戶認證系統使用總結

Django用戶認證系統使用總結html

by:授客 QQ1033553122python

 

測試環境web

Win7算法

Django 1.11數據庫

 

 

 

 

使用Django認證系統django

本文按默認配置講解Django認證系統的用法。若是默認的認證沒法知足項目,Django提供了對認證系統的擴展與定製。後端

Django身份驗證同時提供身份驗證和受權,一般稱爲身份驗證系統,由於這些特性有些耦合。api

 

用戶對象session

默認user對象主要屬性:app

  • username
  • password
  • email
  • first_name
  • last_name

 

建立用戶對象

>>>fromdjango.contrib.auth.modelsimportUser
>>>user=User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
 
#如上,此時用戶對象已經被保存到數據庫了,能夠對它的屬性進行修改
>>>user.last_name='Lennon'
>>>user.save()

若是已經安裝了Django admin應用,能夠直接建立用戶

建立超級用戶

使用createsuperuser 命令:

$ python manage.py createsuperuser --username=joe --email=joe@example.com

回車後,會提示輸入密碼,輸入密碼後回車,當即建立用戶。若是命令行省略了--username 或--email 選項,則回車後還會提示輸入這些選項的值。

 

修改密碼

Django採用hash算法存儲用戶密碼(參考documentation of how passwords are managed

經過命令行修改用戶密碼:

manage.py changepassword user_name

若是不提供user_name,則默認修改當前系統用戶的密碼.

 

經過api修改用戶密碼

>>>fromdjango.contrib.auth.modelsimportUser
>>>u=User.objects.get(username='john')
>>>u.set_password('new password')
>>>u.save()

注:這裏new password爲明文

若是已經安裝了Django admin應用,也能夠在認證系統管理頁面修改用戶密碼 

修改密碼,將註銷對應用戶的全部會話。

 

用戶認證

authenticate(request=None**credentials)

使用authenticate()來確認一系列認證。函數攜帶了credentials關鍵詞參數,默認狀況爲usernamepassword。若是認證經過,則返回對應的User對象,不然返回None:

fromdjango.contrib.authimportauthenticate

 

user=authenticate(username='john', password='secret')

ifuserisnotNone:

# A backend authenticated the credentials

else:
# No backend authenticated the credentials

 

 

除username,password參數以外,咱們還能夠添加其它條件:

例子,驗證用戶帳號密碼是否正確,同時要求被驗證用戶未被刪除(is_delete=1),也就是說,驗證用戶帳號密碼前獲取的用戶數據時,自動已經被刪除的用戶

user=authenticate(username='john', password='secret',is_delete=1)

 

固然,除了是否刪除,是否禁用等字段,其它字段通常不推薦這麼作,能夠在驗證用戶帳號密碼前進行其它前置條件的驗證

 

注意:默認的,django會優先驗證咱們顯示提供的參數,最後再驗證is_active是否未1,若是爲1,則返回None

 

權限和認證(Permissions and Authorization)

Web請求中的認證

Django爲每一個請求提供了 request.user屬性,該屬性表明當前用戶。若是當前用戶未登陸,則該屬性值將被設置爲一個匿名用戶AnonymousUser,不然將設置爲User的一個實例。

ifrequest.user.is_authenticated:# 已登陸
# Do something for authenticated users.
...
else:# 未登陸
# Do something for anonymous users.
...

 

登陸

login(requestuserbackend=None)[source]

login函數會保存用戶id到session.

注意:用戶登陸後,會話中依舊保留登陸前的的任何匿名會話數據。

fromdjango.contrib.authimportauthenticate, login
defmy_view(request):
username=request.POST['username']
password=request.POST['password']
 
# 驗證用戶名和密碼,返回用戶對象
user=authenticate(request, username=username, password=password)
ifuserisnotNone:
login(request, user)
# do something 好比重定向到一個成功頁面.
...
else:
# do something,好比返回一個登陸錯誤消息
...
 

選擇認證後端(backend)

略.

 

退出

logout(request)

 

例子:

fromdjango.contrib.authimportlogout
 
deflogout_view(request):
logout(request)
# do something 好比重定向到一個成功頁面.

注意:若是用戶未登陸,執行logout函數並不會拋出任何異常。

調用logout函數,會清空當前請求的全部會話數據,移除全部已存在數據。

 

對登陸用戶的訪問限制

原始方式

簡單,原始的方式就是檢查request.user.is_authenticated判斷是否定證:

fromdjango.confimportsettings
fromdjango.shortcutsimportredirect
 
defmy_view(request):
ifnotrequest.user.is_authenticated:
returnredirect('%s?next=%s'% (settings.LOGIN_URL, request.path))
# ...

或者:

fromdjango.shortcutsimportrender
 
defmy_view(request):
ifnotrequest.user.is_authenticated:
returnrender(request, 'myapp/login_error.html')
# ...
 

login_required裝飾器

login_required(redirect_field_name='next'login_url=None)

做爲快捷方式,可使用login_required():

fromdjango.contrib.auth.decoratorsimportlogin_required
 
@login_required
defmy_view(request):
...

login_required() 作如下事情:

  • 若是用戶未登陸,重定向到settings.LOGIN_URL變量指定的url,並把當前請求的絕對URL賦值給查詢字符串。例: /accounts/login/?next=/polls/3/.
  • 若是用戶已登陸,正常執行視圖。

默認的,查詢字符串參數名稱爲「next」,若是想用其它名稱,須要使用loging_required的可選參數redirect_field_name,舉例以下

fromdjango.contrib.auth.decoratorsimportlogin_required
 
@login_required(redirect_field_name='my_redirect_field')
defmy_view(request):
...

對應的,html模板中也要使用對應參數名稱。

 

login_required()還攜帶了可選參數 login_url。例:

fromdjango.contrib.auth.decoratorsimportlogin_required
 
@login_required(login_url='/accounts/login/')
defmy_view(request):
...

注意,若是不指定login_url參數,則須要配置settings.LOGIN_URL.

更多詳情,參考官方文檔。

 

一些常見的裝飾器

@require_POST # 設置視圖的http訪問方法必須爲POST

@require_GET  # 設置視圖的http訪問方法必須爲GET

 

例子:設置視圖的訪問方法必須爲POST

from django.views.decorators.http import require_POST,require_GET

 

@require_POST
def test_page(request):
return render(request, 'website/pages/mytest.html',{})

 

訪問效果

 

 

 

The LoginRequired mixin

 

Limiting access to logged-in users that pass a test

 

The permission_required decorator

 

The PermissionRequiredMixin mixin

 

Redirecting unauthorized requests in class-based views

Session invalidation on password change

Authentication Views

Using the views

All authentication views

Helper functions

Built-in forms

 

模板中的認證數據

當使用RequestContext,而且開啓了'django.contrib.auth.context_processors.auth'上下文處理器時(可在settings.py中配置),當前已登陸用戶和他們的權限都被存儲爲變量,存放在模板上下文中

Users

例子:

{%ifuser.is_authenticated%}
<p>Welcome, {{user.username}}. Thanks for logging in.</p>{%else%}
<p>Welcome, new user. Please log in.</p>{%endif%}

若是未使用RequestContext,則模板變量不可獲取,好比上述的 {{ user }}

 

Permissions

Managing users in the admin

 

 

參考連接

https://docs.djangoproject.com/en/2.1/topics/auth/

相關文章
相關標籤/搜索