问题
I am creating API based on Django 1.4.3 with Tastypie. I use ApiKey to authenticate users. As default ApiKey cannot be expired. But there is column created
with datetime in apikey table. Even when I change it to 2010
year, the key is still valid.
My question is how can I make the column created
useful and forbid access for keys older than let say 24 hours, in easiest way and does it make sense?
At the moment I have no idea how I could even try to achieve that.
I don't expect ready solution. Some useful hints.
回答1:
I found solution by overriding method get_key
in ApiKeyAuthentication.
class MyApiKeyAuthentication(ApiKeyAuthentication):
def get_key(self, user, api_key):
"""
Attempts to find the API key for the user. Uses ``ApiKey`` by default
but can be overridden.
"""
from tastypie.models import ApiKey
try:
api_key = ApiKey.objects.get(user=user, key=api_key)
current_time = datetime.utcnow()
current_time = current_time.replace(tzinfo=pytz.utc)
week = timedelta(7)
if not (current_time - api_key.created) < week:
api_key.delete()
return self._unauthorized()
else:
api_key.created = current_time
api_key.save()
except ApiKey.DoesNotExist:
return self._unauthorized()
return True
来源:https://stackoverflow.com/questions/17092212/tastypie-auto-log-out