使用django 的cache設定token的有效期

Bound_w發表於2018-12-14

  

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("認證超時!")

 

相關文章