diff --git a/django_simple_login/settings.py b/django_simple_login/settings.py index 067018a..58be2bd 100644 --- a/django_simple_login/settings.py +++ b/django_simple_login/settings.py @@ -73,7 +73,7 @@ REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( - 'simple_login.utils.authentication.TokenAuthentication', + 'simple_login.utils.authentication.ExpiringTokenAuthentication', ) } @@ -147,3 +147,5 @@ 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', ] + +TOKEN_EXPIRED_AFTER_DAYS = 30 \ No newline at end of file diff --git a/simple_login/utils/authentication.py b/simple_login/utils/authentication.py index a0a6c6f..95db85c 100644 --- a/simple_login/utils/authentication.py +++ b/simple_login/utils/authentication.py @@ -18,9 +18,48 @@ # along with this program. If not, see . # -from rest_framework.authentication import TokenAuthentication as TokenAuth +from rest_framework.authentication import TokenAuthentication from simple_login.models.api import Tokens +from datetime import datetime, timedelta +from django.utils import timezone +from rest_framework import exceptions +from django.conf import settings +from rest_framework.exceptions import AuthenticationFailed -class TokenAuthentication(TokenAuth): + +def expires_in(token): + time_elapsed = timezone.now() - token.created + left_time = timedelta(days=settings.TOKEN_EXPIRED_AFTER_DAYS) - time_elapsed + return left_time + + +def is_token_expired(token): + return expires_in(token) < timedelta(seconds=0) + + +def token_expire_handler(token): + is_expired = is_token_expired(token) + if is_expired: + token.delete() + return is_expired, token + + +class ExpiringTokenAuthentication(TokenAuthentication): model = Tokens + + def authenticate_credentials(self, key): + + try: + token = self.model.objects.get(key=key) + except self.model.DoesNotExist: + raise exceptions.AuthenticationFailed('Invalid token') + + if not token.user.is_active: + raise exceptions.AuthenticationFailed('User inactive or deleted') + + is_expired, token = token_expire_handler(token) + if is_expired: + raise AuthenticationFailed("The Token is expired") + + return token.user, token