From 9889b7ac0803786702e3bcd6ddeaaf72fcf451eb Mon Sep 17 00:00:00 2001
From: Chris Li <c58li@uwaterloo.ca>
Date: Sat, 11 Feb 2023 01:15:17 -0500
Subject: [PATCH] Add token validation.

---
 core/api/auth.py | 16 +++++++++++++++-
 core/urls.py     |  3 ++-
 2 files changed, 17 insertions(+), 2 deletions(-)

diff --git a/core/api/auth.py b/core/api/auth.py
index 56120f1..16e7915 100644
--- a/core/api/auth.py
+++ b/core/api/auth.py
@@ -1,6 +1,8 @@
 from django.shortcuts import render
-from rest_framework import generics
+from rest_framework import generics, HTTP_HEADER_ENCODING
+from rest_framework.decorators import api_view, authentication_classes
 from rest_framework.response import Response
+from knox.auth import TokenAuthentication
 from knox.models import AuthToken
 from django.contrib.auth.backends import AllowAllUsersModelBackend
 
@@ -39,6 +41,18 @@ class LoginAPI(generics.GenericAPIView):
         })
 
 
+@api_view(['GET'])
+@authentication_classes([])
+def validate_token(request):
+    try:
+        authenticator = TokenAuthentication()
+        user, auth_token = authenticator.authenticate(request)
+        if user and auth_token:
+            return Response({'valid': 'true'})
+    except:
+        return Response({'valid': 'false'})
+
+
 def verify_user_and_activate(request, token):
     try:
         auth = AuthToken.objects.filter(digest=token).first()
diff --git a/core/urls.py b/core/urls.py
index 6258c45..b8b37e9 100644
--- a/core/urls.py
+++ b/core/urls.py
@@ -2,7 +2,7 @@ from django.urls import path, include
 from knox import views as knox_views
 from rest_framework import routers
 
-from core.api.auth import RegisterAPI, LoginAPI, verify_user_and_activate
+from core.api.auth import RegisterAPI, LoginAPI, validate_token, verify_user_and_activate
 from core.api.password import ChangePasswordView
 from core.api.profile import ProfileViewSet
 
@@ -16,6 +16,7 @@ urlpatterns += [
     path('api/auth/activate/<token>', verify_user_and_activate, name='activate'),
     path('api/auth/login', LoginAPI.as_view(), name='login'),
     path('api/auth/logout', knox_views.LogoutView.as_view(), name='logout'),
+    path('api/auth/validate-token', validate_token, name='validate-token'),
     # passwd
     path('api/change-password', ChangePasswordView.as_view(), name='change-password'),
     path('api/password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')),
-- 
GitLab