feat: api-tokens pro gerät (backend)
Tokens werden einmal angezeigt und nur gehasht gespeichert. Anmeldung per Authorization: Bearer für Clips, Dateien, Projektliste/-anlage und den Live-Sync (WebSocket ohne Origin). Konto, Admin, Sessions, Tokens und Projektverwaltung bleiben der Browser-Session vorbehalten. Widerruf schließt die Verbindungen des Tokens sofort. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4ae459cf53
commit
d8377c8a04
14 files changed
+520
-32
No files matched your search
@@ -3,7 +3,7 @@ from typing import Annotated
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, Query, status
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.api.deps import ApiUser, DbSession
|
||||
from app.api.notify import notify
|
||||
from app.models import Clip
|
||||
from app.schemas.clips import ClipCreate, ClipList, ClipOut, ClipUpdate
|
||||
@@ -23,7 +23,7 @@ def _clip_data(clip: Clip) -> dict:
|
||||
return ClipOut.model_validate(clip).model_dump(mode="json")
|
||||
|
||||
|
||||
def _get_visible_clip(db: DbSession, user: CurrentUser, clip_id: int) -> Clip:
|
||||
def _get_visible_clip(db: DbSession, user: ApiUser, clip_id: int) -> Clip:
|
||||
# Invisible and missing clips look the same, so ids of other users are not revealed
|
||||
clip = clip_service.get_clip(db, user.id, clip_id)
|
||||
if clip is None:
|
||||
@@ -33,7 +33,7 @@ def _get_visible_clip(db: DbSession, user: CurrentUser, clip_id: int) -> Clip:
|
||||
|
||||
@router.get("", response_model=ClipList)
|
||||
def list_clips(
|
||||
user: CurrentUser,
|
||||
user: ApiUser,
|
||||
db: DbSession,
|
||||
limit: Annotated[int, Query(ge=1, le=100)] = 50,
|
||||
offset: Annotated[int, Query(ge=0)] = 0,
|
||||
@@ -48,7 +48,7 @@ def list_clips(
|
||||
|
||||
|
||||
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession, background: BackgroundTasks):
|
||||
def create_clip(body: ClipCreate, user: ApiUser, db: DbSession, background: BackgroundTasks):
|
||||
clip = clip_service.create_clip(db, user.id, **body.model_dump())
|
||||
notify(
|
||||
background,
|
||||
@@ -60,7 +60,7 @@ def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession, background:
|
||||
|
||||
|
||||
@router.get("/{clip_id}", response_model=ClipOut)
|
||||
def get_clip(clip_id: int, user: CurrentUser, db: DbSession):
|
||||
def get_clip(clip_id: int, user: ApiUser, db: DbSession):
|
||||
return _get_visible_clip(db, user, clip_id)
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ def get_clip(clip_id: int, user: CurrentUser, db: DbSession):
|
||||
def update_clip(
|
||||
clip_id: int,
|
||||
body: ClipUpdate,
|
||||
user: CurrentUser,
|
||||
user: ApiUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
):
|
||||
@@ -97,9 +97,7 @@ def update_clip(
|
||||
|
||||
|
||||
@router.delete("/{clip_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_clip(
|
||||
clip_id: int, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||
) -> None:
|
||||
def delete_clip(clip_id: int, user: ApiUser, db: DbSession, background: BackgroundTasks) -> None:
|
||||
clip = _get_visible_clip(db, user, clip_id)
|
||||
audience = clip_audience(db, clip.user_id, clip.project_id)
|
||||
clip_service.delete_clip(db, user.id, clip)
|
||||
|
||||
@@ -9,6 +9,7 @@ from app.db import get_db
|
||||
from app.middleware import SAFE_METHODS
|
||||
from app.models import User, UserSession
|
||||
from app.services.sessions import resolve_session
|
||||
from app.services.tokens import resolve_token
|
||||
|
||||
SESSION_COOKIE = "lc_session"
|
||||
CSRF_COOKIE = "lc_csrf"
|
||||
@@ -37,6 +38,28 @@ def get_current_user(session: CurrentSession) -> User:
|
||||
CurrentUser = Annotated[User, Depends(get_current_user)]
|
||||
|
||||
|
||||
def bearer_token(authorization: str | None) -> str | None:
|
||||
if authorization and authorization[:7].lower() == "bearer ":
|
||||
return authorization[7:].strip()
|
||||
return None
|
||||
|
||||
|
||||
def get_api_user(request: Request, db: DbSession) -> User:
|
||||
"""Session or device token (Authorization: Bearer). Only for the endpoints the desktop
|
||||
agent needs; admin, password, sessions and token management stay session-only."""
|
||||
plain = bearer_token(request.headers.get("authorization"))
|
||||
if plain is None:
|
||||
return get_current_session(request, db).user
|
||||
token = resolve_token(db, plain, client_ip(request))
|
||||
if token is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Token ungültig oder widerrufen.")
|
||||
# No CSRF check: browsers never attach this header on their own
|
||||
return token.user
|
||||
|
||||
|
||||
ApiUser = Annotated[User, Depends(get_api_user)]
|
||||
|
||||
|
||||
def require_admin(user: CurrentUser) -> User:
|
||||
if not user.is_admin:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "Nur für Administratoren.")
|
||||
|
||||
@@ -4,7 +4,7 @@ from fastapi import APIRouter, BackgroundTasks, HTTPException, Query, Request, s
|
||||
from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.api.deps import ApiUser, DbSession
|
||||
from app.api.notify import notify
|
||||
from app.config import get_settings
|
||||
from app.schemas.clips import ClipOut
|
||||
@@ -32,7 +32,7 @@ class ExpiryUpdate(BaseModel):
|
||||
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
|
||||
async def upload(
|
||||
request: Request,
|
||||
user: CurrentUser,
|
||||
user: ApiUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
name: Annotated[str, Query(max_length=1000)],
|
||||
@@ -62,7 +62,7 @@ async def upload(
|
||||
|
||||
|
||||
@router.get("/usage", response_model=Usage)
|
||||
def usage(user: CurrentUser, db: DbSession) -> Usage:
|
||||
def usage(user: ApiUser, db: DbSession) -> Usage:
|
||||
settings = get_settings()
|
||||
return Usage(
|
||||
used_bytes=file_service.used_bytes(db, user.id),
|
||||
@@ -72,7 +72,7 @@ def usage(user: CurrentUser, db: DbSession) -> Usage:
|
||||
|
||||
|
||||
@router.get("/{clip_id}")
|
||||
def download(clip_id: int, user: CurrentUser, db: DbSession, inline: bool = False):
|
||||
def download(clip_id: int, user: ApiUser, db: DbSession, inline: bool = False):
|
||||
stored = file_service.get_file(db, user.id, clip_id)
|
||||
# Stored under the uploader, who may be another member of a shared project
|
||||
path = None if stored is None else file_service.file_path(stored.user_id, stored.storage_name)
|
||||
@@ -95,7 +95,7 @@ def download(clip_id: int, user: CurrentUser, db: DbSession, inline: bool = Fals
|
||||
def update_expiry(
|
||||
clip_id: int,
|
||||
body: ExpiryUpdate,
|
||||
user: CurrentUser,
|
||||
user: ApiUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
):
|
||||
|
||||
@@ -2,7 +2,7 @@ from collections.abc import Iterable
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, status
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.api.deps import ApiUser, CurrentUser, DbSession
|
||||
from app.api.notify import notify
|
||||
from app.models import Project
|
||||
from app.schemas.projects import (
|
||||
@@ -17,6 +17,8 @@ from app.services import projects as project_service
|
||||
from app.services.access import project_audience
|
||||
from app.services.projects import ProjectView
|
||||
|
||||
# Device tokens may list and create projects (the agent sets up its own); managing
|
||||
# projects and members needs a browser session
|
||||
router = APIRouter(prefix="/projects", tags=["projects"])
|
||||
|
||||
|
||||
@@ -65,13 +67,13 @@ def _notify_project(
|
||||
|
||||
|
||||
@router.get("", response_model=list[ProjectOut])
|
||||
def list_projects(user: CurrentUser, db: DbSession) -> list[ProjectOut]:
|
||||
def list_projects(user: ApiUser, db: DbSession) -> list[ProjectOut]:
|
||||
return [_out(view) for view in project_service.list_projects(db, user.id)]
|
||||
|
||||
|
||||
@router.post("", response_model=ProjectOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_project(
|
||||
body: ProjectCreate, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||
body: ProjectCreate, user: ApiUser, db: DbSession, background: BackgroundTasks
|
||||
) -> ProjectOut:
|
||||
project = project_service.create_project(db, user.id, **body.model_dump())
|
||||
out = _out(_view(db, user, project.id))
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, status
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.services import tokens as token_service
|
||||
from app.ws.hub import hub
|
||||
|
||||
# Session only: a device token must not be able to create or list tokens
|
||||
router = APIRouter(prefix="/tokens", tags=["tokens"])
|
||||
|
||||
|
||||
class TokenCreate(BaseModel):
|
||||
name: str = Field(max_length=1000)
|
||||
|
||||
|
||||
class TokenOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
prefix: str
|
||||
created_at: datetime
|
||||
last_used_at: datetime | None
|
||||
last_ip: str | None
|
||||
|
||||
|
||||
class TokenCreated(TokenOut):
|
||||
token: str = Field(description="Shown only once")
|
||||
|
||||
|
||||
@router.get("", response_model=list[TokenOut])
|
||||
def list_tokens(user: CurrentUser, db: DbSession):
|
||||
return token_service.list_tokens(db, user.id)
|
||||
|
||||
|
||||
@router.post("", response_model=TokenCreated, status_code=status.HTTP_201_CREATED)
|
||||
def create_token(body: TokenCreate, user: CurrentUser, db: DbSession) -> TokenCreated:
|
||||
token, plain = token_service.create_token(db, user.id, body.name)
|
||||
return TokenCreated(**TokenOut.model_validate(token).model_dump(), token=plain)
|
||||
|
||||
|
||||
@router.delete("/{token_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def revoke_token(
|
||||
token_id: int, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||
) -> None:
|
||||
if not token_service.revoke_token(db, user.id, token_id):
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Token nicht gefunden.")
|
||||
background.add_task(hub.close_token, token_id)
|
||||
@@ -2,7 +2,7 @@ from fastapi import APIRouter
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.api.deps import ApiUser, DbSession
|
||||
from app.models import User
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["users"])
|
||||
@@ -14,7 +14,7 @@ class UserName(BaseModel):
|
||||
|
||||
|
||||
@router.get("", response_model=list[UserName])
|
||||
def list_user_names(user: CurrentUser, db: DbSession) -> list[UserName]:
|
||||
def list_user_names(user: ApiUser, db: DbSession) -> list[UserName]:
|
||||
"""Names of the other active users, for sharing projects; nothing else is revealed."""
|
||||
rows = db.execute(
|
||||
select(User.id, User.username)
|
||||
|
||||
+32
-11
@@ -4,10 +4,11 @@ import time
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
|
||||
from app.api.deps import SESSION_COOKIE
|
||||
from app.api.deps import SESSION_COOKIE, bearer_token
|
||||
from app.config import get_settings
|
||||
from app.db import _session_factory
|
||||
from app.services.sessions import is_session_valid, resolve_session
|
||||
from app.services.tokens import is_token_valid, resolve_token
|
||||
from app.ws.hub import CLOSE_UNAUTHORIZED, Connection, hub
|
||||
|
||||
router = APIRouter()
|
||||
@@ -18,15 +19,23 @@ REVALIDATE_INTERVAL_SECONDS = 300
|
||||
CLOSE_TOO_MANY = 4429
|
||||
|
||||
|
||||
def _resolve(token: str | None) -> tuple[int, int] | None:
|
||||
def _resolve_session(token: str | None) -> tuple[int, int] | None:
|
||||
with _session_factory()() as db:
|
||||
session = resolve_session(db, token)
|
||||
return (session.id, session.user_id) if session else None
|
||||
|
||||
|
||||
def _still_valid(session_id: int) -> bool:
|
||||
def _resolve_token(plain: str, ip: str | None) -> tuple[int, int] | None:
|
||||
with _session_factory()() as db:
|
||||
return is_session_valid(db, session_id)
|
||||
token = resolve_token(db, plain, ip)
|
||||
return (token.id, token.user_id) if token else None
|
||||
|
||||
|
||||
def _still_valid(conn: Connection) -> bool:
|
||||
with _session_factory()() as db:
|
||||
if conn.token_id is not None:
|
||||
return is_token_valid(db, conn.token_id)
|
||||
return conn.session_id is not None and is_session_valid(db, conn.session_id)
|
||||
|
||||
|
||||
async def _heartbeat(conn: Connection) -> None:
|
||||
@@ -37,7 +46,7 @@ async def _heartbeat(conn: Connection) -> None:
|
||||
await conn.websocket.send_json({"type": "ping"})
|
||||
if time.monotonic() - last_check >= REVALIDATE_INTERVAL_SECONDS:
|
||||
last_check = time.monotonic()
|
||||
if not await run_in_threadpool(_still_valid, conn.session_id):
|
||||
if not await run_in_threadpool(_still_valid, conn):
|
||||
await conn.websocket.close(code=CLOSE_UNAUTHORIZED)
|
||||
return
|
||||
|
||||
@@ -50,24 +59,36 @@ async def _drain(conn: Connection) -> None:
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def websocket_endpoint(websocket: WebSocket) -> None:
|
||||
# Origin check protects the cookie-authenticated socket against cross-site hijacking
|
||||
origin = (websocket.headers.get("origin") or "").rstrip("/")
|
||||
if origin not in get_settings().allowed_origin_list:
|
||||
plain = bearer_token(websocket.headers.get("authorization"))
|
||||
origin = websocket.headers.get("origin")
|
||||
# Origin check protects the cookie-authenticated socket against cross-site hijacking.
|
||||
# The desktop agent sends a token and no Origin; browsers always send Origin and
|
||||
# cannot set an Authorization header on WebSockets.
|
||||
origin_ok = (origin or "").rstrip("/") in get_settings().allowed_origin_list
|
||||
if not origin_ok and not (plain is not None and origin is None):
|
||||
await websocket.close(code=4403) # before accept: handshake is rejected
|
||||
return
|
||||
|
||||
await websocket.accept()
|
||||
# Accept first so the client sees the close code and can redirect to login
|
||||
ids = await run_in_threadpool(_resolve, websocket.cookies.get(SESSION_COOKIE))
|
||||
ip = websocket.client.host if websocket.client else None
|
||||
if plain is not None:
|
||||
ids = await run_in_threadpool(_resolve_token, plain, ip)
|
||||
else:
|
||||
ids = await run_in_threadpool(_resolve_session, websocket.cookies.get(SESSION_COOKIE))
|
||||
if ids is None:
|
||||
await websocket.close(code=CLOSE_UNAUTHORIZED)
|
||||
return
|
||||
session_id, user_id = ids
|
||||
credential_id, user_id = ids
|
||||
if hub.count(user_id) >= MAX_CONNECTIONS_PER_USER:
|
||||
await websocket.close(code=CLOSE_TOO_MANY)
|
||||
return
|
||||
|
||||
conn = Connection(websocket=websocket, user_id=user_id, session_id=session_id)
|
||||
conn = (
|
||||
Connection(websocket=websocket, user_id=user_id, token_id=credential_id)
|
||||
if plain is not None
|
||||
else Connection(websocket=websocket, user_id=user_id, session_id=credential_id)
|
||||
)
|
||||
hub.add(conn)
|
||||
try:
|
||||
await websocket.send_json({"type": "hello"})
|
||||
|
||||
+2
-1
@@ -9,7 +9,7 @@ from fastapi.concurrency import run_in_threadpool
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
|
||||
from app import __version__
|
||||
from app.api import admin, auth, clips, files, health, projects, users, ws
|
||||
from app.api import admin, auth, clips, files, health, projects, tokens, users, ws
|
||||
from app.config import get_settings
|
||||
from app.db import _session_factory
|
||||
from app.middleware import (
|
||||
@@ -151,6 +151,7 @@ def create_app() -> FastAPI:
|
||||
app.include_router(projects.router, prefix="/api")
|
||||
app.include_router(files.router, prefix="/api")
|
||||
app.include_router(users.router, prefix="/api")
|
||||
app.include_router(tokens.router, prefix="/api")
|
||||
app.include_router(ws.router, prefix="/api")
|
||||
|
||||
@app.exception_handler(UserError)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from app.models.api_token import ApiToken
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
from app.models.clip import Clip, ClipKind
|
||||
from app.models.file import StoredFile
|
||||
@@ -8,6 +9,7 @@ from app.models.session import UserSession
|
||||
from app.models.user import Role, User
|
||||
|
||||
__all__ = [
|
||||
"ApiToken",
|
||||
"Base",
|
||||
"Clip",
|
||||
"ClipKind",
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import ForeignKey, Index, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
class ApiToken(Base):
|
||||
"""Per-device token for the desktop agent and scripts; only its hash is stored."""
|
||||
|
||||
__tablename__ = "api_tokens"
|
||||
__table_args__ = (Index("ix_api_tokens_user", "user_id"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
token_hash: Mapped[str] = mapped_column(String(64), unique=True)
|
||||
# First characters of the token, so the user can tell tokens apart
|
||||
prefix: Mapped[str] = mapped_column(String(16))
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
last_used_at: Mapped[datetime | None] = mapped_column(UTCDateTime)
|
||||
last_ip: Mapped[str | None] = mapped_column(String(45))
|
||||
|
||||
user: Mapped[User] = relationship(lazy="joined")
|
||||
@@ -0,0 +1,80 @@
|
||||
import secrets
|
||||
import unicodedata
|
||||
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import ApiToken, utcnow
|
||||
from app.security import hash_token
|
||||
from app.services.sessions import TOUCH_INTERVAL
|
||||
from app.services.users import UserError
|
||||
|
||||
TOKEN_PREFIX = "lc_" # noqa: S105 - public marker, not a secret
|
||||
SHOWN_PREFIX_LENGTH = 10
|
||||
NAME_MAX_LENGTH = 100
|
||||
MAX_TOKENS_PER_USER = 50
|
||||
|
||||
|
||||
def create_token(db: Session, user_id: int, name: str) -> tuple[ApiToken, str]:
|
||||
"""Create a token; the plain value is returned once and never stored."""
|
||||
name = " ".join(name.split())
|
||||
if not name:
|
||||
raise UserError("Bitte einen Namen für das Gerät angeben.")
|
||||
if len(name) > NAME_MAX_LENGTH:
|
||||
raise UserError(f"Der Name ist zu lang (höchstens {NAME_MAX_LENGTH} Zeichen).")
|
||||
if any(unicodedata.category(ch).startswith("C") for ch in name):
|
||||
raise UserError("Der Name enthält ungültige Zeichen.")
|
||||
count = db.scalar(select(func.count(ApiToken.id)).where(ApiToken.user_id == user_id))
|
||||
if (count or 0) >= MAX_TOKENS_PER_USER:
|
||||
raise UserError(f"Höchstens {MAX_TOKENS_PER_USER} Tokens möglich.")
|
||||
|
||||
plain = TOKEN_PREFIX + secrets.token_urlsafe(32)
|
||||
token = ApiToken(
|
||||
user_id=user_id,
|
||||
name=name,
|
||||
token_hash=hash_token(plain),
|
||||
prefix=plain[:SHOWN_PREFIX_LENGTH],
|
||||
)
|
||||
db.add(token)
|
||||
db.commit()
|
||||
return token, plain
|
||||
|
||||
|
||||
def list_tokens(db: Session, user_id: int) -> list[ApiToken]:
|
||||
return list(
|
||||
db.scalars(
|
||||
select(ApiToken).where(ApiToken.user_id == user_id).order_by(ApiToken.created_at)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def revoke_token(db: Session, user_id: int, token_id: int) -> bool:
|
||||
result = db.execute(
|
||||
delete(ApiToken).where(ApiToken.id == token_id, ApiToken.user_id == user_id)
|
||||
)
|
||||
db.commit()
|
||||
return result.rowcount > 0
|
||||
|
||||
|
||||
def resolve_token(db: Session, plain: str | None, ip: str | None = None) -> ApiToken | None:
|
||||
"""The token for a raw value if valid (owner active); records when it was last used."""
|
||||
if not plain or not plain.startswith(TOKEN_PREFIX):
|
||||
return None
|
||||
token = db.scalar(select(ApiToken).where(ApiToken.token_hash == hash_token(plain)))
|
||||
if token is None or not token.user.is_active:
|
||||
return None
|
||||
now = utcnow()
|
||||
if (
|
||||
token.last_used_at is None
|
||||
or now - token.last_used_at >= TOUCH_INTERVAL
|
||||
or (ip is not None and ip != token.last_ip)
|
||||
):
|
||||
token.last_used_at = now
|
||||
token.last_ip = ip
|
||||
db.commit()
|
||||
return token
|
||||
|
||||
|
||||
def is_token_valid(db: Session, token_id: int) -> bool:
|
||||
token = db.get(ApiToken, token_id)
|
||||
return token is not None and token.user.is_active
|
||||
@@ -23,7 +23,9 @@ CLOSE_UNAUTHORIZED = 4401
|
||||
class Connection:
|
||||
websocket: WebSocket
|
||||
user_id: int
|
||||
session_id: int
|
||||
# Exactly one of these: browser session or device token
|
||||
session_id: int | None = None
|
||||
token_id: int | None = None
|
||||
|
||||
|
||||
class Hub:
|
||||
@@ -57,6 +59,9 @@ class Hub:
|
||||
async def close_session(self, session_id: int) -> None:
|
||||
await self._close_where(lambda c: c.session_id == session_id)
|
||||
|
||||
async def close_token(self, token_id: int) -> None:
|
||||
await self._close_where(lambda c: c.token_id == token_id)
|
||||
|
||||
async def close_user(self, user_id: int, except_session_id: int | None = None) -> None:
|
||||
await self._close_where(
|
||||
lambda c: c.user_id == user_id and c.session_id != except_session_id
|
||||
|
||||
Reference in new issue
Block a user