Spaces:
Paused

File size: 14,054 Bytes
d22e0e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091ca1d
d22e0e4
 
 
 
 
c85f9e9
d22e0e4
 
 
 
 
 
 
383d839
d22e0e4
383d839
d22e0e4
 
 
 
383d839
d22e0e4
 
 
 
 
 
 
 
 
 
 
 
383d839
d22e0e4
 
 
 
 
383d839
d22e0e4
 
 
 
 
 
 
383d839
d22e0e4
 
383d839
d22e0e4
 
 
 
 
 
383d839
d22e0e4
 
 
 
383d839
 
 
 
 
 
 
 
 
 
 
 
 
d22e0e4
 
 
 
383d839
d22e0e4
 
 
 
 
 
 
383d839
d22e0e4
 
 
 
 
383d839
d22e0e4
 
383d839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d22e0e4
 
 
 
383d839
d22e0e4
 
 
 
 
 
 
 
383d839
d22e0e4
 
 
 
 
 
 
 
 
383d839
d22e0e4
 
 
 
383d839
d22e0e4
 
 
 
383d839
d22e0e4
 
383d839
d22e0e4
 
 
 
383d839
d22e0e4
 
 
 
 
 
 
383d839
d22e0e4
 
 
 
383d839
d22e0e4
383d839
d22e0e4
 
383d839
d22e0e4
 
383d839
d22e0e4
 
 
383d839
d22e0e4
 
 
 
 
383d839
 
 
d22e0e4
 
 
 
 
 
383d839
d22e0e4
383d839
d22e0e4
383d839
d22e0e4
 
 
 
 
383d839
d22e0e4
383d839
d22e0e4
 
 
383d839
d22e0e4
 
383d839
 
d22e0e4
383d839
 
d22e0e4
 
 
 
 
 
383d839
d22e0e4
383d839
d22e0e4
 
383d839
d22e0e4
383d839
d22e0e4
 
 
383d839
d22e0e4
 
 
 
383d839
 
 
 
d22e0e4
 
383d839
d22e0e4
383d839
d22e0e4
 
 
383d839
d22e0e4
 
 
383d839
d22e0e4
383d839
d22e0e4
383d839
 
d22e0e4
 
 
 
 
 
383d839
d22e0e4
383d839
d22e0e4
 
383d839
d22e0e4
 
383d839
d22e0e4
 
383d839
d22e0e4
 
 
 
383d839
 
d22e0e4
383d839
d22e0e4
 
 
383d839
d22e0e4
383d839
d22e0e4
383d839
 
d22e0e4
 
 
 
 
 
383d839
d22e0e4
 
 
 
383d839
d22e0e4
 
383d839
d22e0e4
 
 
383d839
d22e0e4
 
383d839
d22e0e4
 
 
383d839
d22e0e4
 
 
 
383d839
 
d22e0e4
 
 
091ca1d
d22e0e4
383d839
d22e0e4
383d839
d22e0e4
 
 
 
 
383d839
d22e0e4
 
 
 
383d839
d22e0e4
383d839
d22e0e4
 
 
 
 
 
 
383d839
d22e0e4
383d839
d22e0e4
 
 
 
383d839
d22e0e4
383d839
d22e0e4
383d839
d22e0e4
383d839
d22e0e4
 
 
 
 
 
 
383d839
d22e0e4
 
 
383d839
d22e0e4
383d839
d22e0e4
 
383d839
d22e0e4
 
383d839
d22e0e4
 
383d839
d22e0e4
 
 
 
 
 
383d839
d22e0e4
 
383d839
 
 
d22e0e4
 
 
383d839
d22e0e4
383d839
d22e0e4
383d839
 
d22e0e4
 
383d839
d22e0e4
 
 
383d839
d22e0e4
 
 
 
 
 
 
383d839
d22e0e4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
"""
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
# ============================================================================


@router.get(
    "/vapid-public-key",
    response_model=VAPIDPublicKeyResponse,
    summary="Get VAPID public key",
    description="Get the VAPID public key for client-side push subscription",
)
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
# ============================================================================


@router.post(
    "/subscribe",
    response_model=PushSubscriptionResponse,
    summary="Subscribe to push notifications",
    description="Register push subscription for authenticated user",
)
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)}")


@router.post(
    "/unsubscribe",
    response_model=PushSubscriptionResponse,
    summary="Unsubscribe from push notifications",
    description="Remove push subscription for authenticated user",
)
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)}")


@router.get(
    "/status",
    response_model=SubscriptionStatus,
    summary="Get subscription status",
    description="Check push notification subscription status for current user",
)
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
# ============================================================================


@router.post(
    "/test",
    response_model=TestNotificationResponse,
    summary="Send test notification",
    description="Send a test push notification to all user's devices",
)
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
# ============================================================================


@router.post(
    "/admin/cleanup",
    summary="Cleanup expired subscriptions",
    description="Remove expired push subscriptions (admin only)",
)
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)}")


@router.get("/health", summary="Health check", description="Check push notification service health")
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(),
    }