Skip to content

Conversation

Anshumancanrock
Copy link

@Anshumancanrock Anshumancanrock commented Sep 24, 2025

Fixes : #382

Summary by Sourcery

Fix export of sessions by properly extracting user IDs from bearer tokens for personalized schedule exports and returning responses with correct content types.

Bug Fixes:

  • Correct personalized session exports by decoding bearer tokens to identify the requesting user

Enhancements:

  • Map export formats to appropriate HTTP content types and use HttpResponse instead of DRF Response
  • Introduce get_uid_from_token static method to parse and validate JWT tokens from the Authorization header

Copy link

sourcery-ai bot commented Sep 24, 2025

Reviewer's Guide

This PR refactors the session export endpoint to reliably extract the user from a bearer token and to return exports with correct MIME types based on the requested format.

File-Level Changes

Change Details Files
Improve user lookup by extracting UID from bearer token
  • Added static method get_uid_from_token to parse and validate the Authorization header
  • Replaced direct User.objects.filter(token_id=request.user) with token-based lookup inside try/except
  • Handled missing or malformed token cases without breaking export flow
server/venueless/api/views.py
Use client_state directly and clean up schedule-my export logic
  • Removed redundant .first() call and accessed user.client_state directly
  • Adjusted conditional for 'my' exports to use updated user object
server/venueless/api/views.py
Return responses with correct MIME types
  • Introduced content_type_map mapping export_type to appropriate MIME type
  • Switched from generic Response to HttpResponse with explicit content_type
server/venueless/api/views.py

Possibly linked issues

  • Export of my starred sessions is not working #382: The PR fixes the export of starred sessions by correcting user ID extraction from tokens and ensuring the correct content type is returned for different export formats, resolving the 'Page not found' error.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `server/venueless/api/views.py:314-316` </location>
<code_context>
+        
+        # Extract user ID from token properly
+        user = None
+        try:
+            user_code = ExportView.get_uid_from_token(request, kwargs["world_id"])
+            if user_code:
+                user = User.objects.filter(token_id=user_code).first()
+        except Exception:
</code_context>

<issue_to_address>
**issue (bug_risk):** Exception handling is too broad and may mask unexpected errors.

Use specific exception types like AuthenticationFailed or ValueError when handling token extraction errors to prevent hiding unrelated issues.
</issue_to_address>

### Comment 2
<location> `server/venueless/api/views.py:344` </location>
<code_context>
                 talk_url = talk_base_url + export_endpoint + "?talks=" + talk_list_str
+        
         header = {"Content-Type": "application/json"}
         response = requests.get(talk_url, headers=header)
-        return Response(response.content.decode("utf-8"))
+        
</code_context>

<issue_to_address>
**issue (bug_risk):** No error handling for failed HTTP requests.

Handle exceptions from 'requests.get' and check for non-200 status codes to prevent returning incorrect data.
</issue_to_address>

### Comment 3
<location> `server/venueless/api/views.py:358-360` </location>
<code_context>
+            'myxcal': 'application/xcal+xml'
+        }
+        
+        response_content_type = content_type_map.get(export_type, 'text/plain')
+        
+        return HttpResponse(response.content, content_type=response_content_type)
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Defaulting to 'text/plain' for unknown export types may not be ideal.

Validate 'export_type' before this point and return a 400 Bad Request for unsupported types to prevent serving incorrect content.

```suggestion
        if export_type not in content_type_map:
            return HttpResponse(
                "Unsupported export type.",
                status=400,
                content_type="text/plain"
            )
        response_content_type = content_type_map[export_type]

        return HttpResponse(response.content, content_type=response_content_type)
```
</issue_to_address>

### Comment 4
<location> `server/venueless/api/views.py:363` </location>
<code_context>
+        return HttpResponse(response.content, content_type=response_content_type)
+
+    @staticmethod
+    def get_uid_from_token(request, world_id):
+        world = get_object_or_404(World, id=world_id)
+        auth_header = get_authorization_header(request).split()
</code_context>

<issue_to_address>
**suggestion:** Token extraction logic assumes the token is always present and valid.

Please add checks for missing or malformed authorization headers and handle invalid tokens gracefully, such as by returning None or raising a controlled exception.
</issue_to_address>

### Comment 5
<location> `server/venueless/api/views.py:314` </location>
<code_context>
    @staticmethod
    def get(request, *args, **kwargs):
        export_type = request.GET.get("export_type", "json")
        world = get_object_or_404(World, id=kwargs["world_id"])
        talk_config = world.config.get("pretalx")

        # Extract user ID from token properly
        user = None
        try:
            user_code = ExportView.get_uid_from_token(request, kwargs["world_id"])
            if user_code:
                user = User.objects.filter(token_id=user_code).first()
        except Exception:
            # If token extraction fails, continue without user context
            pass

        talk_base_url = (
            talk_config.get("domain")
            + "/"
            + talk_config.get("event")
            + "/schedule/export/"
        )
        export_endpoint = "schedule." + export_type
        talk_url = talk_base_url + export_endpoint

        if "my" in export_type and user:
            user_state = user.client_state
            if (
                user_state
                and user_state.get("schedule")
                and user_state.get("schedule").get("favs")
            ):
                talk_list = user_state.get("schedule").get("favs")
                talk_list_str = ",".join(talk_list)
                export_endpoint = "schedule-my." + export_type.replace("my", "")
                talk_url = talk_base_url + export_endpoint + "?talks=" + talk_list_str

        header = {"Content-Type": "application/json"}
        response = requests.get(talk_url, headers=header)

        # Return appropriate content type and response
        content_type_map = {
            'json': 'application/json',
            'myjson': 'application/json',
            'ics': 'text/calendar',
            'myics': 'text/calendar', 
            'xml': 'application/xml',
            'myxml': 'application/xml',
            'xcal': 'application/xcal+xml',
            'myxcal': 'application/xcal+xml'
        }

        response_content_type = content_type_map.get(export_type, 'text/plain')

        return HttpResponse(response.content, content_type=response_content_type)

</code_context>

<issue_to_address>
**issue (code-quality):** We've found these issues:

- Use `contextlib`'s `suppress` method to silence an error ([`use-contextlib-suppress`](https://docs.sourcery.ai/Reference/Default-Rules/refactorings/use-contextlib-suppress/))
- Use named expression to simplify assignment and conditional ([`use-named-expression`](https://docs.sourcery.ai/Reference/Default-Rules/refactorings/use-named-expression/))
- Use f-string instead of string concatenation ([`use-fstring-for-concatenation`](https://docs.sourcery.ai/Reference/Default-Rules/refactorings/use-fstring-for-concatenation/))
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Export of my starred sessions is not working
1 participant