### Setup and Run Embedded Example Project Source: https://context7.com/preset-io/embedded-example/llms.txt Instructions for setting up and running the embedded example project. This includes cloning the repository, creating a virtual environment, installing dependencies, configuring the .env file, and running the Flask development server. ```bash # Complete setup and run workflow # 1. Clone repository and navigate to directory cd embedded-example # 2. Create virtual environment python3 -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # 3. Install dependencies pip install --upgrade pip pip install -r requirements/requirements.txt # 4. Configure environment cp .env-example .env # Edit .env with your credentials and dashboard information # 5. Run the application flask --app app run --port=8080 --debug # 6. Access in browser # http://127.0.0.1:8080/ # Expected output in terminal: # * Serving Flask app 'app' # * Debug mode: on # * Running on http://127.0.0.1:8080 # * Press CTRL+C to quit ``` -------------------------------- ### Configure Preset SDK Embedding with Guest Token Refresh Source: https://github.com/preset-io/embedded-example/blob/master/README.md Demonstrates how to configure the Preset SDK to embed a dashboard, including a mechanism to refresh the guest token. This is crucial as guest tokens are short-lived (5 minutes). The example shows the `fetchGuestToken` parameter being set to an asynchronous function that retrieves a new guest token. ```javascript const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: async () => fetchGuestTokenFromBackend(), // `fetchGuestTokenFromBackend()` is a function that returns a Guest Token dashboardUiConfig: {}, }); ``` -------------------------------- ### Flask CLI Command for PEM Key Generation Source: https://context7.com/preset-io/embedded-example/llms.txt This Flask CLI command, implemented using Python and the 'click' library, generates RSA public and private key pairs. It checks for OpenSSL installation, creates a directory for keys if it doesn't exist, and generates a 2048-bit RSA key pair. The command includes an option to overwrite existing keys. It requires 'subprocess' and 'os' modules and relies on the 'openssl' binary being available in the system's PATH. ```python import subprocess import os import click # Assume KEY_DIR, PRIVATE_KEY_PATH, PUBLIC_KEY_PATH, and app are defined elsewhere @app.cli.command("generate-keys") @click.option("--overwrite", is_flag=True, help="Overwrite existing keys if they exist.") def generate_keys(overwrite=False): # Check if OpenSSL is installed try: result = subprocess.run( ["openssl", "version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, ) print(f"OpenSSL version: {result.stdout.decode().strip()}") except FileNotFoundError as exc: raise RuntimeError("OpenSSL is not installed or not available in PATH.") from exc # Ensure the output directory exists if not os.path.exists(KEY_DIR): os.makedirs(KEY_DIR) # Check if the files already exist if (os.path.exists(PRIVATE_KEY_PATH) or os.path.exists(PUBLIC_KEY_PATH)) and not overwrite: raise Exception("Key files already exist. Use --overwrite to overwrite the existing files.") # Generate the private key subprocess.run([ "openssl", "genpkey", "-algorithm", "RSA", "-out", PRIVATE_KEY_PATH, "-pkeyopt", "rsa_keygen_bits:2048", ], check=True) # Generate the public key subprocess.run([ "openssl", "rsa", "-pubout", "-in", PRIVATE_KEY_PATH, "-out", PUBLIC_KEY_PATH, ], check=True) ``` -------------------------------- ### Guest Token Generation via API Source: https://context7.com/preset-io/embedded-example/llms.txt Generates a guest token by authenticating with the Preset API and requesting a time-limited guest token for dashboard access. ```APIDOC ## GET /guest-token ### Description Generates a guest token by authenticating with the Preset API and requesting a time-limited guest token for dashboard access. This endpoint uses API tokens for authentication. ### Method GET ### Endpoint /guest-token ### Request Example ```bash curl http://localhost:8080/guest-token ``` ### Response #### Success Response (200) - **token** (string) - The generated guest token for accessing the dashboard. #### Response Example ```json { "payload": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } } ``` #### Error Response (500) - **error** (string) - Description of the error encountered during token generation. ``` -------------------------------- ### Generate PEM Keys for Authentication Source: https://github.com/preset-io/embedded-example/blob/master/README.md Commands to generate public and private PEM keys for authenticating guest users locally. Requires OpenSSL to be installed. The public key is then used in Preset Manager. ```bash flask generate-keys ``` ```bash pbcopy < keys/embedded-example-public-key.pem ``` -------------------------------- ### Guest Token Generation via PEM Key Source: https://context7.com/preset-io/embedded-example/llms.txt Generates a guest token locally using RSA private key signing, bypassing the need for API calls to Preset. ```APIDOC ## GET /guest-token-pem ### Description Generates a guest token locally using RSA private key signing. This method bypasses the need for direct API calls to Preset for authentication, relying on pre-configured PEM keys. ### Method GET ### Endpoint /guest-token-pem ### Parameters (This endpoint relies on server-side configuration of PEM keys and Key ID. No explicit request parameters are typically needed if configured correctly.) ### Request Example ```bash curl http://localhost:8080/guest-token-pem ``` ### Response #### Success Response (200) - **token** (string) - The locally generated guest token for accessing the dashboard. #### Response Example ```json { "payload": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } } ``` #### Error Response (e.g., 400, 500) - **error** (string) - Description of the error if PEM files are missing, Key ID is not configured, or signing fails. ``` -------------------------------- ### Fetch Guest Token from Backend (JavaScript) Source: https://github.com/preset-io/embedded-example/blob/master/templates/index.html Asynchronously fetches a guest token from the backend. It determines the target URL based on the 'authType' variable and handles potential errors returned in the response. This function is crucial for authenticating with the Preset API when embedding dashboards. ```javascript async function fetchGuestTokenFromBackend() { const authType = "{{ authType }}"; target_url = authType === "api" ? "/guest-token" : "/pem-key"; let response = await fetch(target_url); let data = await response.json(); if (data["error"]) { alert("ERROR: " + data.error); return null; } return data; } ``` -------------------------------- ### Configure Environment Variables for Preset Source: https://context7.com/preset-io/embedded-example/llms.txt Sets up environment variables for secure credential storage and application configuration. The .env file should be populated with API credentials, PEM key details, and dashboard settings. These variables are loaded into the application's configuration. ```bash # .env file structure (copy from .env-example) # Preset API credentials API_TOKEN=your_api_token_here API_SECRET=your_api_secret_here # PEM Key auth KEY_ID=your_key_id_here # Dashboard configuration DASHBOARD_ID=abc123-dashboard-id SUPERSET_DOMAIN=https://your-workspace.preset.io PRESET_TEAM=your-team-id WORKSPACE_SLUG=your-workspace-slug ``` -------------------------------- ### Embed Dashboard with Guest Token Source: https://github.com/preset-io/embedded-example/blob/master/README.md Embeds a dashboard using a guest token provided directly to the fetchGuestToken parameter. The token is only valid for 5 minutes and cannot be refreshed by the SDK. ```javascript const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: () => "{{myGuestToken}}", // Replace `{{myGuestToken}}` with the generated token dashboardUiConfig: {}, }); ``` -------------------------------- ### Bash Commands for Full Workflow Integration Source: https://context7.com/preset-io/embedded-example/llms.txt This set of bash commands outlines the complete workflow for setting up PEM authentication with Preset.io. It covers generating keys, copying the public key to the clipboard (macOS specific), pasting it into Preset Manager, retrieving the Key ID, configuring it in the `.env` file, and finally running the Flask app to access the token via PEM authentication. ```bash # Usage example with complete workflow # 1. Generate keys flask generate-keys # 2. Copy public key to clipboard (macOS) pbcopy < keys/embedded-example-public-key.pem # 3. Paste the public key in Preset Manager > Workspace Settings > Embedded tab # 4. Copy the Key ID from Preset Manager # 5. Add KEY_ID to .env file # KEY_ID=your_key_id_from_preset_manager # 6. Start the app with PEM authentication flask --app app run --port=8080 --debug # 7. Access with PEM auth # http://localhost:8080/?auth_type=pem ``` -------------------------------- ### Load Environment Variables in Python App Source: https://context7.com/preset-io/embedded-example/llms.txt Loads environment variables from a .env file into the Python application's configuration using the `dotenv` library. This makes sensitive information and settings accessible via `os.environ`. ```python # Loading configuration in app.py from dotenv import load_dotenv load_dotenv() app.config.from_mapping({ "API_TOKEN": os.environ.get("API_TOKEN"), "API_SECRET": os.environ.get("API_SECRET"), "DASHBOARD_ID": os.environ.get("DASHBOARD_ID"), "SUPERSET_DOMAIN": os.environ.get("SUPERSET_DOMAIN"), "PRESET_TEAM": os.environ.get("PRESET_TEAM"), "WORKSPACE_SLUG": os.environ.get("WORKSPACE_SLUG"), "PRESET_BASE_URL": URL("https://api.app.preset.io/"), "KEY_ID": os.environ.get("KEY_ID"), }) ``` -------------------------------- ### Root Endpoint - Dashboard Embedding Page Source: https://context7.com/preset-io/embedded-example/llms.txt Serves the main HTML page that embeds the Preset dashboard using the JavaScript SDK. Supports both API token and PEM key authentication. ```APIDOC ## GET / ### Description Serves the main HTML page that embeds the Preset dashboard using the JavaScript SDK. Supports authentication via API tokens (default) or PEM keys. ### Method GET ### Endpoint / ### Query Parameters - **auth_type** (string) - Optional - Specifies the authentication method to use. Accepts 'api' (default) or 'pem'. ### Request Example ```bash # Access with API authentication (default) curl http://localhost:8080/ # Access with PEM key authentication curl http://localhost:8080/?auth_type=pem ``` ### Response #### Success Response (200) Renders an HTML page with embedded dashboard. #### Response Example (HTML content of index.html) ``` -------------------------------- ### Guest Token Generation via PEM Key (Python/Flask) Source: https://context7.com/preset-io/embedded-example/llms.txt This section describes the process of generating a guest token locally using RSA private key signing. Unlike the API token method, this approach bypasses direct API calls to Preset by signing the token on the client side. The actual Python code for this functionality is not provided in the snippet but is indicated to exist. -------------------------------- ### Load Dashboard with Specific Filter State via Permalink Source: https://github.com/preset-io/embedded-example/blob/master/README.md Embeds a dashboard and loads it with a predefined filter configuration using a permalink key. Requires `dashboardId`, `supersetDomain`, and a valid `permalink_key`. ```javascript const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: async () => fetchGuestTokenFromBackend(), dashboardUiConfig: { urlParams: { "permalink_key": "aE6zJGOJK3k" // Key generated via the API with the desired filter state } } }); ``` -------------------------------- ### Embed Dashboard with Custom iframe Title Source: https://github.com/preset-io/embedded-example/blob/master/README.md Embeds a dashboard and sets a custom title for the iframe element. This can be specified using the `iframeTitle` parameter during the embed call. ```javascript const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: async () => fetchGuestTokenFromBackend(), iframeTitle: "Preset Embedded Dashboard", // optional: title for the iframe }); ``` -------------------------------- ### Embed Dashboard with Specific iframe Referrer Policy Source: https://github.com/preset-io/embedded-example/blob/master/README.md Embeds a dashboard and enforces a specific `referrerPolicy` for the iframe. This ensures the Referrer header is included in the iframe request for proper domain validation. ```javascript const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: async () => fetchGuestTokenFromBackend(), referrerPolicy: "strict-origin-when-cross-origin", }); ``` -------------------------------- ### Embed Preset Dashboard with JavaScript SDK Source: https://context7.com/preset-io/embedded-example/llms.txt JavaScript implementation to embed Preset dashboards. It fetches guest tokens from a backend endpoint and configures the dashboard UI. The SDK provides methods to interact with the embedded dashboard, such as retrieving filter states and observing filter changes. ```javascript // Complete frontend implementation from templates/index.html // 1. Define async function to fetch guest token from backend async function fetchGuestTokenFromBackend() { const authType = "api"; // or "pem" target_url = authType === "api" ? "/guest-token" : "/pem-key"; let response = await fetch(target_url); let data = await response.json(); if (data["error"]) { alert("ERROR: " + data.error); return null; } return data; } // 2. Configure and embed the dashboard const dashboardId = "abc123-dashboard-id"; const supersetDomain = "https://your-workspace.preset.io"; const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: async () => fetchGuestTokenFromBackend(), dashboardUiConfig: { hideTitle: false, hideChartControls: false, filters: { expanded: true, }, }, iframeTitle: "Preset Embedded Dashboard", referrerPolicy: "strict-origin-when-cross-origin", }); // 3. Access dashboard methods after loading myLightDashboard.then(async (dashboardElement) => { // Get current filter state const currentDataMask = await dashboardElement.getDataMask(); console.log('Current filter state:', currentDataMask); // Observe filter changes dashboardElement.observeDataMask((dataMaskConfig) => { console.log('Filter changed:', dataMaskConfig); if (dataMaskConfig.nativeFiltersChanged) { console.log('Native filters changed'); } if (dataMaskConfig.crossFiltersChanged) { console.log('Cross filters changed'); } }); }); ``` -------------------------------- ### Bash Commands for PEM Key Generation and Token Retrieval Source: https://context7.com/preset-io/embedded-example/llms.txt This section provides bash commands for interacting with the Flask application. It includes the command to generate PEM keys using the Flask CLI, with an option to overwrite existing keys. It also shows how to retrieve the generated guest token using `curl` from the `/pem-key` endpoint. The output demonstrates the expected format of generated key paths and the JWT token. ```bash # Generate PEM keys using Flask CLI command flask generate-keys # Or with overwrite flag flask generate-keys --overwrite # Expected output: # OpenSSL version: OpenSSL 1.1.1... # Private key generated at: keys/embedded-example-private-key.pem # Public key generated at: keys/embedded-example-public-key.pem # Retrieve token via curl curl http://localhost:8080/pem-key # Returns: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6InlvdXJfa2V5X2lkIn0..." ``` -------------------------------- ### Python: Apply RLS Rules with PEM Key Authentication Source: https://context7.com/preset-io/embedded-example/llms.txt Illustrates how to apply Row-Level Security (RLS) rules when using PEM key authentication for guest tokens. This method uses the 'rls_rules' key in the payload and is suitable for scenarios requiring reduced API calls. It allows specifying RLS for specific datasets or broader conditions. ```python # For PEM key authentication, use rls_rules instead payload = { "user": {"username": "john_doe", "first_name": "John", "last_name": "Doe"}, "resources": [{"type": "dashboard", "id": app.config["DASHBOARD_ID"]}], "rls_rules": [ {"dataset": 123, "clause": "region = 'North America'"}, {"clause": "department = 'Sales'"}, ], "type": "guest", "aud": app.config["WORKSPACE_SLUG"], } ``` -------------------------------- ### Embed Preset Dashboard using SDK (JavaScript) Source: https://github.com/preset-io/embedded-example/blob/master/templates/index.html Embeds a Preset dashboard into an HTML element using the Preset Embedded SDK. It requires the dashboard ID, Superset domain, and a function to fetch guest tokens. Various UI configurations and iframe properties can be customized. ```javascript const dashboardId = "{{ dashboardId }}"; const supersetDomain = "{{ supersetDomain }}"; const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), // any html element that can contain an iframe fetchGuestToken: async () => fetchGuestTokenFromBackend(), dashboardUiConfig: { hideTitle: false, // change it to `true` to hide the dashboard title hideChartControls: false, // change it to `true` to hide the chart controls (ellipses menu) filters: { expanded: true, // change it to `false` so that dashboard filters are collapsed (for vertical filter bar) }, }, iframeTitle: "Preset Embedded Dashboard", // optional: title for the iframe referrerPolicy: "strict-origin-when-cross-origin", }); ``` -------------------------------- ### Embed Dashboard with Force Refresh Source: https://github.com/preset-io/embedded-example/blob/master/README.md Embeds a dashboard and forces a data refresh on load by passing the 'force' URL parameter. This overrides cached data for charts, filters, and RLS combinations. ```javascript const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: async () => fetchGuestTokenFromBackend(), dashboardUiConfig: { urlParams: { "force": true, } } }); ``` -------------------------------- ### JavaScript: Load Dashboard with Specific Filter State Source: https://context7.com/preset-io/embedded-example/llms.txt Loads an embedded dashboard with a predefined filter state by utilizing a permalink key. This allows for consistent views and sharing of specific dashboard configurations. The 'permalink_key' URL parameter is used within the dashboard UI configuration. ```javascript const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: async () => fetchGuestTokenFromBackend(), dashboardUiConfig: { urlParams: { "permalink_key": "aE6zJGOJK3k" } } }); ``` -------------------------------- ### Retrieve Current Dashboard Filter State (Data Mask) Source: https://github.com/preset-io/embedded-example/blob/master/README.md Fetches the current data mask configuration, which includes the filter state, from an embedded dashboard instance. This method is called on the dashboard element after it has been loaded. ```javascript const dashboardElement = await myLightDashboard; // `myLightDashboard` is a promise that resolves to the dashboard instance ... const currentDataMaskConfig = await dashboardElement.getDataMask(); console.log('The current data mask configuration for the dashboard is: ', datamask); ``` -------------------------------- ### Fetch Guest Token from Backend (JavaScript) Source: https://context7.com/preset-io/embedded-example/llms.txt This JavaScript function, intended for use in `index.html`, fetches a guest token from the backend API endpoint `/guest-token`. It makes an asynchronous `fetch` request and returns the JSON response containing the guest token or an error message. This function is crucial for the frontend to obtain the necessary token for embedding dashboards. ```javascript // Frontend usage in index.html async function fetchGuestTokenFromBackend() { let response = await fetch("/guest-token"); let data = await response.json(); if (data["error"]) { alert("ERROR: " + data.error); return null; } return data; } // Expected response format // "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### JavaScript: Force Dashboard Refresh on Load Source: https://context7.com/preset-io/embedded-example/llms.txt Forces the embedded dashboard to refresh its data automatically when it loads. This is useful for ensuring users see the most up-to-date information. It is implemented by setting the 'force' URL parameter to true within the dashboard UI configuration. ```javascript const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: async () => fetchGuestTokenFromBackend(), dashboardUiConfig: { urlParams: { "force": true, } } }); ``` -------------------------------- ### Embed Dashboard with UI Configurations Source: https://github.com/preset-io/embedded-example/blob/master/README.md Embeds a dashboard with various UI configurations applied. This includes options to hide the title, chart controls, manage filter visibility and expansion, set URL parameters, and show row limit warnings. ```javascript const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: async () => fetchGuestTokenFromBackend(), dashboardUiConfig: { // dashboard UI config (all optional) hideTitle: false, // change it to `true` to hide the dashboard title hideChartControls: false, // change it to `true` to hide the chart controls (ellipses menu) filters: { expanded: true, // change it to `false` so that dashboard filters are collapsed (for vertical filter bar) visible: true, // change it to `falee` to completely hide the dashboard filter bar }, urlParams: { // URL parameters to be used with the ``{{url_param()}}`` Jinja macro param_name: "value", other_param: "value", }, showRowLimitWarning: false, // change it to `true` to show the row limit reached warning on charts }, }); ``` -------------------------------- ### Generate Guest Token via API (Python/Flask) Source: https://context7.com/preset-io/embedded-example/llms.txt This Flask route handler in `app.py` generates a guest token by first authenticating with the Preset API to obtain a JWT token, and then using that JWT to request a time-limited guest token for dashboard access. It returns the guest token as JSON or an error if the API calls fail. It relies on helper functions `authenticate_with_preset` and `fetch_guest_token` and requires Preset API credentials and configuration. ```python # Route handler in app.py @app.route("/guest-token", methods=["GET"]) def guest_token_generator(): try: jwt_token = authenticate_with_preset() guest_token = jsonify(fetch_guest_token(jwt_token)) return guest_token, 200 except requests.exceptions.HTTPError as error: return jsonify({"error": str(error)}), 500 # Helper function to authenticate with Preset API def authenticate_with_preset(): url = app.config["PRESET_BASE_URL"] / "v1/auth/" payload = {"name": app.config["API_TOKEN"], "secret": app.config["API_SECRET"]} headers = {"Content-Type": "application/json", "Accept": "application/json"} response = requests.post(url, headers=headers, json=payload, timeout=7) response.raise_for_status() return response.json()["payload"]["access_token"] # Helper function to fetch guest token def fetch_guest_token(jwt_key): url = ( app.config["PRESET_BASE_URL"] / "v1/teams" / app.config["PRESET_TEAM"] / "workspaces" / app.config["WORKSPACE_SLUG"] / "guest-token/" ) payload = { "user": {"username": "test_user", "first_name": "test", "last_name": "user"}, "resources": [{"type": "dashboard", "id": app.config["DASHBOARD_ID"]}] "rls": [] } headers = { "Authorization": f"Bearer {jwt_key}", "Accept": "application/json", "Content-Type": "application/json", } response = requests.post(url, headers=headers, json=payload, timeout=7) response.raise_for_status() return response.json()["payload"]["token"] ``` -------------------------------- ### Validate Native and Cross Filter Changes in Data Mask Source: https://github.com/preset-io/embedded-example/blob/master/README.md Processes data mask changes emitted from the dashboard, specifically checking if native filters or cross-filters have been modified. This function is used as a callback for `observeDataMask`. ```javascript function processDataMaskChange(dataMaskConfig) { console.log("Received a data mask change from the dashboard:"); if (dataMaskConfig.nativeFiltersChanged) { console.log("Native filters have changed!"); } if (dataMaskConfig.crossFiltersChanged) { console.log("Cross filters have changed!"); } console.log(dataMaskConfig); } myLightDashboard.then(dashboardElement => { dashboardElement.observeDataMask(processDataMaskChange); }); ``` -------------------------------- ### Python: Apply Row-Level Security (RLS) in Guest Token Payload Source: https://context7.com/preset-io/embedded-example/llms.txt Demonstrates how to apply Row-Level Security (RLS) rules to an embedded dashboard by including them in the guest token payload. This allows for granular data access control based on user attributes or specific conditions. It shows applying RLS to a specific dataset or all datasets. ```python # Apply Row-Level Security (RLS) in guest token payload # In app.py fetch_guest_token function payload = { "user": {"username": "john_doe", "first_name": "John", "last_name": "Doe"}, "resources": [{"type": "dashboard", "id": app.config["DASHBOARD_ID"]}], "rls": [ # Apply RLS to a specific dataset {"dataset": 123, "clause": "region = 'North America'"}, # Apply RLS to all datasets {"clause": "user_id = 'john_doe'"}, ] } ``` -------------------------------- ### Embed Dashboard with Custom iframe Sandbox Attributes Source: https://github.com/preset-io/embedded-example/blob/master/README.md Embeds a dashboard and adds custom sandbox attributes to the iframe element to control its security restrictions. The `allow-popups-to-escape-sandbox` attribute is included to permit links to open in new tabs. ```javascript const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: async () => fetchGuestTokenFromBackend(), iframeSandboxExtras: ['allow-popups-to-escape-sandbox'], }); ``` -------------------------------- ### Serve Dashboard Embedding Page (Python/Flask) Source: https://context7.com/preset-io/embedded-example/llms.txt This route handler in `app.py` serves the main HTML page for embedding Preset dashboards. It supports both API and PEM key authentication methods, rendering the `index.html` template with necessary dashboard and Superset domain configurations. It requires dashboard ID, Superset domain, and optionally authentication type. ```python # Route handler in app.py @app.route("/") def main_page(): auth_type = request.args.get("auth_type", "api") if auth_type == "pem": if not os.path.exists(PRIVATE_KEY_PATH) or not os.path.exists(PUBLIC_KEY_PATH): raise FileNotFoundError("PEM key files not found.") if app.config["KEY_ID"] is None: raise KeyError("Key ID not defined in environment variables.") return render_template( "index.html", dashboardId=app.config["DASHBOARD_ID"], supersetDomain=app.config["SUPERSET_DOMAIN"], authType=auth_type, ) return render_template( "index.html", dashboardId=app.config["DASHBOARD_ID"], supersetDomain=app.config["SUPERSET_DOMAIN"], authType="api", ) ``` -------------------------------- ### Customize Guest Token Permissions with PEM Key Source: https://github.com/preset-io/embedded-example/blob/master/README.md This snippet demonstrates how to configure guest token permissions when generating tokens using a PEM key. Similar to API generation, it allows defining user information, accessible resources, and RLS rules. Additionally, it includes token type and audience specification for PEM-based authentication. ```python { "user": { "username": "test_user", "first_name": "test", "last_name": "user" }, "resources": [ { "type": "dashboard", "id": dashboard_id } ], "rls_rules": [ # Apply an RLS to a specific dataset # { "dataset": dataset_id, "clause": "column = 'filter'" }, # Apply an RLS to all datasets # { "clause": "column = 'filter'" }, ], "type": "guest", "aud": workspace_slug, } ``` -------------------------------- ### Automatically Emit Dashboard Filter State Changes Source: https://github.com/preset-io/embedded-example/blob/master/README.md Configures the embedded dashboard to emit filter state changes automatically. This is useful for monitoring filter usage. It requires setting `emitDataMasks` to `true` and observing changes via `observeDataMask`. ```javascript const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: async () => fetchGuestTokenFromBackend(), dashboardUiConfig: { emitDataMasks: true, // When set to true, the dashboard emits filter state changes } }); function processDataMaskChange(dataMaskConfig) { console.log("Received a data mask change from the dashboard:"); console.log(dataMaskConfig); } myLightDashboard.then(dashboardElement => { dashboardElement.observeDataMask(processDataMaskChange); }); ``` -------------------------------- ### Python Flask Route Handler for JWT Guest Token Source: https://context7.com/preset-io/embedded-example/llms.txt This Python code defines a Flask route handler that generates a JWT guest token. It reads a private key from a file, constructs a payload with user and resource information, and then encodes the JWT using the RS256 algorithm. The encoded JWT is returned as a JSON string. It depends on the 'jwt' library and assumes the private key path and workspace configuration are available. ```python import json import jwt # Assume PRIVATE_KEY_PATH, app, and other configurations are defined elsewhere @app.route("/pem-key", methods=["GET"]) def get_guest_token_using_pem_key(): with open(PRIVATE_KEY_PATH, "r", encoding="utf-8") as file: private_key = file.read() payload = { "user": {"username": "test_user", "first_name": "test", "last_name": "user"}, "resources": [{"type": "dashboard", "id": app.config["DASHBOARD_ID"]}], "rls_rules": [], "type": "guest", "aud": app.config["WORKSPACE_SLUG"], } encoded_jwt = jwt.encode( payload, private_key, algorithm="RS256", headers={"kid": app.config["KEY_ID"]}, ) return json.dumps(encoded_jwt) ``` -------------------------------- ### JavaScript: Enable Data Mask Emission for Filter Tracking Source: https://context7.com/preset-io/embedded-example/llms.txt Enables the emission of data masks, which can be used for tracking filter interactions and changes within the embedded dashboard. This feature is activated by setting the 'emitDataMasks' option to true in the dashboard UI configuration. ```javascript const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: async () => fetchGuestTokenFromBackend(), dashboardUiConfig: { emitDataMasks: true, } }); ``` -------------------------------- ### Access Dashboard Embedding Page (Shell) Source: https://context7.com/preset-io/embedded-example/llms.txt These `curl` commands demonstrate how to access the main dashboard embedding page served by the Flask application. The first command accesses the page using the default API authentication, while the second command specifies PEM key authentication by appending `?auth_type=pem` to the URL. ```bash # Access with API authentication (default) curl http://localhost:8080/ # Access with PEM key authentication curl http://localhost:8080/?auth_type=pem ``` -------------------------------- ### JavaScript: Custom Iframe Sandbox Attributes for Link Handling Source: https://context7.com/preset-io/embedded-example/llms.txt Configures custom sandbox attributes for the iframe embedding the dashboard, enhancing security and controlling interactions, particularly for handling links. The 'allow-popups-to-escape-sandbox' attribute is added to the 'iframeSandboxExtras' array to manage popup behavior. ```javascript const myLightDashboard = presetSdk.embedDashboard({ id: dashboardId, supersetDomain: supersetDomain, mountPoint: document.getElementById("dashboard-container"), fetchGuestToken: async () => fetchGuestTokenFromBackend(), iframeSandboxExtras: ['allow-popups-to-escape-sandbox'], }); ``` -------------------------------- ### Customize Guest Token Permissions via API Source: https://github.com/preset-io/embedded-example/blob/master/README.md This snippet shows how to configure guest token permissions when generating tokens via the API. It allows specifying user details, accessible resources (like dashboards), and Row-Level Security (RLS) rules for datasets. RLS rules can be applied to specific datasets or all datasets within the workspace. ```python { "user": { "username": "test_user", "first_name": "test", "last_name": "user" }, "resources": [ { "type": "dashboard", "id": dashboard_id, } ], "rls": [ # Apply an RLS to a specific dataset # { "dataset": dataset_id, "clause": "column = 'filter'" }, # Apply an RLS to all datasets # { "clause": "column = 'filter'" }, ] } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.