From e274e91dcb020ce1eec4573abcfa45a858020617 Mon Sep 17 00:00:00 2001 From: Tykayn Date: Sun, 21 Sep 2025 12:27:00 +0200 Subject: [PATCH] traffic with osm auth --- .env.example | 7 +- backend.py | 1 + doc/demo_endpoint.md | 43 ++- oedb/resources/demo.py | 603 ++++++++++++++++++++++++++++++++++++++++- 4 files changed, 649 insertions(+), 5 deletions(-) diff --git a/.env.example b/.env.example index 4b52d1e..dd0701e 100644 --- a/.env.example +++ b/.env.example @@ -1,2 +1,7 @@ DB_USER=cipherbliss -POSTGRES_PASSWORD=tralalahihou \ No newline at end of file +POSTGRES_PASSWORD=tralalahihou + +CLIENT_ID=ziozioizo-sllkslk +CLIENT_SECRET=spposfdo-msmldflkds +CLIENT_AUTORIZATIONS=read_prefs +CLIENT_REDIRECT=https://oedb.cipherbliss.com:8080/demo/traffic diff --git a/backend.py b/backend.py index 54044b2..8fac739 100644 --- a/backend.py +++ b/backend.py @@ -62,6 +62,7 @@ def create_app(): app.add_route('/demo/by-what', demo, suffix='by_what') # Handle events by type page app.add_route('/demo/map-by-what', demo, suffix='map_by_what') # Handle map by event type page app.add_route('/demo/edit/{id}', demo, suffix='edit') # Handle event editing page + app.add_route('/demo/traffic', demo, suffix='traffic') # Handle traffic jam reporting page logger.success("Application initialized successfully") return app diff --git a/doc/demo_endpoint.md b/doc/demo_endpoint.md index 4da86e2..811b7de 100644 --- a/doc/demo_endpoint.md +++ b/doc/demo_endpoint.md @@ -68,12 +68,49 @@ If no events appear on the map: 3. Check the browser console for any JavaScript errors 4. Verify that the `/event` endpoint is working correctly by accessing it directly +## Additional Demo Pages + +The demo section includes several specialized pages: + +1. **Main Demo Page** (`/demo`): Shows a map with all current events +2. **Search Page** (`/demo/search`): Provides advanced search functionality +3. **Events by Type** (`/demo/by-what`): Lists events grouped by their type +4. **Map by Event Type** (`/demo/map-by-what`): Shows events on a map with filtering by type +5. **Add Event** (`/demo/add`): Form for adding new events +6. **Edit Event** (`/demo/edit/{id}`): Form for editing existing events +7. **Traffic Jam Reporting** (`/demo/traffic`): Form for reporting traffic jams with geolocation + +### Traffic Jam Reporting Page + +The traffic jam reporting page (`/demo/traffic`) provides a specialized form for reporting traffic jams. Features include: + +- Button to automatically detect the user's current location using browser geolocation +- Map for selecting the location of the traffic jam +- Form fields for traffic jam details (description, severity, cause, etc.) +- Automatic reverse geocoding to determine the road/location name +- Submission to the API as a traffic.jam event type +- OpenStreetMap OAuth2 authentication to include the reporter's OSM username in the event + +#### OpenStreetMap Authentication + +The traffic jam reporting page includes OAuth2 authentication with OpenStreetMap: + +- Users can authenticate with their OpenStreetMap account +- After authentication, the user's OSM username and a link to their profile are displayed +- When submitting a traffic jam report, the OSM username is included in the event properties as `reporter:osm` +- OAuth2 configuration parameters are stored in the `.env` file: + - `CLIENT_ID`: The OAuth2 client ID for the application + - `CLIENT_SECRET`: The OAuth2 client secret for the application + - `CLIENT_AUTORIZATIONS`: The permissions requested (default: "read_prefs") + - `CLIENT_REDIRECT`: The redirect URL after authentication + ## Future Improvements -Potential future improvements for the demo page: +Potential future improvements for the demo pages: 1. Add date selection to view events from different dates -2. Add filtering options (by event type, location, etc.) +2. Add more filtering options (by event type, location, etc.) 3. Add a search box to find specific events 4. Improve the mobile experience -5. Add more interactive features to the map \ No newline at end of file +5. Add more interactive features to the map +6. Expand the traffic reporting functionality to include other traffic-related events \ No newline at end of file diff --git a/oedb/resources/demo.py b/oedb/resources/demo.py index 159b321..c6a8bfc 100644 --- a/oedb/resources/demo.py +++ b/oedb/resources/demo.py @@ -5,8 +5,10 @@ Demo resource for the OpenEventDatabase. import falcon import requests import json +import os from collections import defaultdict from oedb.utils.logging import logger +from oedb.utils.db import load_env_from_file class DemoResource: """ @@ -36,7 +38,7 @@ class DemoResource: resp.content_type = 'text/html' # Fetch the event data from the API - response = requests.get(f'http://localhost/event/{id}') + response = requests.get(f'http://api.openevent/event/{id}') if response.status_code != 200: resp.status = falcon.HTTP_404 @@ -508,6 +510,7 @@ class DemoResource:
  • /demo/search - Advanced Search
  • /demo/by-what - Events by Type
  • /demo/map-by-what - Map by Event Type
  • +
  • /demo/traffic - Report Traffic Jam
  • Search Music Events
  • Search Sport Events
  • @@ -2303,5 +2306,603 @@ class DemoResource: resp.status = falcon.HTTP_500 resp.text = f"Error: {str(e)}" + def on_get_traffic(self, req, resp): + """ + Handle GET requests to the /demo/traffic endpoint. + Returns an HTML page with a form for reporting traffic jams. + + Args: + req: The request object. + resp: The response object. + """ + logger.info("Processing GET request to /demo/traffic") + + try: + # Set content type to HTML + resp.content_type = 'text/html' + + # Load environment variables from .env file + load_env_from_file() + + # Get OAuth2 configuration parameters + client_id = os.getenv("CLIENT_ID", "") + client_secret = os.getenv("CLIENT_SECRET", "") + client_authorizations = os.getenv("CLIENT_AUTORIZATIONS", "read_prefs") + client_redirect = os.getenv("CLIENT_REDIRECT", "") + + # Check if we have an authorization code in the query parameters + auth_code = req.params.get('code', None) + auth_state = req.params.get('state', None) + + # Variables to track authentication state + is_authenticated = False + osm_username = "" + osm_user_id = "" + + # If we have an authorization code, exchange it for an access token + if auth_code: + logger.info(f"Received authorization code: {auth_code}") + + try: + # Exchange authorization code for access token + token_url = "https://www.openstreetmap.org/oauth2/token" + token_data = { + "grant_type": "authorization_code", + "code": auth_code, + "redirect_uri": client_redirect, + "client_id": client_id, + "client_secret": client_secret + } + + token_response = requests.post(token_url, data=token_data) + token_response.raise_for_status() + token_info = token_response.json() + + access_token = token_info.get("access_token") + + if access_token: + # Use access token to get user information + user_url = "https://api.openstreetmap.org/api/0.6/user/details.json" + headers = {"Authorization": f"Bearer {access_token}"} + + user_response = requests.get(user_url, headers=headers) + user_response.raise_for_status() + user_info = user_response.json() + + # Extract user information + user = user_info.get("user", {}) + osm_username = user.get("display_name", "") + osm_user_id = user.get("id", "") + + if osm_username: + is_authenticated = True + logger.info(f"User authenticated: {osm_username} (ID: {osm_user_id})") + else: + logger.error("Failed to get OSM username from user details") + else: + logger.error("Failed to get access token from token response") + except Exception as e: + logger.error(f"Error during OAuth2 token exchange: {e}") + + # Create HTML response with form + # Start with the common HTML header + html_header = f""" + + + + + + Report Traffic Jam - OpenEventDatabase + + + + + +
    + + +

    Report Traffic Jam

    + +
    +

    OpenStreetMap Authentication

    + """ + + # Add authentication section based on authentication status + if is_authenticated: + auth_section = f""" +
    +
    +

    Logged in as {osm_username}

    +

    View OSM Profile

    + + +
    +
    + """ + else: + auth_section = f""" +

    Authenticate with your OpenStreetMap account to include your username in the traffic report.

    + + """ + + # Add the rest of the HTML template + html_footer = """ +
    + + + +
    +
    + + +
    + +
    +
    + + +
    + +
    + + +
    +
    + +
    +
    + + +
    + +
    + + +
    +
    + +
    + + +
    + +
    + +
    +
    Click on the map to set the traffic jam location or use the "Get My Current Location" button
    +
    + + +
    + +
    +
    + + + + + """ + + # Concatenate the HTML parts to form the complete template + html = html_header + auth_section + html_footer + + # Set the response body and status + resp.text = html + resp.status = falcon.HTTP_200 + logger.success("Successfully processed GET request to /demo/traffic") + except Exception as e: + logger.error(f"Error processing GET request to /demo/traffic: {e}") + resp.status = falcon.HTTP_500 + resp.text = f"Error: {str(e)}" + # Create a global instance of DemoResource demo = DemoResource() \ No newline at end of file