Question

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.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top