Commit 75f7f42b authored by impfundev's avatar impfundev

feat: refresh jwt token 5 minutes before expired

parent ce37dda1
import jwt import jwt
from datetime import datetime from django.conf import settings
from datetime import datetime, timedelta
from django.utils.deprecation import MiddlewareMixin from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from librarians.models import Librarians import jwt.utils
from django.conf import settings
class AuthMiddleware(MiddlewareMixin): class AuthMiddleware(MiddlewareMixin):
...@@ -17,29 +16,34 @@ class AuthMiddleware(MiddlewareMixin): ...@@ -17,29 +16,34 @@ class AuthMiddleware(MiddlewareMixin):
auth_session = request.session.get("auth_session", None) auth_session = request.session.get("auth_session", None)
if request.path.startswith("/dashboard/"): if auth_session is not None:
if auth_session is not None: try:
decoded = jwt.decode( payload = jwt.decode(
auth_session, settings.JWT_SECRET, algorithms=["HS256"] auth_session, settings.JWT_SECRET, algorithms=["HS256"]
) )
user_verified = get_object_or_404(
Librarians, id=decoded["librarian_id"]
)
user_obj = { # refresh token 5 minutes before expired
"exp": decoded["exp"], expired_time = datetime.fromtimestamp(payload["exp"])
"id": user_verified.id, near_expired = expired_time - timedelta(minutes=5)
"name": user_verified.name,
"time": str(datetime.now()), if datetime.now() >= near_expired:
} payload["exp"] = (
message = "login request success, user: " + f"{user_obj}" payload["exp"] + timedelta(minutes=15).total_seconds()
print(message) )
new_token = jwt.encode(
payload, settings.JWT_SECRET, algorithm="HS256"
)
request.session["auth_session"] = new_token
return response return response
else:
except jwt.ExpiredSignatureError:
del request.session["auth_session"]
return HttpResponseRedirect("/auth/login") return HttpResponseRedirect("/auth/login")
if auth_session is not None and request.path.startswith("/auth/"): if auth_session is None and request.path.startswith("/dashboard/"):
return HttpResponseRedirect("/auth/login")
elif auth_session is not None and request.path.startswith("/auth/"):
return HttpResponseRedirect("/dashboard/") return HttpResponseRedirect("/dashboard/")
else: else:
return response return response
...@@ -25,7 +25,7 @@ class AuthView(TemplateView): ...@@ -25,7 +25,7 @@ class AuthView(TemplateView):
password=form.data["password"], password=form.data["password"],
) )
expiration_time = datetime.now() + timedelta(minutes=30) expiration_time = datetime.now() + timedelta(minutes=15)
payload = { payload = {
"exp": expiration_time.timestamp(), "exp": expiration_time.timestamp(),
"librarian_id": librarian.id, "librarian_id": librarian.id,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment