🚧(backend) Add utility function to generate LiveKit access token

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.
This commit is contained in:
lebaudantoine
2024-06-25 18:55:52 +02:00
parent b3de3f5e92
commit 2deef12d05

47
src/backend/core/utils.py Normal file
View File

@@ -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()