Skip to content

Commit

Permalink
Merge branch 'main' into frontend/Kian
Browse files Browse the repository at this point in the history
  • Loading branch information
Kariyu42 committed Oct 28, 2024
2 parents afc8002 + 1966266 commit bb14597
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 38 deletions.
16 changes: 2 additions & 14 deletions backend/api/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,7 @@ async def connect(self):
await self.close()
return

try:
self.user = await sync_to_async(User.objects.get)(userID=userID)
except User.DoesNotExist:
logger.info(f"[{self.__class__.__name__}] User {userID} not found")
await self.close()
return

self.user = await sync_to_async(User.objects.get)(userID=userID)
self.user_group_name = f"status_{self.user.userID}"

await self.channel_layer.group_add(
Expand Down Expand Up @@ -198,13 +192,7 @@ async def connect(self):
await self.close()
return

try:
self.user = await sync_to_async(User.objects.get)(userID=userID)
except User.DoesNotExist:
logger.info(f"[{self.__class__.__name__}] User {userID} not found")
await self.close()
return

self.user = await sync_to_async(User.objects.get)(userID=userID)
self.user_group_name = f"chat_{self.user.userID}"

await self.channel_layer.group_add(
Expand Down
53 changes: 29 additions & 24 deletions backend/api/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
import random
import resend
import os
import httpx
import logging
import ssl
import certifi
import jwt

from plivo import RestClient
from asgiref.sync import sync_to_async

from django.conf import settings

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -132,26 +133,30 @@ def get_safe_profile(data: dict, me: bool, many: bool = False):
return safe_data

async def get_user_id_from_token(token):
try:
url = "https://localhost:8443/api/v1/users/@me/profile"
headers = {
"Authorization": f"Bearer {token}"
}

# Create a custom SSL context that doesn't verify certificates
ssl_context = ssl.create_default_context(cafile=certifi.where())
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

async with httpx.AsyncClient(verify=ssl_context) as client:
response = await client.get(url, headers=headers)

if response.status_code != 200:
raise Exception(f"Exited with bad status_code: {response.status_code} {response.reason}")
from .models import User # Avoid premature loading
from .serializers import UserSerializer

user_data = response.json()
return user_data["userID"]

except Exception as err:
logger.error(f"User from token failed: {err}")
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
user_id = payload.get('user_id')

if not user_id:
logger.warning(f"[UserIDFromToken] {token}: Token payload missing user_id")
return None

user = await sync_to_async(User.objects.get)(id=user_id)
if not user:
logger.warning(f"[UserIDFromToken] {token}: User not found")
return None

user_serializer = UserSerializer(user).data
return user_serializer['userID']
except jwt.ExpiredSignatureError:
logger.warning(f"[UserIDFromToken] {token}: Expired token")
return None
except jwt.InvalidTokenError:
logger.warning(f"[UserIDFromToken] {token}: Invalid token")
return None
except Exception as e:
logger.error(f"[UserIDFromToken] {token}: {e}")
return None

0 comments on commit bb14597

Please sign in to comment.