Browse Source

[ADD] JWT custom authentication

Gogs 7 years ago
parent
commit
2f1dccbe9c
2 changed files with 61 additions and 3 deletions
  1. 33 2
      api/utils/jwt_authentication.py
  2. 28 1
      api/utils/jwt_token.py

+ 33 - 2
api/utils/jwt_authentication.py

@@ -1,14 +1,45 @@
 # -*- coding: utf-8 -*-
 from __future__ import unicode_literals
 from tastypie.authentication import Authentication
+from django.contrib.auth.models import User
+from .jwt_token import check_token, get_username
+import simplejson as json
 
 class JWTAuthentication(Authentication):
     '''
     '''
     def is_authenticated(self, request, **kwargs):
-        return True
+        # Check content type
+        if request.content_type != 'application/json':
+            return False
+
+        # Check body
+        if not request.body:
+            return False
+
+        body = json.loads(request.body)
+
+        # Check required parameters
+        if 'token' not in body:
+            return False
+
+        return check_token(body['token'])
 
     '''
     '''
     def get_identifier(self, request):
-        return request.user.username
+        # Check content type
+        if request.content_type != 'application/json':
+            return None
+
+        # Check body
+        if not request.body:
+            return None
+
+        body = json.loads(request.body)
+
+        # Check required parameters
+        if 'token' not in body:
+            return None
+
+        return get_username(body['token'])

+ 28 - 1
api/utils/jwt_token.py

@@ -28,7 +28,7 @@ def create_token(username, password):
 
 '''
 '''
-def check_token(token):
+def explode_token(token):
     # Check if exists jwt key
     if not settings.JWT_SECRET_KEY:
         return None
@@ -38,6 +38,33 @@ def check_token(token):
     # Check payload parameters
     if 'uid' not in payload or 'password' not in payload:
         return False
+    
+    return 
+
+'''
+'''
+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)
 
     user = User.objects.get(pk=payload['uid'])