-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathfcm.py
More file actions
61 lines (53 loc) · 2.25 KB
/
fcm.py
File metadata and controls
61 lines (53 loc) · 2.25 KB
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
import logging
from fastapi import APIRouter, Depends, HTTPException
from wps_shared.auth import asa_authentication_required, audit_asa
from wps_shared.db.crud.fcm import (
get_device_by_device_id,
save_device_token,
update_device_token_is_active,
)
from wps_shared.db.database import get_async_write_session_scope
from wps_shared.db.models.fcm import DeviceToken
from wps_shared.utils.time import get_utc_now
from app.fcm.schema import DeviceRequestResponse, RegisterDeviceRequest, UnregisterDeviceRequest
logger = logging.getLogger(__name__)
router = APIRouter(
prefix="/device",
dependencies=[Depends(asa_authentication_required), Depends(audit_asa)],
)
@router.post("/register")
async def register_device(request: RegisterDeviceRequest):
"""
Upsert a device token for a device_id.
"""
logger.info("/device/register")
async with get_async_write_session_scope() as session:
existing = await get_device_by_device_id(session, request.device_id)
if existing:
existing.is_active = True
existing.token = request.token
existing.updated_at = get_utc_now()
logger.info(f"Updated existing DeviceInfo record for token: {request.token}")
else:
device_token = DeviceToken(
user_id=request.user_id,
device_id=request.device_id,
token=request.token,
platform=request.platform,
is_active=True,
)
save_device_token(session, device_token)
logger.info("Successfully created new DeviceToken record.")
return DeviceRequestResponse(success=True)
@router.post("/unregister")
async def unregister_device(request: UnregisterDeviceRequest):
"""
Mark a token inactive (e.g., user logged out or uninstalled).
"""
logger.info("/device/unregister")
async with get_async_write_session_scope() as session:
success = await update_device_token_is_active(session, request.token, False)
if not success:
logger.error(f"Could not find a record matching the provided token: {request.token}")
raise HTTPException(status_code=404, detail=f"Token not found: {request.token}")
return DeviceRequestResponse(success=True)