Skip to content

Commit

Permalink
Merge pull request #3 from OpenRnD007/patch-1
Browse files Browse the repository at this point in the history
datetime utcnow is deprecated from 3.2 so updating jwt.py
  • Loading branch information
sabuhibrahim authored Jul 8, 2024
2 parents 76ee5e6 + e72cd75 commit 741852c
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/core/jwt.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import uuid
import sys
from datetime import timedelta, datetime, timezone

from jose import jwt, JWTError
from fastapi import Response
from sqlalchemy.ext.asyncio import AsyncSession
Expand All @@ -16,9 +18,17 @@
IAT = "iat"
JTI = "jti"

def _get_utc_now():
if sys.version_info >= (3, 2):
# For Python 3.2 and later
current_utc_time = datetime.now(timezone.utc)
else:
# For older versions of Python
current_utc_time = datetime.utcnow()
return current_utc_time

def _create_access_token(payload: dict, minutes: int | None = None) -> JwtTokenSchema:
expire = datetime.utcnow() + timedelta(
expire = _get_utc_now() + timedelta(
minutes=minutes or config.ACCESS_TOKEN_EXPIRES_MINUTES
)

Expand All @@ -34,7 +44,7 @@ def _create_access_token(payload: dict, minutes: int | None = None) -> JwtTokenS


def _create_refresh_token(payload: dict) -> JwtTokenSchema:
expire = datetime.utcnow() + timedelta(minutes=config.REFRESH_TOKEN_EXPIRES_MINUTES)
expire = _get_utc_now() + timedelta(minutes=config.REFRESH_TOKEN_EXPIRES_MINUTES)

payload[EXP] = expire

Expand All @@ -48,7 +58,7 @@ def _create_refresh_token(payload: dict) -> JwtTokenSchema:


def create_token_pair(user: User) -> TokenPair:
payload = {SUB: str(user.id), JTI: str(uuid.uuid4()), IAT: datetime.utcnow()}
payload = {SUB: str(user.id), JTI: str(uuid.uuid4()), IAT: _get_utc_now()}

return TokenPair(
access=_create_access_token(payload={**payload}),
Expand Down Expand Up @@ -80,12 +90,12 @@ def refresh_token_state(token: str):

def mail_token(user: User):
"""Return 2 hour lifetime access_token"""
payload = {SUB: str(user.id), JTI: str(uuid.uuid4()), IAT: datetime.utcnow()}
payload = {SUB: str(user.id), JTI: str(uuid.uuid4()), IAT: _get_utc_now()}
return _create_access_token(payload=payload, minutes=2 * 60).token


def add_refresh_token_cookie(response: Response, token: str):
exp = datetime.utcnow() + timedelta(minutes=config.REFRESH_TOKEN_EXPIRES_MINUTES)
exp = _get_utc_now() + timedelta(minutes=config.REFRESH_TOKEN_EXPIRES_MINUTES)
exp.replace(tzinfo=timezone.utc)

response.set_cookie(
Expand Down

0 comments on commit 741852c

Please sign in to comment.