Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve access logic and URL structure #386

Merged
merged 29 commits into from
Nov 19, 2024

Conversation

odkhang
Copy link
Collaborator

@odkhang odkhang commented Oct 10, 2024

This PR related to issue fossasia/eventyay-video#240 Improve access logic and URL structure
It implement point 2 + 3 of the issue (point 1 is implemented by update nginx)

New button in event page of common, will redirect to video system with admin permission

image

Summary by Sourcery

Enhance the event page by adding a button for video system access with admin permissions and improve the access logic by implementing a VideoAccessAuthenticator class to manage permissions and token generation.

New Features:

  • Introduce a new button on the event page that redirects to the video system with admin permissions.

Enhancements:

  • Improve the access logic by adding a VideoAccessAuthenticator class to handle video access permissions and token generation.

@odkhang odkhang marked this pull request as ready for review October 14, 2024 03:22
Copy link

sourcery-ai bot commented Oct 14, 2024

Reviewer's Guide by Sourcery

This PR enhances the event management system by implementing video access functionality. The changes introduce a new VideoAccessAuthenticator view for handling video access permissions and add a video access button to the event page. The implementation includes token generation for secure access and proper permission checks.

Sequence diagram for video access authentication

sequenceDiagram
    actor User
    participant EventPage
    participant VideoAccessAuthenticator
    participant VideoSystem

    User->>EventPage: Click "Enable video access"
    EventPage->>VideoAccessAuthenticator: Request video access
    VideoAccessAuthenticator->>VideoAccessAuthenticator: Check video configuration
    alt Configuration incomplete or plugin disabled
        VideoAccessAuthenticator-->>User: Permission Denied
    else Configuration complete
        VideoAccessAuthenticator->>VideoAccessAuthenticator: Check user permissions
        alt User lacks permissions
            VideoAccessAuthenticator-->>User: Permission Denied
        else User has permissions
            VideoAccessAuthenticator->>VideoAccessAuthenticator: Generate token
            VideoAccessAuthenticator->>VideoSystem: Redirect with token
        end
    end
Loading

Class diagram for VideoAccessAuthenticator

classDiagram
    class VideoAccessAuthenticator {
        +get(request, *args, **kwargs)
        +generate_token_url(request)
    }
    VideoAccessAuthenticator --> APIView
    class APIView {
        <<abstract>>
    }
Loading

File-Level Changes

Change Details Files
Added new VideoAccessAuthenticator view to handle video access authentication and redirection
  • Implements permission checks for video plugin configuration and user access
  • Generates JWT tokens for video system access with 30-day expiration
  • Creates URL with embedded token for video system redirection
  • Adds traits for event organizer and admin permissions
src/pretix/eventyay_common/views/event.py
Enhanced event listing view with plugin handling functionality
  • Added get_plugins method to format plugin list into an array
  • Modified get_context_data to include plugins array for each event
src/pretix/eventyay_common/views/event.py
Updated event listing template to display video access button
  • Added conditional rendering of video camera button for events with video plugin enabled
  • Linked video access button to new VideoAccessAuthenticator endpoint
src/pretix/eventyay_common/templates/eventyay_common/events/index.html
Added new URL route for video access authentication
  • Created new URL pattern for video access authentication endpoint
src/pretix/eventyay_common/urls.py

Possibly linked issues


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.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a 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. You can also use
    this command to specify where the summary should be inserted.

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 @odkhang - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider making the create_world task more resilient to failures of the external video service, possibly by implementing a retry mechanism or making it fully asynchronous.
  • The encode_email function in utils.py uses a combination of hashing and random characters. While this provides some obfuscation, it may not be necessary if the email is not sensitive information. Consider simplifying this if possible.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟡 Security: 3 issues found
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

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.

src/pretix/eventyay_common/views/event.py Show resolved Hide resolved
@@ -103,6 +103,48 @@ def send_event_webhook(self, user_id, event, action):
except self.MaxRetriesExceededError:
logger.error("Max retries exceeded for sending organizer webhook.")

@shared_task(bind=True, max_retries=5, default_retry_delay=60) # Retries up to 5 times with a 60-second delay
def create_world(self, is_video_create, data):
Copy link

