Skip to content

Commit

Permalink
♻️(backend) rename simple_jwt classes
Browse files Browse the repository at this point in the history
As we now have only playlist tokens, the simple_jwt classes must be renamed
for reflecting it.
  • Loading branch information
kernicPanel committed Aug 17, 2023
1 parent 26a690b commit 05ac9e3
Show file tree
Hide file tree
Showing 35 changed files with 242 additions and 242 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
)
from marsha.core.lti import LTI
from marsha.core.models import ADMINISTRATOR
from marsha.core.simple_jwt.tokens import ResourceAccessToken
from marsha.core.simple_jwt.tokens import PlaylistAccessToken
from marsha.core.tests.test_views_lti_base import BaseLTIViewForPortabilityTestCase

from ..factories import {{cookiecutter.model}}Factory
Expand Down Expand Up @@ -65,7 +65,7 @@ def test_views_lti_{{cookiecutter.model_lower}}_student(self, mock_get_consumer_
)

context = json.loads(html.unescape(match.group(1)))
jwt_token = ResourceAccessToken(context.get("jwt"))
jwt_token = PlaylistAccessToken(context.get("jwt"))
self.assertEqual(context.get("state"), "success")
self.assertIsNotNone(context.get("resource"))
self.assertEqual(context.get("modelName"), "{{cookiecutter.model_plural_lower}}")
Expand Down Expand Up @@ -153,7 +153,7 @@ def test_views_lti_{{cookiecutter.model_lower}}_instructor_same_playlist(
)

context = json.loads(html.unescape(match.group(1)))
jwt_token = ResourceAccessToken(context.get("jwt"))
jwt_token = PlaylistAccessToken(context.get("jwt"))
self.assertEqual(jwt_token.payload["resource_id"], str({{cookiecutter.model_lower}}.id))
self.assertEqual(
jwt_token.payload["user"],
Expand Down
4 changes: 2 additions & 2 deletions src/backend/marsha/account/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
TokenRefreshSerializer as BaseTokenRefreshSerializer,
)

from marsha.core.simple_jwt.authentication import TokenResource
from marsha.core.simple_jwt.authentication import TokenPlaylist
from marsha.core.simple_jwt.tokens import MarshaRefreshToken, UserRefreshToken


Expand Down Expand Up @@ -79,7 +79,7 @@ def __init__(self, *args, **kwargs):
"""Instantiate the serializer and make the `TokenUser` to `User` conversion."""
super().__init__(*args, **kwargs)
if isinstance(self.user, TokenUser) and not isinstance(
self.user, TokenResource
self.user, TokenPlaylist
):
# May raise 500 here but this is not expected so let it raise
self.user = get_user_model().objects.get(pk=self.user.pk)
Expand Down
4 changes: 2 additions & 2 deletions src/backend/marsha/account/tests/api/test_password_change.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from django.test import TestCase

from marsha.core.factories import UserFactory
from marsha.core.simple_jwt.factories import LTIResourceAccessTokenFactory
from marsha.core.simple_jwt.factories import LTIPlaylistAccessTokenFactory
from marsha.core.simple_jwt.tokens import UserAccessToken


Expand Down Expand Up @@ -54,7 +54,7 @@ def test_password_change_wrong_authentication(self):
"new_password2": "new_password",
}
),
HTTP_AUTHORIZATION=f"Bearer {str(LTIResourceAccessTokenFactory())}",
HTTP_AUTHORIZATION=f"Bearer {str(LTIPlaylistAccessTokenFactory())}",
)

self.assertEqual(response.status_code, 401) # Unauthorized
Expand Down
10 changes: 5 additions & 5 deletions src/backend/marsha/account/tests/api/test_token_refresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@

