Remove admin token from sessionStorage during impersonation

Embed admin_id claim in impersonation JWTs and add a backend
/api/admin/unimpersonate endpoint that re-issues the admin token
from that claim. The admin token no longer needs to be stored in
sessionStorage, eliminating the risk of token theft via XSS.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-19 23:32:08 -07:00
parent f6cc7a606e
commit 6d09e40f58
4 changed files with 45 additions and 14 deletions

View File

@@ -27,7 +27,7 @@ def hash_password(password: str) -> str:
return pwd_context.hash(password)
def create_access_token(user_id: int, username: str, is_admin: bool, user_timezone: str = "UTC") -> str:
def create_access_token(user_id: int, username: str, is_admin: bool, user_timezone: str = "UTC", admin_id: Optional[int] = None) -> str:
expire = datetime.now(timezone.utc) + timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
payload = {
"sub": str(user_id),
@@ -36,9 +36,24 @@ def create_access_token(user_id: int, username: str, is_admin: bool, user_timezo
"timezone": user_timezone,
"exp": expire,
}
if admin_id is not None:
payload["admin_id"] = admin_id
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
async def get_token_payload(
token: str = Depends(oauth2_scheme),
) -> dict:
try:
return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
except JWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
async def get_current_user(
token: str = Depends(oauth2_scheme),
db: Session = Depends(get_db),