Download src/api/push_notifications.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/api/push_notifications.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/api/push_notifications.py
-
curl -L -o push_notifications.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/api/push_notifications.py
14.1 kB
| """ | |
| Push Notification API | |
| Endpoints for Web Push subscription management and VAPID key distribution. | |
| Clinical Context: Critical alert delivery when app not in foreground | |
| Standards: W3C Push API, VAPID (RFC 8292) | |
| Performance: <100ms for subscription operations | |
| Security: Tenant-isolated, HIPAA-compliant (minimal PHI in payload) | |
| Phase 1 Implementation - January 2026 | |
| """ | |
| from __future__ import annotations | |
| from datetime import datetime, timezone | |
| from typing import Optional, List, Dict, Any | |
| from uuid import UUID | |
| import os | |
| from fastapi import APIRouter, Depends, HTTPException, Query | |
| from pydantic import BaseModel, ConfigDict, ConfigDict, Field | |
| import structlog | |
| from services.push_notifications import ( | |
| VAPIDKeyManager, | |
| PushSubscriptionManager, | |
| PushSubscription, | |
| PushNotificationService, | |
| ) | |
| from core.dependencies import get_current_user, CurrentUser | |
| from core.multitenancy.tenant import get_tenant_id | |
| logger = structlog.get_logger() | |
| router = APIRouter(prefix="/api/v1/push", tags=["Push Notifications"]) | |
| # ============================================================================ | |
| # SINGLETON MANAGERS (initialized once at startup) | |
| # ============================================================================ | |
| # Load VAPID keys from environment or generate new ones | |
| _vapid_private_key = os.getenv("VAPID_PRIVATE_KEY") | |
| _vapid_public_key = os.getenv("VAPID_PUBLIC_KEY") | |
| _vapid_contact_email = os.getenv("VAPID_CONTACT_EMAIL", "alerts@yazcare.com") | |
| vapid_manager = VAPIDKeyManager( | |
| private_key=_vapid_private_key, public_key=_vapid_public_key, contact_email=_vapid_contact_email | |
| ) | |
| subscription_manager = PushSubscriptionManager() | |
| push_service = PushNotificationService( | |
| vapid_manager=vapid_manager, subscription_manager=subscription_manager | |
| ) | |
| # ============================================================================ | |
| # PYDANTIC SCHEMAS | |
| # ============================================================================ | |
| class VAPIDPublicKeyResponse(BaseModel): | |
| """VAPID public key for client subscription.""" | |
| public_key: str = Field(..., description="Base64 encoded VAPID public key") | |
| contact_email: str = Field(..., description="Contact email for push service") | |
| class PushSubscriptionRequest(BaseModel): | |
| """Push subscription registration request.""" | |
| endpoint: str = Field(..., description="Push service endpoint URL") | |
| p256dh: str = Field(..., description="Client public key (base64)") | |
| auth: str = Field(..., description="Client auth secret (base64)") | |
| user_agent: Optional[str] = Field(None, description="User agent string") | |
| model_config = ConfigDict( | |
| json_schema_extra={ | |
| "examples": [ | |
| { | |
| "endpoint": "https://fcm.googleapis.com/fcm/send/example...", | |
| "p256dh": "BNcRdreALRFXTkOOUHK1EtK2wtaz5Ry4YfYCA_0...", | |
| "auth": "tBHItJI5svbpez7KI4...", | |
| "user_agent": "Mozilla/5.0 ...", | |
| } | |
| ] | |
| } | |
| ) | |
| class PushSubscriptionResponse(BaseModel): | |
| """Push subscription response.""" | |
| success: bool | |
| subscription_id: str | |
| message: str | |
| class UnsubscribeRequest(BaseModel): | |
| """Push unsubscription request.""" | |
| endpoint: str = Field(..., description="Push service endpoint to remove") | |
| class TestNotificationRequest(BaseModel): | |
| """Test notification request.""" | |
| title: Optional[str] = Field("YAZ Care Test", description="Notification title") | |
| body: Optional[str] = Field("This is a test notification", description="Notification body") | |
| notification_type: Optional[str] = Field( | |
| "info", description="Type: critical, urgent, routine, info" | |
| ) | |
| model_config = ConfigDict( | |
| json_schema_extra={ | |
| "examples": [ | |
| { | |
| "title": "Test Alert", | |
| "body": "This is a test push notification from YAZ Care", | |
| "notification_type": "info", | |
| } | |
| ] | |
| } | |
| ) | |
| class TestNotificationResponse(BaseModel): | |
| """Test notification response.""" | |
| success: bool | |
| delivered_to: int | |
| failed: int | |
| message: str | |
| class SubscriptionStatus(BaseModel): | |
| """Subscription status for a user.""" | |
| subscribed: bool | |
| subscription_count: int | |
| endpoints: List[str] | |
| # ============================================================================ | |
| # VAPID PUBLIC KEY ENDPOINT | |
| # ============================================================================ | |
| async def get_vapid_public_key(): | |
| """ | |
| Get VAPID public key for push subscription. | |
| This endpoint is public (no auth required) as the client needs | |
| the public key before authentication to request push permission. | |
| Returns: | |
| VAPID public key and contact email | |
| """ | |
| return VAPIDPublicKeyResponse( | |
| public_key=vapid_manager.get_public_key(), contact_email=vapid_manager.contact_email | |
| ) | |
| # ============================================================================ | |
| # SUBSCRIPTION MANAGEMENT ENDPOINTS | |
| # ============================================================================ | |
| async def subscribe_push(request: PushSubscriptionRequest, current_user=Depends(get_current_user)): | |
| """ | |
| Register push subscription. | |
| Registers the client's push subscription with the server. | |
| Supports multiple devices per user. | |
| Args: | |
| request: Push subscription details from browser | |
| current_user: Authenticated user | |
| Returns: | |
| Subscription confirmation | |
| """ | |
| try: | |
| # Get tenant from user | |
| tenant_id = getattr(current_user, "tenant_id", "default") | |
| user_id = str(getattr(current_user, "id", current_user.get("id", "unknown"))) | |
| subscription = PushSubscription( | |
| user_id=user_id, | |
| tenant_id=str(tenant_id), | |
| endpoint=request.endpoint, | |
| p256dh=request.p256dh, | |
| auth=request.auth, | |
| user_agent=request.user_agent, | |
| ) | |
| success = await subscription_manager.subscribe(subscription) | |
| if success: | |
| logger.info( | |
| "push_subscription_created", | |
| user_id=user_id, | |
| tenant_id=str(tenant_id), | |
| endpoint=request.endpoint[:50], | |
| ) | |
| return PushSubscriptionResponse( | |
| success=True, | |
| subscription_id=f"{user_id}-{hash(request.endpoint) % 10000}", | |
| message="Successfully subscribed to push notifications", | |
| ) | |
| else: | |
| raise HTTPException(status_code=500, detail="Failed to register subscription") | |
| except Exception as e: | |
| logger.error("push_subscription_failed", error=str(e)) | |
| raise HTTPException(status_code=500, detail=f"Subscription failed: {str(e)}") | |
| async def unsubscribe_push(request: UnsubscribeRequest, current_user=Depends(get_current_user)): | |
| """ | |
| Unregister push subscription. | |
| Removes a specific push subscription endpoint for the user. | |
| Args: | |
| request: Endpoint to unsubscribe | |
| current_user: Authenticated user | |
| Returns: | |
| Unsubscription confirmation | |
| """ | |
| try: | |
| user_id = str(getattr(current_user, "id", current_user.get("id", "unknown"))) | |
| success = await subscription_manager.unsubscribe(user_id=user_id, endpoint=request.endpoint) | |
| if success: | |
| logger.info( | |
| "push_subscription_removed", user_id=user_id, endpoint=request.endpoint[:50] | |
| ) | |
| return PushSubscriptionResponse( | |
| success=True, | |
| subscription_id=f"{user_id}-removed", | |
| message="Successfully unsubscribed from push notifications", | |
| ) | |
| else: | |
| return PushSubscriptionResponse( | |
| success=False, subscription_id="", message="No matching subscription found" | |
| ) | |
| except Exception as e: | |
| logger.error("push_unsubscription_failed", error=str(e)) | |
| raise HTTPException(status_code=500, detail=f"Unsubscription failed: {str(e)}") | |
| async def get_subscription_status(current_user=Depends(get_current_user)): | |
| """ | |
| Get push subscription status. | |
| Returns the user's current subscription status including | |
| number of subscribed devices. | |
| Args: | |
| current_user: Authenticated user | |
| Returns: | |
| Subscription status | |
| """ | |
| try: | |
| user_id = str(getattr(current_user, "id", current_user.get("id", "unknown"))) | |
| subscriptions = await subscription_manager.get_subscriptions(user_id) | |
| return SubscriptionStatus( | |
| subscribed=len(subscriptions) > 0, | |
| subscription_count=len(subscriptions), | |
| endpoints=[s.endpoint[:50] + "..." for s in subscriptions], | |
| ) | |
| except Exception as e: | |
| logger.error("push_status_check_failed", error=str(e)) | |
| raise HTTPException(status_code=500, detail=f"Status check failed: {str(e)}") | |
| # ============================================================================ | |
| # TEST NOTIFICATION ENDPOINT | |
| # ============================================================================ | |
| async def send_test_notification( | |
| request: TestNotificationRequest, current_user=Depends(get_current_user) | |
| ): | |
| """ | |
| Send test push notification. | |
| Sends a test notification to all registered devices for the user. | |
| Useful for verifying push notification setup. | |
| Args: | |
| request: Notification content | |
| current_user: Authenticated user | |
| Returns: | |
| Delivery results | |
| """ | |
| try: | |
| user_id = str(getattr(current_user, "id", current_user.get("id", "unknown"))) | |
| # Build notification data | |
| notification_data = { | |
| "type": request.notification_type, | |
| "alertId": f"test-{datetime.now(timezone.utc).timestamp()}", | |
| "url": "/apps/dashboard", | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| } | |
| # Define actions based on type | |
| actions = [] | |
| if request.notification_type == "critical": | |
| actions = [ | |
| {"action": "acknowledge", "title": "Acknowledge"}, | |
| {"action": "view", "title": "View Details"}, | |
| ] | |
| else: | |
| actions = [ | |
| {"action": "view", "title": "View"}, | |
| {"action": "dismiss", "title": "Dismiss"}, | |
| ] | |
| result = await push_service.send_notification( | |
| user_id=user_id, | |
| title=request.title, | |
| body=request.body, | |
| data=notification_data, | |
| actions=actions, | |
| tag=f"test-{request.notification_type}", | |
| require_interaction=request.notification_type == "critical", | |
| ) | |
| return TestNotificationResponse( | |
| success=result.get("delivered", 0) > 0, | |
| delivered_to=result.get("delivered", 0), | |
| failed=result.get("failed", 0), | |
| message=f"Notification sent to {result.get('delivered', 0)} device(s)", | |
| ) | |
| except Exception as e: | |
| logger.error("test_notification_failed", error=str(e)) | |
| return TestNotificationResponse( | |
| success=False, delivered_to=0, failed=1, message=f"Failed to send: {str(e)}" | |
| ) | |
| # ============================================================================ | |
| # ADMIN ENDPOINTS | |
| # ============================================================================ | |
| async def cleanup_expired_subscriptions(current_user=Depends(get_current_user)): | |
| """ | |
| Cleanup expired subscriptions. | |
| Removes subscriptions that haven't been used in 90+ days. | |
| Admin-only endpoint. | |
| Args: | |
| current_user: Authenticated admin user | |
| Returns: | |
| Cleanup results | |
| """ | |
| # TODO: Add admin role check | |
| # if not hasattr(current_user, 'is_admin') or not current_user.is_admin: | |
| # raise HTTPException(status_code=403, detail="Admin access required") | |
| try: | |
| removed_count = await subscription_manager.cleanup_expired() | |
| logger.info("push_subscriptions_cleanup_completed", removed_count=removed_count) | |
| return { | |
| "success": True, | |
| "removed_count": removed_count, | |
| "message": f"Removed {removed_count} expired subscription(s)", | |
| } | |
| except Exception as e: | |
| logger.error("push_cleanup_failed", error=str(e)) | |
| raise HTTPException(status_code=500, detail=f"Cleanup failed: {str(e)}") | |
| async def push_health_check(): | |
| """ | |
| Push notification health check. | |
| Returns: | |
| Service health status | |
| """ | |
| return { | |
| "status": "healthy", | |
| "service": "push_notifications", | |
| "vapid_configured": bool(vapid_manager.public_key), | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| } | |