11from fastapi import Depends , HTTPException , Request , status
22from fastapi .security import APIKeyHeader , HTTPAuthorizationCredentials , HTTPBearer
33
4+ from cachetools import TTLCache
45from cwms_batch_events .core .auth .user .jwt import verify_jwt
56from cwms_batch_events .core .auth .user .models import User
67from cwms_batch_events .core .auth .user .roles import (
2425 description = "Use format: apikey <your-api-key>" ,
2526)
2627
28+ user_cache : TTLCache [str , User ] = TTLCache (maxsize = 1024 , ttl = 300 )
29+
2730
2831async def get_auth_header_for_docs (
2932 bearer : str = Depends (bearer_scheme ),
@@ -47,6 +50,10 @@ async def get_auth_credentials(
4750async def get_current_user_cwms (
4851 credentials : HTTPAuthorizationCredentials = Depends (get_auth_credentials ),
4952) -> User :
53+ cache_key = f"{ credentials .scheme } :{ credentials .credentials } "
54+ if cache_key in user_cache :
55+ return user_cache [cache_key ]
56+
5057 if credentials .scheme .lower () == "bearer" :
5158 token = credentials .credentials
5259 try :
@@ -71,13 +78,16 @@ async def get_current_user_cwms(
7178
7279 allowed_offices = get_user_allowed_offices (cda_user )
7380 admin_offices = get_user_admin_offices (cda_user )
74- return User (
81+ user = User (
7582 username = cda_user .user_name ,
7683 offices = allowed_offices ,
7784 admin_offices = admin_offices ,
7885 roles = cda_user .roles ,
7986 )
8087
88+ user_cache [cache_key ] = user
89+ return user
90+
8191
8292async def get_current_user_mock () -> User :
8393 return User (
0 commit comments