82 lines
2.9 KiB
Python
82 lines
2.9 KiB
Python
"""
|
|
Verwaltung der Zugriffstoken für die externe Gruppenpositions-API.
|
|
"""
|
|
import secrets
|
|
import sqlite3
|
|
|
|
from cmbnet.db import get_db
|
|
|
|
|
|
class ApiTokenService:
|
|
"""Erzeugt, liest, prüft und löscht mandantenweite API-Tokens."""
|
|
|
|
@staticmethod
|
|
def list_for_tenant(tenant_id):
|
|
"""Liefert alle Tokens eines Mandanten inklusive Ersteller."""
|
|
db = get_db()
|
|
rows = db.execute(
|
|
'''SELECT t.id, t.tenant_id, t.token, t.created_at,
|
|
t.created_by_account_id, a.name AS created_by_name
|
|
FROM api_tokens t
|
|
LEFT JOIN accounts a
|
|
ON a.id = t.created_by_account_id
|
|
AND a.tenant_id = t.tenant_id
|
|
WHERE t.tenant_id = ?
|
|
ORDER BY t.id''',
|
|
(tenant_id,)
|
|
).fetchall()
|
|
return [dict(row) for row in rows]
|
|
|
|
@staticmethod
|
|
def generate(tenant_id, created_by_account_id=None):
|
|
"""Erzeugt einen neuen zufälligen Token und speichert ihn."""
|
|
db = get_db()
|
|
for _ in range(10):
|
|
token = secrets.token_urlsafe(32)
|
|
try:
|
|
cursor = db.execute(
|
|
'''INSERT INTO api_tokens
|
|
(tenant_id, token, created_by_account_id)
|
|
VALUES (?, ?, ?)''',
|
|
(tenant_id, token, created_by_account_id)
|
|
)
|
|
db.commit()
|
|
row = db.execute(
|
|
'''SELECT t.id, t.tenant_id, t.token, t.created_at,
|
|
t.created_by_account_id, a.name AS created_by_name
|
|
FROM api_tokens t
|
|
LEFT JOIN accounts a
|
|
ON a.id = t.created_by_account_id
|
|
AND a.tenant_id = t.tenant_id
|
|
WHERE t.id = ?''',
|
|
(cursor.lastrowid,)
|
|
).fetchone()
|
|
return dict(row) if row else None
|
|
except sqlite3.IntegrityError:
|
|
# Eine Kollision ist bei 32 Byte Zufall praktisch
|
|
# ausgeschlossen, wird aber sauber erneut versucht.
|
|
db.rollback()
|
|
raise RuntimeError('Es konnte kein eindeutiger API-Token erzeugt werden')
|
|
|
|
@staticmethod
|
|
def delete(tenant_id, token_id):
|
|
"""Löscht einen Token. Gibt False zurück, wenn er nicht existiert."""
|
|
db = get_db()
|
|
cursor = db.execute(
|
|
'DELETE FROM api_tokens WHERE id = ? AND tenant_id = ?',
|
|
(token_id, tenant_id)
|
|
)
|
|
db.commit()
|
|
return cursor.rowcount > 0
|
|
|
|
@staticmethod
|
|
def validate(tenant_id, token):
|
|
"""Liefert den Token-Datensatz oder None bei ungültigem Token."""
|
|
if not token:
|
|
return None
|
|
db = get_db()
|
|
return db.execute(
|
|
'SELECT * FROM api_tokens WHERE tenant_id = ? AND token = ?',
|
|
(tenant_id, token)
|
|
).fetchone()
|