From 28f43fb2c0d723d6ef408ef4fd84f4e53b93902c Mon Sep 17 00:00:00 2001 From: lebaudantoine Date: Wed, 7 Aug 2024 16:25:54 +0200 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F(backend)=20refactor=20LiveKi?= =?UTF-8?q?t=20access=20token=20handling?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Switched to using query parameters instead of GET requests, enabling the inclusion of additional parameters when calling the create endpoint via POST. Simplified the access token generation process by removing redundant calls to `with_identity` and consolidating token generation steps. This streamlines the method flow by preparing all necessary data before generating the access token. --- src/backend/core/api/serializers.py | 2 +- src/backend/core/utils.py | 22 ++++++++++++---------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/src/backend/core/api/serializers.py b/src/backend/core/api/serializers.py index 394df68c..a1af11a2 100644 --- a/src/backend/core/api/serializers.py +++ b/src/backend/core/api/serializers.py @@ -123,7 +123,7 @@ class RoomSerializer(serializers.ModelSerializer): if role is not None or instance.is_public: slug = f"{instance.id!s}".replace("-", "") - username = request.GET.get("username", None) + username = request.query_params.get("username", None) output["livekit"] = { "url": settings.LIVEKIT_CONFIGURATION["url"], diff --git a/src/backend/core/utils.py b/src/backend/core/utils.py index 9b18c792..514d5bc7 100644 --- a/src/backend/core/utils.py +++ b/src/backend/core/utils.py @@ -11,7 +11,7 @@ from livekit.api import AccessToken, VideoGrants def generate_token(room: str, user, username: Optional[str] = None) -> str: - """Generate a Livekit access token for a user in a specific room. + """Generate a LiveKit access token for a user in a specific room. Args: room (str): The name of the room. @@ -22,7 +22,6 @@ def generate_token(room: str, user, username: Optional[str] = None) -> str: Returns: str: The LiveKit JWT access token. """ - video_grants = VideoGrants( room=room, room_join=True, @@ -35,18 +34,21 @@ def generate_token(room: str, user, username: Optional[str] = None) -> str: ], ) - token = AccessToken( - api_key=settings.LIVEKIT_CONFIGURATION["api_key"], - api_secret=settings.LIVEKIT_CONFIGURATION["api_secret"], - ).with_grants(video_grants) - if user.is_anonymous: - token.with_identity(str(uuid4())) + identity = str(uuid4()) default_username = "Anonymous" else: - token.with_identity(user.sub) + identity = str(user.sub) default_username = str(user) - token.with_name(username or default_username) + token = ( + AccessToken( + api_key=settings.LIVEKIT_CONFIGURATION["api_key"], + api_secret=settings.LIVEKIT_CONFIGURATION["api_secret"], + ) + .with_grants(video_grants) + .with_identity(identity) + .with_name(username or default_username) + ) return token.to_jwt()