Django系列(2)-設置token失效時間

PS: 本篇中的token,指的是rest_framework的token。

新建token.py,比較token時間戳

import datetime
from rest_framework.authentication import TokenAuthentication, get_authorization_header
from rest_framework.exceptions import AuthenticationFailed

from main.base_settings import AUTH_TOKEN_AGE
from utils.time_util import TimeUtil


class ExpiringTokenAuthentication(TokenAuthentication):
    def authenticate_credentials(self, key):
        model = self.get_model()
        try:
            token = model.objects.select_related('user').get(key=key)
        except model.DoesNotExist:
            raise AuthenticationFailed(_('Invalid token.'))
        if not token.user.is_active:
            raise AuthenticationFailed(_('User inactive or deleted.'))

        now = int(TimeUtil.string2time_stamp(str(datetime.datetime.now())))
        token_created = int(TimeUtil.string2time_stamp(str(token.created)))
        # 滿足條件的話,就表示token已失效,提示用戶重新登錄刷新token.
        if now - token_created > AUTH_TOKEN_AGE:
            raise AuthenticationFailed('Token has expired')

        return token.user, token

其中,TimeUtil代碼如下:

class TimeUtil:
    @staticmethod
    def string2time_stamp(str_value):

        try:
            d = datetime.datetime.strptime(str_value, "%Y-%m-%d %H:%M:%S.%f")
            t = d.timetuple()
            time_stamp = int(time.mktime(t))
            time_stamp = float(str(time_stamp) + str("%06d" % d.microsecond)) / 1000000
            return time_stamp
        except ValueError as e:
            print(e)
            d = datetime.datetime.strptime(str_value, "%Y-%m-%d %H:%M:%S")
            t = d.timetuple()
            time_stamp = int(time.mktime(t))
            time_stamp = float(str(time_stamp) + str("%06d" % d.microsecond)) / 1000000
            return time_stamp

配置setting.py

# token失效時間,設置爲1天,開發可自行配置
AUTH_TOKEN_AGE = 60 * 60 * 24

# 此處的ExpiringTokenAuthentication需要寫明你自己的路徑!
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'yourapp_path.ExpiringTokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
    ......
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章