Tastypie auto log out

。_饼干妹妹 提交于 2019-12-11 15:13:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!