Skip to content

Commit 0fab482

Browse files
committed
Rewrite to asyncio
1 parent 395dfec commit 0fab482

1 file changed

Lines changed: 25 additions & 25 deletions

File tree

  • backend/PennCourses/authentication
Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import logging
2-
import threading
3-
import time
2+
import asyncio
43

54
import jwt
65
from django.conf import settings
@@ -10,36 +9,35 @@
109

1110
logger = logging.getLogger(__name__)
1211

13-
REFRESH_INTERVAL = 3600 # 1 hour
12+
REFRESH_INTERVAL = 5 # 1 hour
1413
jwks_client = jwt.PyJWKClient(settings.JWKS_URI)
15-
jwks_client_lock = threading.Lock()
14+
jwks_client_lock = asyncio.Lock()
1615

1716

18-
def get_jwks_client():
19-
with jwks_client_lock:
17+
async def get_jwks_client():
18+
async with jwks_client_lock:
2019
return jwks_client
2120

21+
async def refresh_jwks_client():
22+
global jwks_client
23+
while True:
24+
try:
25+
new_client = jwt.PyJWKClient(settings.JWKS_URI)
26+
async with jwks_client_lock:
27+
jwks_client = new_client
28+
logger.info("[JWK] JWKs client updated and cached.")
29+
except Exception as e:
30+
logger.error("[JWK] Error updating JWKs client: %s", e)
31+
await asyncio.sleep(REFRESH_INTERVAL)
2232

2333
def start_jwks_refresh():
24-
def refresh():
25-
global jwks_client
26-
while True:
27-
try:
28-
new_client = jwt.PyJWKClient(settings.JWKS_URI)
29-
with jwks_client_lock:
30-
jwks_client = new_client
31-
logger.info("[JWK] JWKs client updated and cached.")
32-
except Exception as e:
33-
logger.info("[JWK] Error updating JWKs client: %s", e)
34-
time.sleep(REFRESH_INTERVAL)
35-
36-
thread = threading.Thread(target=refresh, daemon=True)
37-
thread.start()
38-
39-
40-
def verify_jwt(token):
34+
loop = asyncio.get_event_loop()
35+
loop.create_task(refresh_jwks_client())
36+
37+
async def verify_jwt(token):
4138
try:
42-
signing_key = jwks_client.get_signing_key_from_jwt(token).key
39+
client = await get_jwks_client()
40+
signing_key = client.get_signing_key_from_jwt(token).key
4341
payload = jwt.decode(
4442
token, signing_key, audience=settings.AUTH_OIDC_CLIENT_ID, algorithms=["RS256"]
4543
)
@@ -56,7 +54,9 @@ class JWTAuthentication(authentication.BaseAuthentication):
5654
def authenticate(self, request):
5755
id_token = request.COOKIES.get("id_token")
5856
if id_token:
59-
payload = verify_jwt(id_token)
57+
payload = asyncio.run(verify_jwt(id_token))
6058
if payload:
6159
return (payload, None)
6260
return (AnonymousUser, None)
61+
62+
start_jwks_refresh()

0 commit comments

Comments
 (0)