Spaces:
Sleeping
Sleeping
File size: 5,912 Bytes
59a1470 | 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 | """λΈλΌμ°μ Web Push(λ³΅μ½ μλ¦Ό) API.
VAPID ν€λ μ½λμ νλμ½λ©νμ§ λ§κ³ νκ²½λ³μλ‘ μ£Όμ
νλ€.
`/Users/apple/Documents/GitHub/pill-advisor/.env` (λ° Render λμ보λ)μ μλλ₯Ό μΆκ°:
VAPID_PUBLIC_KEY=... # base64url νμ P-256 곡κ°ν€ (μλ λͺ
λ ΉμΌλ‘ μμ±)
VAPID_PRIVATE_KEY=... # PEM νμ κ°μΈν€ (μλ λͺ
λ ΉμΌλ‘ μμ±)
VAPID_SUBJECT=mailto:beomjinkim2000@gmail.com # (μ ν) νΈμ μλΉμ€ μ°λ½μ²
ν€ μμ± (base64url 곡κ°ν€ μΆλ ₯):
cd web/backend && pip install pywebpush cryptography
python3 -c "
from py_vapid import Vapid
import base64
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
v = Vapid()
v.generate_keys()
raw = v.public_key.public_bytes(Encoding.X962, PublicFormat.UncompressedPoint)
print('VAPID_PRIVATE_KEY:', v.serialize_private_key().decode().strip())
print('VAPID_PUBLIC_KEY:', base64.urlsafe_b64encode(raw).rstrip(b'=').decode())
"
μ£Όμ: PushManager.subscribe(applicationServerKey)λ base64url νμμ raw P-256 곡κ°ν€λ₯Ό
μꡬνλ€. PEM νμμ λ£μΌλ©΄ ꡬλ
μ λ°νμ μλ¬κ° λ°μνλ€.
VAPID_PUBLIC_KEY νκ²½λ³μμλ λ°λμ base64url νμ κ°μ λ£μ κ².
"""
import base64
import json
import os
from typing import Any
import supabase as sb
from fastapi import APIRouter, Header, HTTPException
from pydantic import BaseModel
from services.auth import auth as _auth
router = APIRouter()
VAPID_PRIVATE_KEY = os.environ.get("VAPID_PRIVATE_KEY", "")
VAPID_SUBJECT = os.environ.get("VAPID_SUBJECT", "mailto:beomjinkim2000@gmail.com")
# PEM νμμΌλ‘ λ€μ΄μ¨ κ²½μ° base64urlλ‘ μλ λ³ν (μλͺ»λ νκ²½λ³μ μ€μ μ λν λ°©μ΄)
_raw_public_key = os.environ.get("VAPID_PUBLIC_KEY", "")
def _normalize_public_key(key: str) -> str:
"""PEM λλ base64url 곡κ°ν€λ₯Ό λΈλΌμ°μ μ© base64url(unpadded)λ‘ μ κ·ν."""
if not key:
return ""
if key.startswith("-----"):
try:
from cryptography.hazmat.primitives.serialization import (
Encoding,
PublicFormat,
load_pem_public_key,
)
pub = load_pem_public_key(key.encode())
raw = pub.public_bytes(Encoding.X962, PublicFormat.UncompressedPoint)
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
except Exception:
return key
return key
VAPID_PUBLIC_KEY = _normalize_public_key(_raw_public_key)
class PushKeys(BaseModel):
p256dh: str
auth: str
class SubscribeRequest(BaseModel):
endpoint: str
keys: PushKeys
@router.get("/push/public-key")
async def get_public_key() -> dict[str, str]:
"""νλ‘ νΈκ° PushManager.subscribe(applicationServerKey)μ μ¬μ©ν VAPID 곡κ°ν€(base64url)."""
if not VAPID_PUBLIC_KEY:
raise HTTPException(status_code=503, detail="νΈμ μλ¦Όμ΄ μ€μ λμ§ μμμ΅λλ€.")
return {"public_key": VAPID_PUBLIC_KEY}
@router.post("/push/subscribe")
async def subscribe(
data: SubscribeRequest,
authorization: str = Header(...),
) -> dict[str, Any]:
"""λΈλΌμ°μ ꡬλ
μ 보λ₯Ό μ μ₯(λλ κ°±μ )νλ€. (user_id, endpoint) λ¨μλ‘ λ©±λ±."""
db, user_id = _auth(authorization)
result = (
db.table("push_subscriptions")
.upsert(
{
"user_id": user_id,
"endpoint": data.endpoint,
"p256dh": data.keys.p256dh,
"auth_key": data.keys.auth,
},
on_conflict="user_id,endpoint",
)
.execute()
)
if not result.data:
raise HTTPException(status_code=500, detail="ꡬλ
μ μ₯ μ€ν¨")
return {"subscribed": True, "id": result.data[0]["id"]}
@router.post("/push/test")
async def send_test(authorization: str = Header(...)) -> dict[str, Any]:
"""λ³ΈμΈμ λͺ¨λ ꡬλ
λ¨λ§λ‘ ν
μ€νΈ μλ¦Όμ μ μ‘νλ€."""
if not VAPID_PRIVATE_KEY:
raise HTTPException(status_code=503, detail="νΈμ μλ¦Όμ΄ μ€μ λμ§ μμμ΅λλ€.")
db, user_id = _auth(authorization)
subs = (
db.table("push_subscriptions").select("*").eq("user_id", user_id).execute()
)
rows = subs.data or []
if not rows:
raise HTTPException(status_code=404, detail="λ±λ‘λ μλ¦Ό ꡬλ
μ΄ μμ΅λλ€.")
payload = json.dumps(
{
"title": "λ³΅μ½ μλ¦Ό ν
μ€νΈ",
"body": "μλ¦Όμ΄ μ μμ μΌλ‘ μ€μ λμμ΄μ! π",
"url": "/home",
}
)
sent, failed = 0, 0
for row in rows:
if _send_web_push(row, payload, db, user_id):
sent += 1
else:
failed += 1
return {"sent": sent, "failed": failed}
def _send_web_push(
row: dict, payload: str, db: sb.Client, user_id: str
) -> bool:
"""λ¨μΌ ꡬλ
μΌλ‘ μΉ νΈμλ₯Ό μ μ‘νλ€. λ§λ£(404/410) ꡬλ
μ μμ νλ€."""
# pywebpush λ μ ν μμ‘΄μ± β λ―Έμ€μΉ νκ²½μμ import μ μ± κΈ°λμ΄ λ§νμ§ μλλ‘ μ§μ° import.
from pywebpush import WebPushException, webpush
subscription_info = {
"endpoint": row["endpoint"],
"keys": {"p256dh": row["p256dh"], "auth": row["auth_key"]},
}
try:
webpush(
subscription_info=subscription_info,
data=payload,
vapid_private_key=VAPID_PRIVATE_KEY,
vapid_claims={"sub": VAPID_SUBJECT},
)
return True
except WebPushException as e:
status = getattr(getattr(e, "response", None), "status_code", None)
if status in (404, 410):
db.table("push_subscriptions").delete().eq("user_id", user_id).eq(
"endpoint", row["endpoint"]
).execute()
return False
except Exception:
return False
|