from app.middleware.current_user.data import set_current_user
from rest_framework.authentication import TokenAuthentication
from rest_framework import exceptions
from datetime import datetime, timedelta
from django.conf import settings


class AppTokenAuthentication(TokenAuthentication):
    keyword = 'Bearer'
    
    def authenticate_credentials(self, key):

        user, token = super(AppTokenAuthentication,
                            self).authenticate_credentials(key)
        
        if token.created < datetime.now() - timedelta(minutes=int(settings.SESSION_TIMEOUT)):
            token.delete()
            raise exceptions.AuthenticationFailed('Token has expired')
        else:
            token.created = datetime.now()
            token.save()

        set_current_user(user)

        return (user, token)
