django版本 2.0.6
auth的login()
from django.contrib.auth import login 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. 在请求中获取用户的id和一个backend ,这个方法不需要在每个请求重新进行身份验证。 注意:当用户登陆期间将会保留匿名session """ session_auth_hash = '' if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): # 生成session的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. # 避免使用其他用户session,当一个token匹配到多个用户的session时创建一个全新的session # 刷新session request.session.flush() else: # # 创建一个新的session,并保留当前会话的信息 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 # 处于安全的目的,在用户登陆完成时更改csrf令牌 rotate_token(request) user_logged_in.send(sender=user.__class__, request=request, user=user)
_get_user_session_key() 从session中提取用户id
from django.contrib.auth import _get_user_session_key def _get_user_session_key(request): # This value in the session is always serialized to a string, so we need # to convert it back to Python whenever we access it. return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
constant_time_compare() 验证session token的合法性
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。