django 的用户验证及登录状态保持

一、用户验证功能

  Django自带用户验证及登录功能,引入模块为:

from django.contrib.auth import authenticate

  其中方法authenticate()的接收参数为:

def authenticate(request=None, **credentials):

  传入参数:

user = authenticate(username=login_user, password=login_password)

  authenticate方法自动在数据库中匹配、验证,但是不能实现邮箱登录的验证,需要对该方法重写,导入模块:

from django.contrib.auth.backends import ModelBackend

  创建重写类:

class ChongxieAuthenticate(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
else:
return None
except Exception as e:
return None

  如果用户名或邮箱、密码验证通过,则会将该对象传递给user,如果为通过,传回None

二、登录状态保持

  Django自带的login()方法可实现用户登录状态的保持,引入模块:

from django.contrib.auth import login

  如果登录验证通过,使用:

login(request, user)

  使用该方法后,会在服务器端的session中生成_auth_user_id和_auth_user_backend两个键值,并发到客户端作为cookie,前端页面可通过{% if request.user.is_authenticated %}判断是否登录,来实现登录状态的保持功能。

 

posted @ 2018-06-01 20:48  问道编程  阅读(2430)  评论(0编辑  收藏  举报