认证

from rest_framework.authentication import BaseAuthentication #认证配置
from rest_framework.exceptions import AuthenticationFailed #抛异常
from course.models import Account
from django.utils.timezone import now #用django 自带的时间模块


class MyAuth(BaseAuthentication):
def authenticate(self,request):
if request.method == "OPTIONS":
return None
# 拿到前端带过来的token
token=request.META.get('HTTP_AUTHENTICATE','')
#判断是否有token
if not token:
raise AuthenticationFailed({'code':1020,'error':'没有携带token'})
user_obj=Account.objects.filter(token=token).first()
if not user_obj:
raise AuthenticationFailed({'code':1021, 'error': 'token不合法'})
# 判断token是否过期
old_time=user_obj.create_token_time
new_time=now()#实例化时间
if (new_time-old_time).days>7:
raise AuthenticationFailed({'code': 1022, 'error': 'token过期请重新登录'})
return (user_obj,token)

猜你喜欢

转载自www.cnblogs.com/xdlzs/p/10017110.html