/** * Example: Authenticated Streaming Handler * * This example shows how to use authentication with streaming handlers. * Works with any Flink auth plugin (JWT, BankID, OAuth, etc.) */ import { StreamHandler, StreamingRouteProps } from "@flink-app/streaming-plugin"; import { FlinkContext } from "@flink-app/flink"; // Route configuration with permissions export const Route: StreamingRouteProps = { path: "/admin/live-metrics", format: "sse", skipAutoRegister: true, permissions: ["admin"], // Only users with 'admin' role can access }; interface MetricEvent { metric: string; value: number; timestamp: number; userId: string; } /** * Authenticated streaming handler * Only accessible to users with 'admin' permission */ const GetLiveMetrics: StreamHandler = async ({ req, stream }) => { // req.user is populated by the auth plugin after successful authentication const userId = (req as any).user?.userId || "unknown"; console.log(`Admin user ${userId} connected to live metrics stream`); let count = 0; const maxMetrics = 20; // Stream metrics every second const interval = setInterval(() => { if (!stream.isOpen() || count >= maxMetrics) { clearInterval(interval); stream.end(); console.log(`User ${userId} disconnected from metrics stream`); return; } // Send metric with user context stream.write({ metric: "cpu_usage", value: Math.random() * 100, timestamp: Date.now(), userId, }); count++; }, 1000); }; export default GetLiveMetrics; /** * CLIENT USAGE: * * ```typescript * // Must include authentication header (depends on your auth plugin) * const eventSource = new EventSource('/admin/live-metrics', { * headers: { * 'Authorization': 'Bearer your-jwt-token' * } * }); * * eventSource.onmessage = (event) => { * const metric = JSON.parse(event.data); * console.log(`Metric from user ${metric.userId}:`, metric); * }; * * eventSource.onerror = (error) => { * console.error('Authentication failed or connection lost'); * }; * ``` * * Note: EventSource API doesn't support custom headers in browsers. * For authenticated SSE, you may need to: * 1. Pass token as query parameter: `/admin/live-metrics?token=...` * 2. Use cookie-based authentication * 3. Use Fetch API with ReadableStream instead of EventSource */