Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion django_simple_login/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'simple_login.utils.authentication.TokenAuthentication',
'simple_login.utils.authentication.ExpiringTokenAuthentication',
)
}

Expand Down Expand Up @@ -147,3 +147,5 @@
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

TOKEN_EXPIRED_AFTER_DAYS = 30
43 changes: 41 additions & 2 deletions simple_login/utils/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,48 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

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