Spaces:
Running

andervier commited on
Commit
c924ee5
Β·
1 Parent(s): dbdd5c5

feat: add Firebase App Check verification + EUR rate

Browse files
Files changed (2) hide show
  1. main.py +47 -15
  2. requirements.txt +1 -0
main.py CHANGED
@@ -1,8 +1,10 @@
1
- from fastapi import FastAPI
2
  from fastapi.middleware.cors import CORSMiddleware
3
  import httpx
4
  import asyncio
5
  import time
 
 
6
 
7
  app = FastAPI(title="Tazas API", version="1.0.0")
8
 
@@ -13,12 +15,38 @@ app.add_middleware(
13
  allow_headers=["*"],
14
  )
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  # ──────────────────────────────────────────────
17
  # Cache simple en memoria
18
  # ──────────────────────────────────────────────
19
  _cache: dict = {}
20
- BCV_TTL = 60 * 60 * 4 # 4 horas (BCV actualiza una vez al dΓ­a)
21
- P2P_TTL = 60 * 20 # 20 minutos
22
 
23
 
24
  def _cached(key: str, ttl: int):
@@ -41,20 +69,24 @@ async def fetch_bcv() -> dict:
41
  return cached
42
 
43
  async with httpx.AsyncClient(timeout=10) as client:
44
- oficial, paralelo = await asyncio.gather(
45
- client.get("https://ve.dolarapi.com/v1/dolares/oficial"),
46
  client.get("https://ve.dolarapi.com/v1/dolares/paralelo"),
47
  )
48
- oficial.raise_for_status()
49
- paralelo.raise_for_status()
 
 
 
50
 
51
- o = oficial.json()
52
- p = paralelo.json()
53
 
54
  data = {
55
- "bcvUsd": o.get("promedio"),
56
- "parallelUsd": p.get("promedio"),
57
- "updatedAt": o.get("fechaActualizacion"),
 
58
  }
59
  _store("bcv", data)
60
  return data
@@ -105,17 +137,17 @@ async def root():
105
  return {"status": "ok", "service": "Tazas API"}
106
 
107
 
108
- @app.get("/v1/rates")
109
  async def rates():
110
  bcv, p2p = await asyncio.gather(fetch_bcv(), fetch_p2p())
111
  return {**bcv, **p2p}
112
 
113
 
114
- @app.get("/v1/bcv")
115
  async def bcv():
116
  return await fetch_bcv()
117
 
118
 
119
- @app.get("/v1/p2p")
120
  async def p2p():
121
  return await fetch_p2p()
 
1
+ from fastapi import FastAPI, Depends, HTTPException, Header
2
  from fastapi.middleware.cors import CORSMiddleware
3
  import httpx
4
  import asyncio
5
  import time
6
+ import jwt
7
+ from jwt import PyJWKClient
8
 
9
  app = FastAPI(title="Tazas API", version="1.0.0")
10
 
 
15
  allow_headers=["*"],
16
  )
17
 
18
+ # ──────────────────────────────────────────────
19
+ # Firebase App Check
20
+ # ──────────────────────────────────────────────
21
+ PROJECT_NUMBER = "748155614527"
22
+ APP_ID = "1:748155614527:android:c29d203cf594986dda8f8a"
23
+ JWKS_URL = "https://firebaseappcheck.googleapis.com/v1/jwks"
24
+
25
+ _jwks_client = PyJWKClient(JWKS_URL, cache_jwk_set=True, lifespan=3600)
26
+
27
+
28
+ def verify_app_check(x_firebase_appcheck: str = Header(...)):
29
+ try:
30
+ signing_key = _jwks_client.get_signing_key_from_jwt(x_firebase_appcheck)
31
+ claims = jwt.decode(
32
+ x_firebase_appcheck,
33
+ signing_key.key,
34
+ algorithms=["RS256"],
35
+ audience=f"projects/{PROJECT_NUMBER}",
36
+ issuer=f"https://firebaseappcheck.googleapis.com/{PROJECT_NUMBER}",
37
+ )
38
+ if claims.get("sub") != APP_ID:
39
+ raise HTTPException(status_code=401, detail="App no autorizada")
40
+ except jwt.exceptions.PyJWTError:
41
+ raise HTTPException(status_code=401, detail="Token App Check invΓ‘lido")
42
+
43
+
44
  # ──────────────────────────────────────────────
45
  # Cache simple en memoria
46
  # ──────────────────────────────────────────────
47
  _cache: dict = {}
48
+ BCV_TTL = 60 * 60 * 4 # 4 horas
49
+ P2P_TTL = 60 * 20 # 20 minutos
50
 
51
 
52
  def _cached(key: str, ttl: int):
 
69
  return cached
70
 
71
  async with httpx.AsyncClient(timeout=10) as client:
72
+ cotizaciones_res, paralelo_res = await asyncio.gather(
73
+ client.get("https://ve.dolarapi.com/v1/cotizaciones"),
74
  client.get("https://ve.dolarapi.com/v1/dolares/paralelo"),
75
  )
76
+ cotizaciones_res.raise_for_status()
77
+ paralelo_res.raise_for_status()
78
+
79
+ cotizaciones = cotizaciones_res.json()
80
+ paralelo = paralelo_res.json()
81
 
82
+ bcv_usd = next((x["promedio"] for x in cotizaciones if x.get("moneda") == "USD" and x.get("fuente") == "oficial"), None)
83
+ bcv_eur = next((x["promedio"] for x in cotizaciones if x.get("moneda") == "EUR" and x.get("fuente") == "oficial"), None)
84
 
85
  data = {
86
+ "bcvUsd": bcv_usd,
87
+ "bcvEur": bcv_eur,
88
+ "parallelUsd": paralelo.get("promedio"),
89
+ "updatedAt": paralelo.get("fechaActualizacion"),
90
  }
91
  _store("bcv", data)
92
  return data
 
137
  return {"status": "ok", "service": "Tazas API"}
138
 
139
 
140
+ @app.get("/v1/rates", dependencies=[Depends(verify_app_check)])
141
  async def rates():
142
  bcv, p2p = await asyncio.gather(fetch_bcv(), fetch_p2p())
143
  return {**bcv, **p2p}
144
 
145
 
146
+ @app.get("/v1/bcv", dependencies=[Depends(verify_app_check)])
147
  async def bcv():
148
  return await fetch_bcv()
149
 
150
 
151
+ @app.get("/v1/p2p", dependencies=[Depends(verify_app_check)])
152
  async def p2p():
153
  return await fetch_p2p()
requirements.txt CHANGED
@@ -1,3 +1,4 @@
1
  fastapi==0.115.6
2
  uvicorn==0.34.0
3
  httpx==0.28.1
 
 
1
  fastapi==0.115.6
2
  uvicorn==0.34.0
3
  httpx==0.28.1
4
+ PyJWT[crypto]==2.10.1