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
@@ -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
|
||||
Reference in new issue
Block a user