認證登錄 django.contrib.auth中提供了許多方法,這裏主要介紹其中的三個:
1 authenticate(**credentials) 提供了用戶認證,即驗證用戶名以及密碼是否正確
一般需要username password兩個關鍵字參數 如果認證信息有效,會返回一個 User 對象。authenticate()會在User 對象上設置一個屬性標識那種認證後端認證了該用戶,且該信息在後面的登錄過程中是需要的。當我們試圖登陸一個從數據庫中直接取出來不經過authenticate()的User對象會報錯的!!
user = authentica(username='someone',password='somepassword')
2 login(HttpRequest, user, backend=None)
該函數接受一個HttpRequest對象,以及一個認證了的User對象 此函數使用django的session框架給某個已認證的用戶附加上session id等信息。
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.
...
3 logout(request) 註銷用戶
from django.contrib.auth import logout
def logout_view(request):
logout(request)
# Redirect to a success page.
該函數接受一個HttpRequest對象,無返回值。 當調用該函數時,當前請求的session信息會全部清除 該用戶即使沒有登錄,使用該函數也不會報錯
只允許登錄的用戶訪問 如果希望:
1 用戶登陸後才能訪問某些頁面,
2 如果用戶沒有登錄就訪問該頁面的話直接跳到登錄頁面
3 用戶在跳轉的登陸界面中完成登陸後,自動訪問跳轉到之前訪問的地址
我們有幾個方法來實現:
1 糙活 檢測request.user.is_authenticated()
from django.conf import settings
from django.shortcuts import redirect
def my_view(request):
if not request.user.is_authenticated():
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
2 django中的login_required函數
django已經爲我們設計好了一個用於此種情況的裝飾器:login_requierd()
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
... 在運行my_view函數前需要進行登錄驗證。
1 若用戶沒有登錄,則會跳轉到django默認的 登錄URL '/accounts/login/ ' (這個值可以在settings文件中通過LOGIN_URL進行修改)。並傳遞 當前訪問url的絕對路徑 (登陸成功後,會重定向到該路徑)。
可以使用 login_url 參數來配置 登錄url 。
可以使用redirectfieldname參數配置 當前訪問url的絕對路徑 。
如果要使用django的默認登陸界面,則可以通過在urls.py中如此配置,這樣的話,如果未登錄,程序會默認跳轉到 “templates\registration\login.html”這個模板。
#urls.py
...
(r'^accounts/login/$', 'django.contrib.auth.views.login'),
2 如果用戶登陸了,則會進入正常的頁面
自定義認證:所謂的自定義認證的時候很常見,假如登錄的時候手機號以及郵箱也可以用來作爲登錄賬號,那麼我們應該怎麼做呢?下面一起來研究自定義認證吧
首先要了解這個ModelBackend類 導入
from django.contrib.auth.backends import ModelBackend
自定義一個類去繼承ModelBackend類,重寫authenticate方法,
from django.contrib.auth.backends import ModelBackend
from .models import UserProfile
from django.db.models import Q
class CustomBackend(ModelBackend):
def authenticate(self, username=None, password=None, **kwargs):
try:
user = UserProfile.objects.get(Q(username=username) | Q(email=username))
if user.check_password(password):
return user
except Exception as e:
print e
return None
這裏用到一個Q類,作爲登錄用戶名並集使用,讓email或者username都可以作爲登錄名。因爲密碼是密文顯示的,我們得到的無法匹配,不過有check_password方法來判斷,如果匹配,返回user對象,否則爲None,
記住 這地方一定要在setting.py去配置
AUTHENTICATION_BACKENDS = (
'users.views.CustomBackend',
)