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 22, 2023
1 parent f945985 commit b47d6e7
Show file tree
Hide file tree
Showing 35 changed files with 265 additions and 277 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
12 changes: 6 additions & 6 deletions src/backend/marsha/core/simple_jwt/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
from rest_framework_simplejwt.models import TokenUser


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

@cached_property
def id(self):
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 @@ -41,15 +41,15 @@ def get_user(self, validated_token):
We keep an actual user-like object to go through Django logic but this
method can return:
- TokenUser for user authentication
- TokenResource for resource authentication
- TokenPlaylist for playlist authentication
"""
try:
user = super().get_user(validated_token)
except InvalidToken as exc:
if "resource_id" not in validated_token:
raise InvalidToken(
_("Token contained no recognizable resource identification")
_("Token contained no recognizable playlist identification")
) from exc
return TokenResource(validated_token)
return TokenPlaylist(validated_token)

return user
Loading

0 comments on commit b47d6e7

Please sign in to comment.