from marsha.core.factories import UserFactory
from marsha.core.simple_jwt.tokens import (
ResourceAccessToken,
ResourceRefreshToken,
PlaylistAccessToken,
PlaylistRefreshToken,
UserAccessToken,
UserRefreshToken,
)
Expand Down Expand Up @@ -92,7 +92,7 @@ def test_success_resource_access(self):
"""
session_id = str(uuid.uuid4())
resource_id = str(uuid.uuid4())
refresh_token = ResourceRefreshToken.for_resource_id(resource_id, session_id)
refresh_token = PlaylistRefreshToken.for_resource_id(resource_id, session_id)

response = self.client.post(
"/account/api/token/refresh/",
Expand All @@ -110,8 +110,8 @@ def test_success_resource_access(self):
self.assertIn("refresh", response_data)

# Verify tokens
new_token = ResourceAccessToken(response_data["access"])
new_refresh_token = ResourceRefreshToken(response_data["refresh"])
new_token = PlaylistAccessToken(response_data["access"])
new_refresh_token = PlaylistRefreshToken(response_data["refresh"])

self.assertEqual(new_token.payload["token_type"], "resource_access")
self.assertEqual(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from marsha.bbb.factories import ClassroomFactory
from marsha.core.models import INSTRUCTOR, NONE
from marsha.core.simple_jwt.tokens import ResourceAccessToken
from marsha.core.simple_jwt.tokens import PlaylistAccessToken
from marsha.core.tests.testing_utils import reload_urlconf


Expand Down Expand Up @@ -52,7 +52,7 @@ def test_invite_public_token(self):
self.assertEqual(response.status_code, 200)
public_token = response.json().get("access_token")

decoded_public_token = ResourceAccessToken(public_token)
decoded_public_token = PlaylistAccessToken(public_token)
self.assertEqual(decoded_public_token.payload["resource_id"], str(classroom.id))
self.assertEqual(decoded_public_token.payload["roles"], [NONE])
self.assertEqual(
Expand All @@ -71,7 +71,7 @@ def test_invite_instructor_token(self):
self.assertEqual(response.status_code, 200)
instructor_token = response.json().get("access_token")

decoded_instructor_token = ResourceAccessToken(instructor_token)
decoded_instructor_token = PlaylistAccessToken(instructor_token)
self.assertEqual(
decoded_instructor_token.payload["resource_id"], str(classroom.id)
)
Expand Down
10 changes: 5 additions & 5 deletions src/backend/marsha/bbb/tests/test_views_lti.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
)
from marsha.core.lti import LTI
from marsha.core.models import ADMINISTRATOR
from marsha.core.simple_jwt.tokens import ResourceAccessToken
from marsha.core.simple_jwt.tokens import PlaylistAccessToken
from marsha.core.tests.testing_utils import reload_urlconf
from marsha.core.tests.views.test_lti_base import BaseLTIViewForPortabilityTestCase

Expand Down Expand Up @@ -98,7 +98,7 @@ def test_views_lti_classroom_student(self, mock_get_consumer_site, mock_verify):
)

context = json.loads(html.unescape(match.group(1)))
jwt_token = ResourceAccessToken(context.get("jwt"))
jwt_token = PlaylistAccessToken(context.get("jwt"))
self.assertEqual(context.get("state"), "success")
self.assertIsNotNone(context.get("resource"))
self.assertEqual(context.get("modelName"), "classrooms")
Expand Down Expand Up @@ -249,7 +249,7 @@ def test_views_lti_classroom_instructor_same_playlist(
)

context = json.loads(html.unescape(match.group(1)))
jwt_token = ResourceAccessToken(context.get("jwt"))
jwt_token = PlaylistAccessToken(context.get("jwt"))
self.assertEqual(jwt_token.payload["resource_id"], str(classroom.playlist.id))
self.assertEqual(
jwt_token.payload["user"],
Expand Down Expand Up @@ -437,7 +437,7 @@ def test_views_lti_classroom_student(self, mock_get_consumer_site, mock_verify):
)

context = json.loads(html.unescape(match.group(1)))
jwt_token = ResourceAccessToken(context.get("jwt"))
jwt_token = PlaylistAccessToken(context.get("jwt"))
self.assertEqual(context.get("state"), "success")
self.assertIsNotNone(context.get("resource"))
self.assertEqual(context.get("modelName"), "classrooms")
Expand Down Expand Up @@ -588,7 +588,7 @@ def test_views_lti_classroom_instructor_same_playlist(
)

context = json.loads(html.unescape(match.group(1)))
jwt_token = ResourceAccessToken(context.get("jwt"))
jwt_token = PlaylistAccessToken(context.get("jwt"))
self.assertEqual(jwt_token.payload["resource_id"], str(classroom.playlist.id))
self.assertEqual(
jwt_token.payload["user"],
Expand Down
6 changes: 3 additions & 3 deletions src/backend/marsha/bbb/utils/tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from django.utils import timezone

from marsha.core.models import INSTRUCTOR, NONE
from marsha.core.simple_jwt.tokens import ResourceAccessToken
from marsha.core.simple_jwt.tokens import PlaylistAccessToken


def create_classroom_stable_invite_jwt(classroom, role=NONE, permissions=None):
Expand All @@ -24,11 +24,11 @@ def create_classroom_stable_invite_jwt(classroom, role=NONE, permissions=None):
Returns
-------
ResourceAccessToken
PlaylistAccessToken
The JWT.
"""
resource_jwt = ResourceAccessToken.for_resource_id(
resource_jwt = PlaylistAccessToken.for_resource_id(
resource_id=str(classroom.id),
session_id=f"{classroom.id}-invite",
roles=[role],
Expand Down
4 changes: 2 additions & 2 deletions src/backend/marsha/core/api/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from ..defaults import SENTRY, VOD_CONVERT
from ..models import SiteConfig, Video
from ..signals import signal_object_uploaded
from ..simple_jwt.tokens import ResourceAccessToken
from ..simple_jwt.tokens import PlaylistAccessToken
from ..utils.api_utils import get_uploadable_models_s3_mapping, validate_signature


Expand Down Expand Up @@ -278,7 +278,7 @@ def check_permissions(self, request):
we keep it as a TokenResource...
"""
request.resource = None
if isinstance(request.auth, ResourceAccessToken): # otherwise, nothing to do
if isinstance(request.auth, PlaylistAccessToken): # otherwise, nothing to do
request.resource = request.user

super().check_permissions(request)
Expand Down
6 changes: 3 additions & 3 deletions src/backend/marsha/core/simple_jwt/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from rest_framework_simplejwt.models import TokenUser


class TokenResource(TokenUser):
class TokenPlaylist(TokenUser):
"""Same as TokenUser but for resource access JWT, with helpers for payload."""

@cached_property
Expand All @@ -26,7 +26,7 @@ def user(self):
return self.token.get("user", {})


class JWTStatelessUserOrResourceAuthentication(JWTStatelessUserAuthentication):
class JWTStatelessUserOrPlaylistAuthentication(JWTStatelessUserAuthentication):
"""
An authentication plugin that authenticates requests through a JSON web
token provided in a request header without performing a database lookup
Expand All @@ -50,6 +50,6 @@ def get_user(self, validated_token):
raise InvalidToken(
_("Token contained no recognizable resource identification")
) from exc
return TokenResource(validated_token)
return TokenPlaylist(validated_token)

return user
34 changes: 17 additions & 17 deletions src/backend/marsha/core/simple_jwt/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@

from marsha.core.factories import ConsumerSiteFactory, LiveSessionFactory, UserFactory
from marsha.core.models import ADMINISTRATOR, INSTRUCTOR, LTI_ROLES, NONE, STUDENT
from marsha.core.simple_jwt.permissions import ResourceAccessPermissions
from marsha.core.simple_jwt.permissions import PlaylistAccessPermissions
from marsha.core.simple_jwt.tokens import (
ChallengeToken,
LTIUserToken,
ResourceAccessToken,
PlaylistAccessToken,
UserAccessToken,
)

Expand Down Expand Up @@ -104,14 +104,14 @@ class Meta: # pylint:disable=missing-class-docstring
model = ChallengeToken.for_user


class ResourcePermissionsFactory(factory.DictFactory):
class PlaylistPermissionsFactory(factory.DictFactory):
"""Factory for resource access permissions."""

can_access_dashboard = False
can_update = False

class Meta: # pylint:disable=missing-class-docstring
model = ResourceAccessPermissions
model = PlaylistAccessPermissions

@classmethod
def _build(cls, model_class, *args, **kwargs):
Expand All @@ -120,7 +120,7 @@ def _build(cls, model_class, *args, **kwargs):
return permissions.as_dict()


class BaseResourceTokenFactory(BaseTokenFactory):
class BasePlaylistTokenFactory(BaseTokenFactory):
"""
Base class for all resource token factories.
This allows to provide a resource (video, document, ...)
Expand Down Expand Up @@ -161,16 +161,16 @@ class Params: # pylint:disable=missing-class-docstring
resource = None


class ResourceAccessTokenFactory(BaseResourceTokenFactory):
class PlaylistAccessTokenFactory(BasePlaylistTokenFactory):
"""Simple resource token. Looks like a public resource token."""

session_id = factory.Faker("uuid4")

class Meta: # pylint:disable=missing-class-docstring
model = ResourceAccessToken.for_resource_id
model = PlaylistAccessToken.for_resource_id


class LTIResourceAccessTokenFactory(BaseResourceTokenFactory):
class LTIPlaylistAccessTokenFactory(BasePlaylistTokenFactory):
"""
LTI resource forged token.
Expand All @@ -181,7 +181,7 @@ class LTIResourceAccessTokenFactory(BaseResourceTokenFactory):

# for_resource_id payload
session_id = factory.Faker("uuid4")
permissions = factory.SubFactory(ResourcePermissionsFactory)
permissions = factory.SubFactory(PlaylistPermissionsFactory)
roles = factory.fuzzy.FuzzyChoice(
[ADMINISTRATOR, INSTRUCTOR, STUDENT, NONE],
getter=lambda x: [x],
Expand All @@ -204,16 +204,16 @@ class LTIResourceAccessTokenFactory(BaseResourceTokenFactory):
)

class Meta: # pylint:disable=missing-class-docstring
model = ResourceAccessToken
model = PlaylistAccessToken


class StudentLtiTokenFactory(LTIResourceAccessTokenFactory):
class StudentLtiTokenFactory(LTIPlaylistAccessTokenFactory):
"""LTI resource forged token for student."""

roles = factory.fuzzy.FuzzyChoice(LTI_ROLES.get(STUDENT), getter=lambda x: [x])


class InstructorOrAdminLtiTokenFactory(LTIResourceAccessTokenFactory):
class InstructorOrAdminLtiTokenFactory(LTIPlaylistAccessTokenFactory):
"""
LTI resource forged token for instructor or administrators.
See `marsha.core.views.BaseLTIView`.
Expand All @@ -225,7 +225,7 @@ class InstructorOrAdminLtiTokenFactory(LTIResourceAccessTokenFactory):

roles = factory.fuzzy.FuzzyChoice([ADMINISTRATOR, INSTRUCTOR], getter=lambda x: [x])
permissions = factory.SubFactory(
ResourcePermissionsFactory,
PlaylistPermissionsFactory,
can_access_dashboard=True,
can_update=True,
)
Expand All @@ -243,17 +243,17 @@ class InstructorOrAdminLtiTokenFactory(LTIResourceAccessTokenFactory):
# playlist = factory.SubFactory(PlaylistFactory)


class LiveSessionResourceAccessTokenFactory(BaseTokenFactory):
class LiveSessionPlaylistAccessTokenFactory(BaseTokenFactory):
"""Generates a resource access token from a live session."""

live_session = factory.SubFactory(LiveSessionFactory)
session_id = factory.Faker("uuid4")

class Meta: # pylint:disable=missing-class-docstring
model = ResourceAccessToken.for_live_session
model = PlaylistAccessToken.for_live_session


class LiveSessionLtiTokenFactory(LTIResourceAccessTokenFactory):
class LiveSessionLtiTokenFactory(LTIPlaylistAccessTokenFactory):
"""
Prefer the use of LiveSessionResourceAccessTokenFactory,
but this one allows to deeply customize the final JWT.
Expand All @@ -276,7 +276,7 @@ class LiveSessionLtiTokenFactory(LTIResourceAccessTokenFactory):
)

class Meta: # pylint:disable=missing-class-docstring
model = ResourceAccessToken
model = PlaylistAccessToken

class Params: # pylint:disable=missing-class-docstring
live_session = factory.SubFactory(
Expand Down
2 changes: 1 addition & 1 deletion src/backend/marsha/core/simple_jwt/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@


@dataclass
class ResourceAccessPermissions:
class PlaylistAccessPermissions:
"""Permissions which can be provided in ResourceAccessToken"""

can_access_dashboard: bool = False
Expand Down
Loading

0 comments on commit 05ac9e3

Please sign in to comment.