from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed from api.models import Token import datetime from django.core.cache import cache import pytz class LoginAuth(BaseAuthentication): def authenticate(self, request): ''' 1 對token設置14天有效時間 2 緩存存儲 :param request: :return: ''' # print(request.META.get("HTTP_AUTHORIZATION")) token=request.META.get("HTTP_AUTHORIZATION") # 1 校驗是否存在token字符串 # 1.1 緩存校驗 user=cache.get(token) if user: print("緩存校驗成功") return user,token # 1.2 數據庫校驗 token_obj = Token.objects.filter(key=token).first() if not token_obj: raise AuthenticationFailed("認證失敗!") # 2 校驗是否在有效期內 print(token_obj.created) # 2018-1-1- 0 0 0 now=datetime.datetime.now() # 2018-1-12- 0 0 0 now = now.replace(tzinfo=pytz.timezone('UTC')) print(now-token_obj.created) delta=now - token_obj.created state=delta < datetime.timedelta(weeks=2) print(state) if state: # 校驗成功,寫入緩存中 print("delta",delta) delta=datetime.timedelta(weeks=2)-delta print(delta.total_seconds()) cache.set(token_obj.key,token_obj.user,min(delta.total_seconds(),3600*24*7)) print("數據庫校驗成功") return token_obj.user,token_obj.key else: raise AuthenticationFailed("認證超時!")