首先我們先看這個(gè)login函數(shù)的代碼:
def login(request, user, backend=None):
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""
session_auth_hash = ''
if user is None:
user = request.user
if hasattr(user, 'get_session_auth_hash'):
session_auth_hash = user.get_session_auth_hash()
if SESSION_KEY in request.session:
if _get_user_session_key(request) != user.pk or (
session_auth_hash and
not constant_time_compare(request.session.get(HASH_SESSION_KEY, ''), session_auth_hash)):
# To avoid reusing another user's session, create a new, empty
# session if the existing session corresponds to a different
# authenticated user.
request.session.flush()
else:
request.session.cycle_key()
try:
backend = backend or user.backend
except AttributeError:
backends = _get_backends(return_tuples=True)
if len(backends) == 1:
_, backend = backends[0]
else:
raise ValueError(
'You have multiple authentication backends configured and '
'therefore must provide the `backend` argument or set the '
'`backend` attribute on the user.'
)
request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
request.session[BACKEND_SESSION_KEY] = backend
request.session[HASH_SESSION_KEY] = session_auth_hash
if hasattr(request, 'user'):
request.user = user
rotate_token(request)
user_logged_in.send(sender=user.__class__, request=request, user=user)
一部分一部分來看,第一部分:
1.校驗(yàn)用戶賬戶信息
這里user.get_session_auth_hash() 獲取用戶加密后的信息的hash值,這里指的是session_id,獲取這個(gè)有什么用呢,就是之后將客戶端發(fā)送的HASH_SESSION_KEY作對比,
對比函數(shù):constant_time_compare()
這個(gè)函數(shù)只是對比散列值長度,速度還是可以接受,
具體的對比及加鹽過程可以點(diǎn)開源碼看一下,很清晰。
2.校驗(yàn)玩用戶數(shù)據(jù)之后進(jìn)行session寫入動(dòng)作,設(shè)置一系列的session值。
3.緊接著,更新token,rotate_token()函數(shù)進(jìn)行更新,
4.更新完之后進(jìn)行了一個(gè)信號操作,這里的信號操作類似hook(鉤子),這里不詳細(xì)解釋,下一篇寫一個(gè)hook的python實(shí)現(xiàn),及原理分析。django里面用了dispatcher來實(shí)現(xiàn)解耦,當(dāng)一些動(dòng)作發(fā)生的時(shí)候,信號允許特定的發(fā)送者去提醒一些接受者。
當(dāng)所有的動(dòng)作做完之后,就是完成了登錄的主要功能,這些功能自己手動(dòng)也能實(shí)現(xiàn),但是框架寫的還是比較完善,推薦使用框架自帶功能。