Skip to content

Commit 2bb4a1d

Browse files
committed
Add user id to logging context
1 parent f55b798 commit 2bb4a1d

1 file changed

Lines changed: 16 additions & 14 deletions

File tree

src/routers/dependencies.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -26,23 +26,25 @@ async def userdb_connection() -> AsyncGenerator[AsyncConnection, None]:
2626
async def fetch_user(
2727
api_key: APIKey | None = None,
2828
user_data: Annotated[AsyncConnection | None, Depends(userdb_connection)] = None,
29-
) -> User | None:
29+
) -> AsyncGenerator[User | None]:
3030
if not (api_key and user_data):
31-
return None
31+
yield None
32+
return
3233

3334
user = await User.fetch(api_key, user_data)
34-
mask_length = 28
35-
masked_key = "*" * mask_length + api_key[mask_length:]
36-
if user:
37-
logger.info(
38-
"User {identifier} authenticated in with api key {api_key}.",
39-
identifier=user.user_id,
40-
api_key=masked_key,
41-
)
42-
return user
43-
logger.info("Authentication failed.", api_key=masked_key)
44-
msg = "Invalid API key provided."
45-
raise AuthenticationFailedError(msg)
35+
masked_key = api_key[-4:]
36+
if not user:
37+
logger.info("Authentication failed.", api_key=masked_key)
38+
msg = "Invalid API key provided."
39+
raise AuthenticationFailedError(msg)
40+
41+
logger.info(
42+
"User {identifier} authenticated in with api key ending in '{api_key}'.",
43+
identifier=user.user_id,
44+
api_key=masked_key,
45+
)
46+
with logger.contextualize(user_id=user.user_id):
47+
yield user
4648

4749

4850
def fetch_user_or_raise(

0 commit comments

Comments
 (0)