fix(task7): invalidate tokens on password change or reset
This commit is contained in:
@@ -31,6 +31,15 @@ def get_current_user(
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if user is None or not user.is_active:
|
||||
raise credentials_exception
|
||||
|
||||
token_tv = payload.get("tv", 0)
|
||||
user_tv = getattr(user, "token_version", 0)
|
||||
if token_tv != user_tv:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token has been invalidated. Please log in again.",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
|
||||
@@ -38,7 +38,10 @@ def run_sqlite_migrations(engine: Engine) -> None:
|
||||
for col in table.columns:
|
||||
if col.name not in existing_cols:
|
||||
col_type = col.type.compile(engine.dialect)
|
||||
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} {col_type}"
|
||||
if col.name == "token_version":
|
||||
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} INTEGER DEFAULT 0 NOT NULL"
|
||||
else:
|
||||
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} {col_type}"
|
||||
logger.info("Auto-migrating SQLite: %s", sql)
|
||||
conn.exec_driver_sql(sql)
|
||||
except Exception:
|
||||
|
||||
@@ -92,6 +92,8 @@ def hash_password(plain: str) -> str:
|
||||
|
||||
def create_access_token(data: dict, expires_minutes: int | None = None) -> str:
|
||||
to_encode = data.copy()
|
||||
if "tv" not in to_encode:
|
||||
to_encode["tv"] = 0
|
||||
expire = utc_now() + timedelta(minutes=expires_minutes or settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
to_encode["exp"] = expire
|
||||
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
|
||||
Reference in New Issue
Block a user