Skip to content

Commit 5a80b86

Browse files
committed
only ensure user exists on login
1 parent 7b87437 commit 5a80b86

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

src/backend/dependencies.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from domain.user import User
1313
from domain.pad import Pad
1414
from coder import CoderAPI
15-
from database.database import async_session, get_session
15+
from database.database import get_session
1616

1717
# oidc_config for session creation and user sessions
1818
oidc_config = {
@@ -49,19 +49,12 @@ def __init__(self, access_token: str, token_data: dict, session_domain: Session,
4949
algorithms=["RS256"],
5050
audience=oidc_config['client_id']
5151
)
52-
53-
# Ensure user exists in database
54-
async def ensure_user():
55-
async with async_session() as session:
56-
await User.ensure_exists(session, self.token_data)
57-
asyncio.create_task(ensure_user())
5852

59-
6053
except jwt.InvalidTokenError as e:
6154
# Log the error and raise an appropriate exception
6255
print(f"Invalid token: {str(e)}")
6356
raise ValueError(f"Invalid authentication token: {str(e)}")
64-
57+
6558
@property
6659
def is_authenticated(self) -> bool:
6760
"""Check if the session is authenticated"""

src/backend/routers/auth_router.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
from coder import CoderAPI
1313
from dependencies import optional_auth, UserSession
1414
from domain.session import Session
15+
from database.database import async_session
16+
from domain.user import User
1517

1618
auth_router = APIRouter()
1719

@@ -81,6 +83,17 @@ async def callback(
8183
access_token = token_data['access_token']
8284
user_info = jwt.decode(access_token, options={"verify_signature": False})
8385

86+
# Ensure user exists in database (only during login)
87+
async with async_session() as db_session:
88+
try:
89+
await User.ensure_exists(db_session, user_info)
90+
except Exception as e:
91+
# Handle duplicate key violations gracefully - this means user already exists
92+
if "duplicate key value violates unique constraint" in str(e) or "already exists" in str(e):
93+
print(f"User {user_info.get('sub')} already exists in database (race condition handled)")
94+
else:
95+
raise e
96+
8497
try:
8598
user_data, _ = coder_api.ensure_user_exists(
8699
user_info

0 commit comments

Comments
 (0)