lf 前后端分离 (1) auth,token认证
一.关于登录验证
用户在登录的时候会通过验证以及滑动解锁,注意的是需要后端if verify(request.data):
来判断是否发送了那三个验证数据
通过
random_str=str(uuid.uuid4())
Token.objects.update_or_create(user=user_obj, defaults={"key":random_str, "created": datetime.datetime.now()}, )
在token表中创建关联用户,在前端通过cookie来验证,当登录成功后,会带着token回到服务器
1 import uuid 2 import datetime 3 4 from rest_framework.views import APIView 5 from rest_framework.response import Response 6 7 from app01.models import * 8 9 from django.contrib import auth 10 from app01.jiyan.captcha_verify import verify 11 12 class LoginView(APIView): 13 14 def post(self,request): 15 print(request.data) 16 17 # 1 获取数据 18 user = request.data.get("username") 19 pwd = request.data.get("password") 20 user_obj = auth.authenticate(username=user, password=pwd) 21 22 res = {"error_no":0, "user": None, "msg": None} 23 if verify(request.data): 24 if user_obj: 25 random_str=str(uuid.uuid4()) 26 Token.objects.update_or_create(user=user_obj, defaults={"key":random_str, "created": datetime.datetime.now()}, ) 27 # 基于auth表的对象 28 res["username"] = user_obj.username 29 res["access_token"] = random_str 30 31 else: 32 res["msg"] = "用户名或者密码错误!" 33 else: 34 res["msg"] = "验证码错误!" 35 print("res", res) 36 return Response(res)
关于在后端接收验证token
在用户在前端发送数据,后端会进行
token = request.META.get("HTTP_AUTHORIZATION")
接收数据,并在token数据库中查找,
存在,会记录登录时间以及有效期,并存储redis缓存中,
在下次登录直接校验缓存即可直接登录
1 from rest_framework.authentication import BaseAuthentication 2 from rest_framework.exceptions import AuthenticationFailed 3 from app01.models import Token 4 import datetime 5 from django.core.cache import cache 6 import pytz 7 8 9 class LoginAuth(BaseAuthentication): 10 def authenticate(self, request): 11 if request.method == "OPTIONS": 12 return None 13 14 token = request.META.get("HTTP_AUTHORIZATION") 15 print("token", token) 16 # 1.缓存检查 17 # 这里的user 是放在redis 里面的user对象 18 user = cache.get(token) 19 if user: 20 return user, token 21 # 2.数据库校验 22 token_obj = Token.objects.filter(key=token).first() 23 if not token_obj: 24 raise AuthenticationFailed("认证失败!") 25 print(token_obj.created) 26 now = datetime.datetime.now() 27 28 now = now.replace(tzinfo=pytz.timezone('UTC')) 29 print(now) 30 delta = now - token_obj.created 31 print(delta) 32 state = delta < datetime.timedelta(weeks=2) 33 if state: 34 delta = datetime.timedelta(weeks=2)-delta 35 print(delta) 36 # 返回关联的token值,以及用户对象 37 cache.set(token_obj.key, token_obj.user, min(delta.total_seconds(), 3600*24*7)) 38 return token_obj.user, token_obj.key 39 else: 40 raise AuthenticationFailed("认证超时!")