Choose a reason for hiding this comment

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

suggestion (bug_risk): Enhance error handling and consider rate limiting for external API calls

Implement more robust error handling for the HTTP request to the external service. Consider adding rate limiting to prevent potential abuse of the video creation functionality.

def create_world(self, is_video_create, data):
    try:
        with RateLimiter(max_calls=5, period=60):  # Rate limit: 5 calls per minute
            response = self.make_api_call(is_video_create, data)
            response.raise_for_status()
    except requests.exceptions.RequestException as e:
        logger.error(f"Error creating video system: {str(e)}")
        raise self.retry(exc=e, countdown=60)

return final_result.upper()


def check_create_permission(request):
Copy link

Choose a reason for hiding this comment

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

🚨 suggestion (security): Refine permission check for video creation

Consider implementing a more specific permission check for video creation, rather than relying solely on the 'can_create_events' permission. This will provide finer-grained control over who can create video platforms.

def check_create_video_permission(request):
    """
    Check if the user has permission to create videos.
    """
    return request.user.has_perm('eventyay_common.create_video')

return token


def encode_email(email):
Copy link

Choose a reason for hiding this comment

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

🚨 question (security): Clarify purpose and security implications of email encoding

The purpose and security benefits of the email encoding function are not clear. If this is intended for privacy or security purposes, consider using a more robust method or explain the rationale behind this implementation.

event_timezone = data.get("timezone")
locale = data.get("locale")
token = data.get("token")
has_permission = data.get("has_permission")
Copy link
Member

Choose a reason for hiding this comment

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

Please make token, has_permission explicit parameters of create_world function.

headers=headers,
)
except requests.exceptions.ConnectionError as e:
logger.error(f"Connection error: {e}")
Copy link
Member

Choose a reason for hiding this comment

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

Wrong use of logger. This has been remined many times.

@param request: user request
@return: jwt
"""
uid_token = encode_email(request.user.email)
Copy link
Member

Choose a reason for hiding this comment

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

Why email need to be encoded?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I would like to create a unique identification for user authentication in the video system.

@odkhang odkhang marked this pull request as draft October 28, 2024 09:35
@odkhang odkhang marked this pull request as ready for review November 1, 2024 08:45
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 @odkhang - I've reviewed your changes - here's some feedback:

Overall Comments:

  • The URL pattern url('', event.VideoAccessAuthenticator.as_view()) is too broad and may conflict with other routes. Consider using a more specific path like url('video-access/', ...)
  • The JWT token expiration of 30 days for admin access seems excessive. Consider reducing this to a shorter period (e.g., 24 hours) and implementing refresh tokens if longer access is needed
Here's what I looked at during the review
  • 🟡 General issues: 3 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

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.

"uid": uid_token,
"traits": list(
{
"eventyay-video-event-{}-orgnanizer".format(request.event.slug),
Copy link

Choose a reason for hiding this comment

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

issue (typo): Fix typo in trait name 'orgnanizer' -> 'organizer'

"""
if plugin_list is None:
return []
return plugin_list.split(",")
Copy link

Choose a reason for hiding this comment

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

suggestion: Make plugin parsing more robust by handling empty strings

Consider handling empty strings and stripping whitespace: 'return [p.strip() for p in plugin_list.split(",") if p.strip()]'

Suggested change
return plugin_list.split(",")
return [p.strip() for p in plugin_list.split(",") if p.strip()]

@@ -19,5 +19,6 @@
url(r'^events/add$', event.EventCreateView.as_view(), name='events.add'),
url(r'^event/(?P<organizer>[^/]+)/(?P<event>[^/]+)/', include([
url(r'^settings/$', event.EventUpdate.as_view(), name='event.update'),
url('', event.VideoAccessAuthenticator.as_view(), name='event.create_access_to_video'),
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): Use a specific URL pattern for video access endpoint

Using an empty string as URL pattern will match all routes. Consider using a specific path like 'video-access/' to avoid routing conflicts.

@mariobehling mariobehling merged commit 36ea5f7 into fossasia:development Nov 19, 2024
4 of 5 checks passed
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.

4 participants