# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.utils.crypto import constant_time_compare import jwt ''' ''' def create_token(username, password): # Check if exists jwt key if not settings.JWT_SECRET_KEY: return None user = authenticate(username=username, password=password) # Check user authentication if not user: return user payload = { 'uid': user.id, 'password': user.password } return jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm='HS256') ''' ''' def explode_token(token): # Check if exists jwt key if not settings.JWT_SECRET_KEY: return None payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithm='HS256') # Check payload parameters if 'uid' not in payload or 'password' not in payload: return False return payload ''' ''' def get_user(token): payload = explode_token(token) user = User.objects.get(pk=payload['uid']) return user ''' ''' def get_username(token): user = get_user(token) # Check if exists user if not user: return user return user.name ''' ''' def check_token(token): payload = explode_token(token) print(payload) user = User.objects.get(pk=payload['uid']) # Check if exists user if not user: return False return constant_time_compare(user.password, payload['password'])