我正在尝试创建一个过期令牌生成器。但是,当我例如使用generate_token
然后使用令牌时,get_token_value
我不断得到cryptography.fernet.InvalidToken
我猜这是两个函数中的编码问题,但我不太确定我缺少什么?
发电机
from datetime import datetime, timedelta
import cryptography
from cryptography.fernet import Fernet
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import force_bytes, force_text
class ExpiringTokenGenerator(object):
FERNET_KEY = Fernet.generate_key()
fernet = Fernet(FERNET_KEY)
DATE_FORMAT = '%Y-%m-%d %H-%M-%S'
EXPIRATION_DAYS = 1
def _get_time(self):
"""Returns a string with the current UTC time"""
return datetime.utcnow().strftime(self.DATE_FORMAT)
def _parse_time(self, d):
"""Parses a string produced by _get_time and returns a datetime object"""
return datetime.strptime(d, self.DATE_FORMAT)
def generate_token(self, text):
"""Generates an encrypted token"""
full_text = str(text) + '|' + self._get_time()
token = self.fernet.encrypt(bytes(full_text, 'utf-8'))
return token
def get_token_value(self, token):
"""Gets a value from an encrypted token.
Returns None if the token is invalid or has expired.
"""
try:
value = self.fernet.decrypt(bytes(token, 'utf-8'))
separator_pos = value.rfind('|')
text = value[: separator_pos]
token_time = self._parse_time(value[separator_pos + 1: ])
print(token_time)
if token_time + timedelta(self.EXPIRATION_DAYS) < datetime.utcnow():
return None
except cryptography.fernet.InvalidToken:
return None
return text
def is_valid_token(self, token):
return self.get_token_value(token) != None
invoice_activation_token = ExpiringTokenGenerator()