From 2deef12d0574275e439e779329af47175e11abc7 Mon Sep 17 00:00:00 2001 From: lebaudantoine Date: Tue, 25 Jun 2024 18:55:52 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A7(backend)=20Add=20utility=20functio?= =?UTF-8?q?n=20to=20generate=20LiveKit=20access=20token?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Introduce a utility function to issue a basic LiveKit access token with the minimal required video grants for videoconferencing. /!\ This function is naive, and doesn’t handle properly all cases. It’s under construction. Testing was conducted using the LiveKit connection test tool https://livekit.io/connection-test, which allows users to input the address of their local LiveKit server and an access token. ** Upcoming improvements? ** - Unit tests should be added. - User display name should be their full name instead of their email address. - Anonymous users should be allowed to provide a full name when requesting access to the room. - Video grants should be adapted based on the room configuration and the user's role. These improvements will be addressed in future commits. Nevertheless, with this draft, we should be able to address various situations, including public rooms, permanent rooms, temporary rooms, logged-in users, and anonymous users. --- src/backend/core/utils.py | 47 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/backend/core/utils.py diff --git a/src/backend/core/utils.py b/src/backend/core/utils.py new file mode 100644 index 00000000..24921687 --- /dev/null +++ b/src/backend/core/utils.py @@ -0,0 +1,47 @@ +""" +Utils functions used in the core app +""" +import string +from uuid import uuid4 + +from django.conf import settings + +from livekit.api import AccessToken, VideoGrants + + +def generate_token(room: string, user) -> str: + """Generate a Livekit access token for a user in a specific room. + + Args: + room (str): The name of the room. + user (User): The user which request the access token. + + Returns: + str: The LiveKit JWT access token. + """ + + # todo - define the video grants properly based on user and room. + video_grants = VideoGrants( + room=room, + room_join=True, + can_publish_sources=[ + "camera", + "microphone", + "screen_share", + "screen_share_audio", + ], + ) + + token = AccessToken( + api_key=settings.LIVEKIT_CONFIGURATION["api_key"], + api_secret=settings.LIVEKIT_CONFIGURATION["api_secret"], + ).with_grants(video_grants) + + if user.is_anonymous: + # todo - allow passing a proper name for not logged-in user + token.with_identity(str(uuid4())) + else: + # todo - use user's fullname instead of its email for the displayed name + token.with_identity(user.sub).with_name(f"{user!s}") + + return token.to_jwt()