Added JWT generation on user login

This commit is contained in:
Marcin Armacki 2020-11-08 20:24:08 +01:00
parent 34c95cd216
commit 3394227619
4 changed files with 33 additions and 3 deletions

View File

@ -1,4 +1,7 @@
import jwt
import time
from django.contrib.auth import authenticate
from django.conf import settings
from django.contrib.auth.models import User
from prototype.filehandler.exceptions import UserAuthFailed
@ -20,8 +23,14 @@ def loginUser(login, password):
try:
user = authenticate(username = login, password = password)
if isinstance(user, User):
payload = {"iss": "NKADF",
"iat": int(time.time()),
"sub": user.id,
"exp": int(time.time()) + 86400}
jwt_token = jwt.encode(payload, settings.SECRET_KEY, algorithm = "HS256").decode("utf-8")
result = {"message": "User authenticated successfully",
"statusCode": 200}
"statusCode": 200,
"token": jwt_token}
else:
raise UserAuthFailed("Error: User authentication failed")
except UserAuthFailed as error:
@ -29,3 +38,14 @@ def loginUser(login, password):
"statusCode": 401}
finally:
return result
def decodeToken(token):
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorith = "HS256")
result = payload
return payload
except Exception as error:
result = {"message": str(error),
"statusCode": 500}
finally:
return result

View File

@ -9,7 +9,7 @@ from prototype.filehandler.models import Document, Forum
from prototype.filehandler.forms import DocumentForm
from prototype.filehandler.xmlParser import parseData
from prototype.filehandler.functions import addToDatabase, listDiscussionsFromFile, listParagraphsFromDiscussion, createLabels, listPostsFromDiscussion, updateLabelsByParagraphId
from prototype.filehandler.userModule import registerNewUser, loginUser
from prototype.filehandler.userModule import registerNewUser, loginUser, decodeToken
from prototype.filehandler.errorCodes import MethodNotAllowed
@ -89,3 +89,11 @@ def login(request):
return JsonResponse(result, status = result["statusCode"])
else:
return JsonResponse(MethodNotAllowed, status = MethodNotAllowed["statusCode"])
@csrf_exempt
def testToken(request):
if request.method == 'POST':
result = decodeToken(request.POST["token"])
return JsonResponse(result, status = 200)
else:
return JsonResponse(MethodNotAllowed, status = MethodNotAllowed["statusCode"])

View File

@ -27,7 +27,8 @@ urlpatterns = [
path('discussions/<int:id>', views.discussions),
path('visualize/<int:id>', views.visualize),
path('user/', views.user),
path('login/', views.login)
path('login/', views.login),
path('testToken/', views.testToken)
]
if settings.DEBUG:

View File

@ -1 +1,2 @@
Django~=3.0.5
pyjwt