This repository was archived by the owner on Jun 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathauth.py
More file actions
527 lines (417 loc) · 19 KB
/
auth.py
File metadata and controls
527 lines (417 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
"""Authentication routes for Google OAuth and JWT management."""
from datetime import datetime, timedelta
from typing import Optional
from fastapi import APIRouter, Depends, Form, HTTPException, status
from fastapi.responses import JSONResponse
from google.auth.transport import requests as google_requests
from google.oauth2 import id_token
from jose import JWTError, jwt
from pydantic import BaseModel
from src.api.dependencies import get_current_user, require_api_key, require_user
from src.config import settings
from src.database.user_store import UserStore
from src.database.api_key_store import APIKeyStore
from src.database.control_plane_store import control_plane_store
router = APIRouter(prefix="/auth", tags=["Authentication"])
# Initialize stores
user_store = UserStore()
api_key_store = APIKeyStore()
# ═══════════════════════════════════════════════════════════════════════════
# MCP OAuth Temp Token Store
# ═══════════════════════════════════════════════════════════════════════════
TEMP_TOKEN_PREFIX = "xm-temp-"
TEMP_TOKEN_TTL_MINUTES = 10
MCP_TEMP_TOKEN_RECORD = "mcp_temp_token"
OAUTH_AUTH_CODE_RECORD = "oauth_auth_code"
def _create_mcp_temp_token(user_id: str) -> dict:
"""Create and store a temporary token for the user."""
return control_plane_store.create_single_use_token(
record_type=MCP_TEMP_TOKEN_RECORD,
user_id=user_id,
prefix=TEMP_TOKEN_PREFIX,
ttl_seconds=TEMP_TOKEN_TTL_MINUTES * 60,
)
def _get_and_invalidate_mcp_token(token: str) -> Optional[str]:
"""Validate temp token and return user_id if valid, None otherwise."""
return control_plane_store.consume_single_use_token(MCP_TEMP_TOKEN_RECORD, token)
# ═══════════════════════════════════════════════════════════════════════════
# Standard OAuth 2.0 Store (for ChatGPT UI)
# ═══════════════════════════════════════════════════════════════════════════
def _generate_auth_code(user_id: str) -> str:
"""Generate a standard OAuth 2.0 authorization code."""
return control_plane_store.create_single_use_token(
record_type=OAUTH_AUTH_CODE_RECORD,
user_id=user_id,
prefix="",
ttl_seconds=10 * 60,
)["token"]
def _get_and_invalidate_auth_code(code: str) -> Optional[str]:
"""Validate auth code and return user_id if valid."""
return control_plane_store.consume_single_use_token(OAUTH_AUTH_CODE_RECORD, code)
# ═══════════════════════════════════════════════════════════════════════════
# Pydantic Models
# ═══════════════════════════════════════════════════════════════════════════
class GoogleTokenRequest(BaseModel):
"""Request model for Google OAuth token exchange."""
credential: str
client_id: Optional[str] = None
class TokenResponse(BaseModel):
"""Response model for successful authentication."""
access_token: str
token_type: str = "bearer"
expires_in: int
user: dict
class UserResponse(BaseModel):
"""Response model for current user."""
id: str
email: str
name: str
username: Optional[str] = None
picture: Optional[str] = None
created_at: Optional[datetime] = None
last_login: Optional[datetime] = None
class SetUsernameRequest(BaseModel):
"""Request model for setting a username."""
username: str
class UsernameCheckResponse(BaseModel):
"""Response model for username availability check."""
available: bool
class RefreshRequest(BaseModel):
"""Request model for token refresh."""
refresh_token: str
# ═══════════════════════════════════════════════════════════════════════════
# MCP OAuth Models
# ═══════════════════════════════════════════════════════════════════════════
class MCPTempTokenResponse(BaseModel):
"""Response model for MCP temp token generation."""
temp_token: str
expires_in: int # seconds
expires_at: datetime
class MCPExchangeRequest(BaseModel):
"""Request model for exchanging temp token for API key."""
temp_token: str
client_type: str = "mcp" # For future extensibility
class MCPExchangeResponse(BaseModel):
"""Response model for successful MCP authentication."""
status: str = "success"
api_key: str
user: dict
class OAuthApproveRequest(BaseModel):
"""Request from frontend to approve OAuth and get a code."""
client_id: str
redirect_uri: str
class OAuthApproveResponse(BaseModel):
"""Response with the authorization code."""
code: str
# ═══════════════════════════════════════════════════════════════════════════
# JWT Utilities
# ═══════════════════════════════════════════════════════════════════════════
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
"""Create a JWT access token.
Args:
data: Data to encode in the token
expires_delta: Optional custom expiration time
Returns:
JWT token string
"""
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(days=settings.jwt_expiration_days)
to_encode.update({"exp": expire, "iat": datetime.utcnow(), "type": "access"})
encoded_jwt = jwt.encode(
to_encode,
settings.jwt_secret_key,
algorithm=settings.jwt_algorithm
)
return encoded_jwt
def verify_google_token(credential: str) -> dict:
"""Verify a Google ID token and return user info.
Args:
credential: Google ID token
Returns:
Dictionary with user info from Google
Raises:
HTTPException: If token is invalid
"""
try:
# Verify the token with Google
idinfo = id_token.verify_oauth2_token(
credential,
google_requests.Request(),
settings.google_client_id,
clock_skew_in_seconds=60
)
# Check issuer
if idinfo["iss"] not in ["accounts.google.com", "https://accounts.google.com"]:
raise ValueError("Invalid issuer")
return {
"google_id": idinfo["sub"],
"email": idinfo.get("email"),
"name": idinfo.get("name"),
"picture": idinfo.get("picture"),
}
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Invalid Google token: {str(e)}"
)
# ═══════════════════════════════════════════════════════════════════════════
# Routes
# ═══════════════════════════════════════════════════════════════════════════
@router.post("/google", response_model=TokenResponse)
async def auth_google(request: GoogleTokenRequest):
"""Authenticate with Google OAuth credential.
This endpoint receives the Google ID token from the frontend,
verifies it, creates or updates the user, and returns a JWT.
"""
# Verify the Google token
google_user = verify_google_token(request.credential)
# Get or create user in database
user = user_store.get_or_create_user(
google_id=google_user["google_id"],
email=google_user["email"],
name=google_user["name"],
picture=google_user.get("picture"),
)
# Create JWT token
access_token = create_access_token(
data={"sub": str(user["_id"])}
)
# Convert user document for response
user_response = {
"id": str(user["_id"]),
"email": user["email"],
"name": user["name"],
"username": user.get("username"),
"picture": user.get("picture"),
"created_at": user.get("created_at"),
"last_login": user.get("last_login"),
}
return TokenResponse(
access_token=access_token,
token_type="bearer",
expires_in=settings.jwt_expiration_days * 24 * 60 * 60, # Convert to seconds
user=user_response,
)
@router.get("/me", response_model=UserResponse)
async def get_me(current_user: dict = Depends(get_current_user)):
"""Get current authenticated user information."""
if not current_user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
return UserResponse(**current_user)
@router.post("/refresh", response_model=TokenResponse)
async def refresh_token(request: RefreshRequest):
"""Refresh an access token.
Note: This is a simplified implementation. In production, you might
want to implement refresh tokens separately from access tokens.
"""
try:
payload = jwt.decode(
request.refresh_token,
settings.jwt_secret_key,
algorithms=[settings.jwt_algorithm]
)
user_id: str = payload.get("sub")
if user_id is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token"
)
# Get user from database
user = user_store.get_user_by_id(user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User not found"
)
# Create new access token
new_token = create_access_token(
data={"sub": str(user["_id"])}
)
# Convert user document for response
user_response = {
"id": str(user["_id"]),
"email": user["email"],
"name": user["name"],
"username": user.get("username"),
"picture": user.get("picture"),
"created_at": user.get("created_at"),
"last_login": user.get("last_login"),
}
return TokenResponse(
access_token=new_token,
token_type="bearer",
expires_in=settings.jwt_expiration_days * 24 * 60 * 60,
user=user_response,
)
except JWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token"
)
@router.get("/check-username/{username}", response_model=UsernameCheckResponse)
async def check_username(username: str):
"""Check if a username is available."""
# Basic validation
if len(username) < 3 or len(username) > 30:
return UsernameCheckResponse(available=False)
import re
if not re.match(r'^[a-zA-Z0-9_-]+$', username):
return UsernameCheckResponse(available=False)
is_available = user_store.is_username_available(username)
return UsernameCheckResponse(available=is_available)
@router.post("/set-username", response_model=UserResponse)
async def set_username(req: SetUsernameRequest, current_user: dict = Depends(get_current_user)):
"""Set username for the currently authenticated user."""
if not current_user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated"
)
if current_user.get("username"):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Username already set"
)
username = req.username
if len(username) < 3 or len(username) > 30:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Username must be between 3 and 30 characters"
)
import re
if not re.match(r'^[a-zA-Z0-9_-]+$', username):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Username can only contain letters, numbers, underscores, and hyphens"
)
success = user_store.set_username(current_user["id"], username)
if not success:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Username is not available or could not be set"
)
# Get updated user
user = user_store.get_user_by_id(current_user["id"])
updated_user = dict(user) if user else current_user
if "_id" in updated_user:
updated_user["id"] = str(updated_user.pop("_id"))
elif "id" not in updated_user:
updated_user["id"] = current_user["id"]
return UserResponse(**updated_user)
@router.get("/verify-key", response_model=UserResponse)
async def verify_key(user: dict = Depends(require_api_key)):
"""Verify an API key and return the associated user information."""
return UserResponse(**user)
# ═══════════════════════════════════════════════════════════════════════════
# MCP OAuth Routes
# ═══════════════════════════════════════════════════════════════════════════
@router.post("/mcp-token", response_model=MCPTempTokenResponse)
async def generate_mcp_temp_token(current_user: dict = Depends(require_user)):
"""
Generate a temporary token for MCP OAuth authentication.
This endpoint is called from the XMem web UI when a user wants to
connect their account to an MCP client (Claude Desktop, ChatGPT, etc.)
that doesn't support environment variable configuration.
The temp token is valid for 10 minutes and can only be exchanged once.
"""
if not current_user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required"
)
user_id = str(current_user.get("id"))
temp_token = _create_mcp_temp_token(user_id)
return MCPTempTokenResponse(
temp_token=temp_token["token"],
expires_in=TEMP_TOKEN_TTL_MINUTES * 60,
expires_at=temp_token["expires_at"],
)
@router.post("/mcp-exchange", response_model=MCPExchangeResponse)
async def exchange_mcp_token(request: MCPExchangeRequest):
"""
Exchange a temporary MCP token for a permanent API key.
This endpoint is called by the MCP server to exchange the temporary
token (provided by the user) for a long-lived API key.
The temp token is single-use and invalidated after exchange.
"""
# Validate and consume the temp token
user_id = _get_and_invalidate_mcp_token(request.temp_token)
if not user_id:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired token"
)
# Get user details
user = user_store.get_user_by_id(user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
# Create a new API key for this user
key_result = api_key_store.create_api_key(
user_id=user_id,
name=f"MCP Client - {datetime.utcnow().strftime('%Y-%m-%d %H:%M')}"
)
# Prepare user response
user_response = {
"id": str(user["_id"]),
"email": user.get("email"),
"name": user.get("name"),
"username": user.get("username"),
}
return MCPExchangeResponse(
status="success",
api_key=key_result["key"],
user=user_response
)
# ═══════════════════════════════════════════════════════════════════════════
# Standard OAuth 2.0 Routes (For ChatGPT UI)
# ═══════════════════════════════════════════════════════════════════════════
@router.post("/oauth/approve", response_model=OAuthApproveResponse)
async def oauth_approve(request: OAuthApproveRequest, current_user: dict = Depends(require_user)):
"""
Called by the Next.js frontend when the user clicks 'Approve' on the consent screen.
Generates an authorization code for standard OAuth 2.0 flow.
"""
if not current_user:
raise HTTPException(status_code=401, detail="Authentication required")
user_id = str(current_user.get("id"))
code = _generate_auth_code(user_id)
return OAuthApproveResponse(code=code)
@router.post("/oauth/token")
async def oauth_token(
grant_type: str = Form(...),
code: str = Form(None),
redirect_uri: str = Form(None),
client_id: str = Form(None)
):
"""
Standard OAuth 2.0 token endpoint.
ChatGPT calls this directly to exchange the authorization code for an access token.
"""
if grant_type != "authorization_code":
return JSONResponse(status_code=400, content={"error": "unsupported_grant_type"})
if not code:
return JSONResponse(status_code=400, content={"error": "invalid_request", "error_description": "code is required"})
user_id = _get_and_invalidate_auth_code(code)
if not user_id:
return JSONResponse(status_code=400, content={"error": "invalid_grant", "error_description": "Invalid or expired authorization code"})
# Generate a permanent API key acting as the access token
key_result = api_key_store.create_api_key(
user_id=user_id,
name=f"OAuth Client ({client_id or 'Unknown'}) - {datetime.utcnow().strftime('%Y-%m-%d')}"
)
return {
"access_token": key_result["key"],
"token_type": "Bearer",
"expires_in": 31536000, # 1 year
"scope": "all"
}