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

refactor: Reorganize routes into /api/v1 #492

Merged
merged 2 commits into from
Feb 23, 2025
Merged

refactor: Reorganize routes into /api/v1 #492

merged 2 commits into from
Feb 23, 2025

Conversation

tphakala
Copy link
Owner

No description provided.

- Update all routes to use consistent `/api/v1/` prefix
- Modify authentication, media, detection, and SSE routes
- Update view templates to use new API route structure
- Improve route organization and predictability
- Enhance cache control middleware for API routes
…ractivity

- Create reusable HTML components for text, password, host, and checkbox inputs
- Implement Alpine.js-powered input validation and interactive features
- Add tooltips, error messages, and accessibility attributes
- Standardize form input styling and behavior across components
Copy link
Contributor

coderabbitai bot commented Feb 23, 2025

Walkthrough

This update systematically revises API route paths by injecting a version prefix (/api/v1) throughout the codebase. The changes span authentication endpoints, detection handlers, media serving, and various AJAX/HTML calls, along with enhanced documentation and refined error handling (including proper response headers and caching). Middleware functions are adjusted to recognize the new endpoints, ensuring consistent protection and caching behaviors. No new functionality is introduced; rather, the revisions standardize and document existing routes for a versioned API structure.

Changes

File(s) Change Summary
internal/httpcontroller/auth_routes.go Updated OAuth2 and social authentication endpoints to use /api/v1 (including /oauth2/authorize, /oauth2/token, /oauth2/callback, and corresponding social auth endpoints). Redirect URL in handleBasicAuthLogin was modified accordingly.
internal/httpcontroller/handlers/detections.go Added and updated API documentation comments for detection-related functions with versioned endpoints (e.g., GET /api/v1/detections, POST /api/v1/detections/review). Introduced a new ReviewDetection function.
internal/httpcontroller/handlers/media.go Revised ServeSpectrogram and ServeAudioClip functions to include API endpoint comments, adjust content-type headers, and improve error handling and cache-control for media responses.
internal/httpcontroller/handlers/audio_level_sse.go, mqtt.go, settings.go, sse.go Updated documentation comments and API endpoint annotations in SSE, MQTT, audio level, and settings functions to reflect the /api/v1 versioning.
internal/httpcontroller/htmx_routes.go Modified all route paths in the route initialization function, adding the /api/v1/ prefix for endpoints related to detections, media, notes, settings, and more.
internal/httpcontroller/middleware.go Adjusted CSRF and Cache-Control middleware logic to recognize updated /api/v1/ endpoints. Expanded the list of protected routes and refined cache-control header settings.
views/elements/*, views/fragments/*, views/pages/settings/settingsBase.html Updated URLs in HTML templates (AJAX calls, EventSource initializations, image/audio sources, and form submissions) to route to new /api/v1 endpoints, affecting authentication, media, detection details, and settings.

Possibly related PRs

Poem

I'm a happy rabbit, hopping with glee,
New API routes now as clear as can be.
With a prefix /api/v1 in every lane,
Our endpoints dance in a versioned domain.
Carrots and code, together they sing—
In this digital burrow, smooth changes we bring!
🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
internal/httpcontroller/auth_routes.go (1)

20-23: Consider moving basic auth routes under /api/v1 for consistency.

While OAuth2 and social authentication routes use the /api/v1 prefix, basic authentication routes (/login, /logout) remain at the root level. This inconsistency could make API documentation and maintenance more difficult.

 // Basic authentication routes
-g.GET("/login", s.Handlers.WithErrorHandling(s.handleLoginPage))
-g.POST("/login", s.handleBasicAuthLogin)
-g.GET("/logout", s.Handlers.WithErrorHandling(s.handleLogout))
+g.GET("/api/v1/login", s.Handlers.WithErrorHandling(s.handleLoginPage))
+g.POST("/api/v1/login", s.handleBasicAuthLogin)
+g.GET("/api/v1/logout", s.Handlers.WithErrorHandling(s.handleLogout))

Also applies to: 25-27, 29-32

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0b5fb99 and 874ee9e.

📒 Files selected for processing (19)
  • internal/httpcontroller/auth_routes.go (2 hunks)
  • internal/httpcontroller/handlers/audio_level_sse.go (1 hunks)
  • internal/httpcontroller/handlers/detections.go (7 hunks)
  • internal/httpcontroller/handlers/media.go (7 hunks)
  • internal/httpcontroller/handlers/mqtt.go (1 hunks)
  • internal/httpcontroller/handlers/settings.go (2 hunks)
  • internal/httpcontroller/handlers/sse.go (1 hunks)
  • internal/httpcontroller/htmx_routes.go (2 hunks)
  • internal/httpcontroller/middleware.go (3 hunks)
  • views/elements/audioLevelIndicator.html (1 hunks)
  • views/elements/callback.html (1 hunks)
  • views/elements/dashboard.html (2 hunks)
  • views/elements/login.html (1 hunks)
  • views/elements/reviewModal.html (2 hunks)
  • views/fragments/birdsTable.html (3 hunks)
  • views/fragments/detectionDetails.html (3 hunks)
  • views/fragments/listDetections.html (8 hunks)
  • views/fragments/recentDetections.html (10 hunks)
  • views/pages/settings/settingsBase.html (2 hunks)
✅ Files skipped from review due to trivial changes (4)
  • internal/httpcontroller/handlers/sse.go
  • internal/httpcontroller/handlers/mqtt.go
  • internal/httpcontroller/handlers/settings.go
  • internal/httpcontroller/handlers/audio_level_sse.go
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: unit-tests
  • GitHub Check: Analyze (go)
🔇 Additional comments (47)
internal/httpcontroller/auth_routes.go (2)

30-32: LGTM! Rate limiting is properly configured for authentication routes.

The rate limiter is correctly applied to protect against brute force attacks, with a reasonable limit of 10 requests per interval.


114-133: LGTM! Secure implementation of basic authentication.

The implementation includes several security best practices:

  • Constant-time password comparison to prevent timing attacks
  • Proper validation of redirect parameter
  • Updated callback URL to use the new API versioning scheme
internal/httpcontroller/middleware.go (3)

31-70: LGTM! Robust CSRF protection with secure defaults.

The CSRF middleware is well-configured with:

  • Secure cookie settings (HTTPOnly, SameSite Lax)
  • Consistent API versioning in skip paths
  • Comprehensive error logging

81-122: LGTM! Well-structured cache control with appropriate settings for each content type.

The implementation provides:

  • No caching for API endpoints (no-store)
  • Long-term caching for static assets
  • 30-day caching for spectrograms
  • Proper debug logging

174-183: LGTM! Comprehensive protection of sensitive routes.

The function correctly identifies and protects sensitive operations under the new API versioning scheme.

internal/httpcontroller/htmx_routes.go (1)

90-98: LGTM! Well-organized route structure with clear separation of concerns.

The implementation:

  • Consistently applies /api/v1 prefix to API routes
  • Keeps UI routes at root level
  • Maintains uniform error handling
internal/httpcontroller/handlers/media.go (2)

222-298: LGTM! Robust implementation of spectrogram serving with proper error handling.

The implementation includes:

  • Correct content type headers for both success and error cases
  • Consistent 30-day caching strategy
  • Secure path sanitization
  • Proper fallback to placeholder SVG

597-673: LGTM! Secure implementation of audio file serving.

The implementation includes:

  • Proper MIME type detection
  • Secure path traversal prevention
  • Sanitized Content-Disposition headers
  • Comprehensive error handling
internal/httpcontroller/handlers/detections.go (7)

41-41: LGTM!

The API documentation comment follows the standard format and clearly indicates the endpoint.


172-173: LGTM!

The API documentation comments follow the standard format and clearly indicate the endpoint.


215-215: LGTM!

The API documentation comment follows the standard format and clearly indicates the endpoint.


323-323: LGTM!

The API documentation comment follows the standard format and clearly indicates the endpoint.


488-488: LGTM!

The API documentation comment follows the standard format and clearly indicates the endpoint.


593-594: LGTM!

The API documentation comments follow the standard format and clearly indicate the endpoint.


667-667: LGTM!

The API documentation comment follows the standard format and clearly indicates the endpoint.

views/elements/callback.html (1)

24-24: LGTM!

The OAuth2 token endpoint has been correctly updated to include the /api/v1 prefix, aligning with the PR objective.

views/elements/dashboard.html (2)

20-20: LGTM!

The top birds endpoint has been correctly updated to include the /api/v1 prefix, aligning with the PR objective.


51-51: LGTM!

The recent detections endpoint has been correctly updated to include the /api/v1 prefix, aligning with the PR objective.

views/fragments/detectionDetails.html (3)

27-27: LGTM!

The spectrogram endpoint has been correctly updated to include the /api/v1 prefix, aligning with the PR objective.


37-37: LGTM!

The audio endpoint has been correctly updated to include the /api/v1 prefix, aligning with the PR objective.


55-55: LGTM!

The audio download endpoint has been correctly updated to include the /api/v1 prefix, aligning with the PR objective.

views/elements/login.html (2)

53-57: API Versioning for Social Authentication (Google)
The anchor link for Google authentication has been updated to use /api/v1/auth/google. This change is consistent with the new API version scheme. Please ensure that the corresponding backend route for Google authentication is also updated.


59-64: API Versioning for Social Authentication (GitHub)
The GitHub authentication URL now correctly uses /api/v1/auth/github, aligning it with the new routing structure. Double-check that the server’s route handling for GitHub authentication reflects this update.

views/fragments/birdsTable.html (4)

29-30: Updated Species Row Link Endpoint
The species row anchor now queries detections using /api/v1/detections?species={{urlquery .Note.CommonName}}&date={{urlquery $.SelectedDate}}&queryType=species. This is a correct update in line with the new versioned API structure.


37-40: Consistent API Versioning for Thumbnail Link
The thumbnail link has been updated to use the new endpoint (/api/v1/detections?species=...). This ensures that both textual and thumbnail-based navigation retrieve species-specific detections correctly.


87-100: Updated Hour Header Endpoint
The hour header’s anchor now points to /api/v1/detections?date={{urlquery .Date}}&hour={{.HourIndex}}&duration={{.Length}}&queryType=hourly. This change properly versioned the hourly detection query endpoint.


107-109: Revised Count Display Link
The count display link has been modified to use /api/v1/detections?species={{urlquery .Species}}&date={{urlquery .Date}}&hour={{.HourIndex}}&duration={{.Duration}}&queryType=species, which is fully consistent with the new API versioning.

views/elements/reviewModal.html (2)

33-35: Updated Spectrogram Image Source URL
The spectrogram image now loads from /api/v1/media/spectrogram?clip={{.ClipName}}, ensuring that media assets are served via the new API version endpoint.


45-48: Updated Review Form Submission Endpoint
The review form’s submission URL is updated to /api/v1/detections/review. This change aligns the review submission process with the versioned API strategy.

views/fragments/recentDetections.html (9)

44-47: Updated Detection Details Link (Desktop Layout)
The detection details link for the desktop layout now directs to /api/v1/detections/details?id={{.ID}}, ensuring that detailed detection data is fetched via the versioned endpoint.


55-59: Revised Thumbnail Link Endpoint (Desktop Layout)
The thumbnail anchor has been updated to use /api/v1/detections/details?id={{.ID}}, maintaining consistency in navigation when a user clicks on the bird thumbnail image.


93-95: Revised Spectrogram Image Source (Desktop Layout)
The spectrogram image for desktop now sources from /api/v1/media/spectrogram?clip={{.ClipName}}, aligning with the updated API version for media retrieval.


102-104: Updated Audio Element Source (Desktop Layout)
The desktop audio element now references /api/v1/media/audio?clip={{.ClipName}}, ensuring that audio clips are loaded through the versioned media endpoint.


114-115: Audio Download Link Endpoint Update (Desktop Layout)
The download link for the audio file now uses /api/v1/media/audio?clip={{.ClipName}}. This update maintains consistency with the media API changes.


147-150: Updated Detection Details Link (Responsive Layout)
In the responsive layout, the detection details link has been updated to /api/v1/detections/details?id={{.ID}}. This ensures that mobile navigation aligns with the new API versioned endpoints.


165-169: Updated Thumbnail Link for Responsive Layout
The responsive thumbnail link now correctly routes to /api/v1/detections/details?id={{.ID}}, matching the versioned format used in the desktop view.


178-180: Revised Spectrogram Image Source (Responsive Layout)
The spectrogram image in the responsive layout now loads from /api/v1/media/spectrogram?clip={{.ClipName}}, in line with the updated media endpoints.


188-189: Updated Audio Element Source (Responsive Layout)
The audio element for the responsive layout is now updated to retrieve the clip from /api/v1/media/audio?clip={{.ClipName}}, ensuring consistent media access across layouts.

views/pages/settings/settingsBase.html (2)

54-56: Updated EventSource URL for SSE
The initialization of the EventSource is now set to /api/v1/sse. This change is key to ensuring that all real‐time notifications are routed through the versioned API endpoint. Please verify the server’s SSE configuration accordingly.


152-158: Revised Settings Save Endpoint
The settings save fetch request now targets /api/v1/settings/save. This update is consistent with the overall API versioning strategy. Ensure that backend CSRF validation and settings processing remain fully functional under the new route.

views/fragments/listDetections.html (6)

6-6: API Version Prefix in Detection Query
The hx-get attribute on line 6 now correctly includes the /api/v1/ prefix, updating the detections query endpoint to /api/v1/detections?.... This change aligns with the new API versioning strategy.


88-91: Updated Detection Details Endpoint
The URL in the anchor’s hx-get attribute has been updated to /api/v1/detections/details?id={{.ID}}, ensuring consistency with the versioned API.


137-137: Updated Spectrogram Media URL
The image src attribute for the spectrogram now correctly points to /api/v1/media/spectrogram?clip={{.ClipName}}, conforming to the new API route structure.


146-146: Updated Audio Media URL
The audio element’s source has been updated to /api/v1/media/audio?clip={{.ClipName}}. This change is consistent with the API versioning and ensures that audio media is served from the correct endpoint.


191-197: Updated Pagination - "Previous" Button Endpoint
The hx-get URL for the "Previous" pagination button now includes the /api/v1/detections prefix and correctly computes the offset using {{sub .Offset .NumResults}}. This update is in line with the new routing structure.


204-210: Updated Pagination - "Next" Button Endpoint
The "Next" button now calls an endpoint updated to /api/v1/detections with the offset calculated via {{add .Offset .NumResults}}, ensuring consistency across all pagination links.

views/elements/audioLevelIndicator.html (1)

56-56: API Version Update for Audio Level SSE
The EventSource initialization now uses the updated endpoint /api/v1/audio-level, which correctly reflects the versioning changes for SSE connections. The update is seamlessly integrated with the existing error handling and reconnection logic.

@tphakala tphakala merged commit 0c8827e into main Feb 23, 2025
10 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.

1 participant