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:
@@ -27,7 +27,7 @@ def hash_password(password: str) -> str:
|
|||||||
return pwd_context.hash(password)
|
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)
|
expire = datetime.now(timezone.utc) + timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
|
||||||
payload = {
|
payload = {
|
||||||
"sub": str(user_id),
|
"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,
|
"timezone": user_timezone,
|
||||||
"exp": expire,
|
"exp": expire,
|
||||||
}
|
}
|
||||||
|
if admin_id is not None:
|
||||||
|
payload["admin_id"] = admin_id
|
||||||
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
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(
|
async def get_current_user(
|
||||||
token: str = Depends(oauth2_scheme),
|
token: str = Depends(oauth2_scheme),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from sqlalchemy.orm import Session
|
|||||||
from database import get_db
|
from database import get_db
|
||||||
from models import User
|
from models import User
|
||||||
from schemas import UserCreate, UserOut, ResetPasswordRequest, TokenResponse
|
from schemas import UserCreate, UserOut, ResetPasswordRequest, TokenResponse
|
||||||
from auth import hash_password, create_access_token, get_current_admin
|
from auth import hash_password, create_access_token, get_current_admin, get_token_payload
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
||||||
logger = logging.getLogger("yolkbook")
|
logger = logging.getLogger("yolkbook")
|
||||||
@@ -113,6 +113,22 @@ def impersonate_user(
|
|||||||
user = db.get(User, user_id)
|
user = db.get(User, user_id)
|
||||||
if not user:
|
if not user:
|
||||||
raise HTTPException(status_code=404, detail="User not found")
|
raise HTTPException(status_code=404, detail="User not found")
|
||||||
token = create_access_token(user.id, user.username, user.is_admin, user.timezone)
|
token = create_access_token(user.id, user.username, user.is_admin, user.timezone, admin_id=current_admin.id)
|
||||||
logger.warning("Admin '%s' (id=%d) is impersonating user '%s' (id=%d).", current_admin.username, current_admin.id, user.username, user.id)
|
logger.warning("Admin '%s' (id=%d) is impersonating user '%s' (id=%d).", current_admin.username, current_admin.id, user.username, user.id)
|
||||||
return TokenResponse(access_token=token)
|
return TokenResponse(access_token=token)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/unimpersonate", response_model=TokenResponse)
|
||||||
|
def unimpersonate(
|
||||||
|
payload: dict = Depends(get_token_payload),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
admin_id = payload.get("admin_id")
|
||||||
|
if not admin_id:
|
||||||
|
raise HTTPException(status_code=400, detail="Not in an impersonation session")
|
||||||
|
admin = db.get(User, int(admin_id))
|
||||||
|
if not admin or admin.is_disabled or not admin.is_admin:
|
||||||
|
raise HTTPException(status_code=403, detail="Original admin account is no longer valid")
|
||||||
|
token = create_access_token(admin.id, admin.username, admin.is_admin, admin.timezone)
|
||||||
|
logger.warning("Admin '%s' (id=%d) ended impersonation session.", admin.username, admin.id)
|
||||||
|
return TokenResponse(access_token=token)
|
||||||
|
|||||||
@@ -118,8 +118,6 @@ async function toggleUser(id, disable) {
|
|||||||
async function impersonateUser(id) {
|
async function impersonateUser(id) {
|
||||||
try {
|
try {
|
||||||
const data = await API.post(`/api/admin/users/${id}/impersonate`, {});
|
const data = await API.post(`/api/admin/users/${id}/impersonate`, {});
|
||||||
// Save admin token so user can return
|
|
||||||
sessionStorage.setItem('admin_token', Auth.getToken());
|
|
||||||
Auth.setToken(data.access_token);
|
Auth.setToken(data.access_token);
|
||||||
window.location.href = '/';
|
window.location.href = '/';
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -39,16 +39,18 @@ const Auth = {
|
|||||||
|
|
||||||
logout() {
|
logout() {
|
||||||
this.removeToken();
|
this.removeToken();
|
||||||
sessionStorage.removeItem('admin_token');
|
|
||||||
window.location.href = '/login';
|
window.location.href = '/login';
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
function returnToAdmin() {
|
async function returnToAdmin() {
|
||||||
const adminToken = sessionStorage.getItem('admin_token');
|
try {
|
||||||
Auth.setToken(adminToken);
|
const data = await API.post('/api/admin/unimpersonate', {});
|
||||||
sessionStorage.removeItem('admin_token');
|
Auth.setToken(data.access_token);
|
||||||
window.location.href = '/admin';
|
window.location.href = '/admin';
|
||||||
|
} catch (err) {
|
||||||
|
Auth.logout();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Timezone helpers ──────────────────────────────────────────────────────────
|
// ── Timezone helpers ──────────────────────────────────────────────────────────
|
||||||
@@ -110,11 +112,11 @@ function initNav() {
|
|||||||
const nav = document.querySelector('.nav');
|
const nav = document.querySelector('.nav');
|
||||||
if (!nav) return;
|
if (!nav) return;
|
||||||
|
|
||||||
const adminToken = sessionStorage.getItem('admin_token');
|
const isImpersonating = !!user.admin_id;
|
||||||
const navUser = document.createElement('div');
|
const navUser = document.createElement('div');
|
||||||
navUser.className = 'nav-user';
|
navUser.className = 'nav-user';
|
||||||
|
|
||||||
if (adminToken) {
|
if (isImpersonating) {
|
||||||
navUser.innerHTML = `
|
navUser.innerHTML = `
|
||||||
<span class="nav-impersonating">Viewing as <strong>${user.username}</strong></span>
|
<span class="nav-impersonating">Viewing as <strong>${user.username}</strong></span>
|
||||||
<button onclick="returnToAdmin()" class="btn btn-sm btn-amber">↩ Return to Admin</button>
|
<button onclick="returnToAdmin()" class="btn btn-sm btn-amber">↩ Return to Admin</button>
|
||||||
@@ -130,7 +132,7 @@ function initNav() {
|
|||||||
|
|
||||||
nav.appendChild(navUser);
|
nav.appendChild(navUser);
|
||||||
|
|
||||||
if (!adminToken) {
|
if (!isImpersonating) {
|
||||||
const tzOptions = buildTimezoneOptions(user.timezone || 'UTC');
|
const tzOptions = buildTimezoneOptions(user.timezone || 'UTC');
|
||||||
document.body.insertAdjacentHTML('beforeend', `
|
document.body.insertAdjacentHTML('beforeend', `
|
||||||
<div id="settings-modal" class="modal-overlay" style="display:none">
|
<div id="settings-modal" class="modal-overlay" style="display:none">
|
||||||
|
|||||||
Reference in New Issue
Block a user