Upload files to "/"
This commit is contained in:
@@ -0,0 +1,866 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||
from dotenv import load_dotenv
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
load_dotenv(BASE_DIR / "config.env")
|
||||
|
||||
SESSION_COOKIE = "kronick_media_session"
|
||||
SESSION_TTL_SECONDS = int(os.getenv("KRONICK_SESSION_TTL_HOURS", "168")) * 3600
|
||||
COOKIE_SECURE = os.getenv("KRONICK_COOKIE_SECURE", "false").strip().lower() in {
|
||||
"1", "true", "yes", "on"
|
||||
}
|
||||
SESSION_SECRET = os.getenv(
|
||||
"KRONICK_SESSION_SECRET",
|
||||
"change-this-media-server-session-secret",
|
||||
).encode("utf-8")
|
||||
|
||||
PASSWORD_MIN_LENGTH = 8
|
||||
USERNAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{2,31}$")
|
||||
SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{2,47}$")
|
||||
|
||||
ROLE_PERMISSIONS = {
|
||||
"owner": {"view_media", "play_media", "manage_media", "manage_members", "manage_group"},
|
||||
"admin": {"view_media", "play_media", "manage_media", "manage_members"},
|
||||
"moderator": {"view_media", "play_media", "manage_media"},
|
||||
"member": {"view_media", "play_media"},
|
||||
}
|
||||
|
||||
DATABASE_PATH = Path(
|
||||
os.getenv(
|
||||
"KRONICK_ACCOUNT_DB",
|
||||
str(BASE_DIR / "kronick_accounts.sqlite3"),
|
||||
)
|
||||
).expanduser().resolve()
|
||||
|
||||
password_hasher = PasswordHasher()
|
||||
|
||||
|
||||
class AccountError(Exception):
|
||||
def __init__(self, status: int, detail: str):
|
||||
super().__init__(detail)
|
||||
self.status = int(status)
|
||||
self.detail = str(detail)
|
||||
|
||||
|
||||
def configure_accounts(database_path: str | Path | None = None) -> None:
|
||||
global DATABASE_PATH
|
||||
if database_path:
|
||||
DATABASE_PATH = Path(database_path).expanduser().resolve()
|
||||
|
||||
|
||||
def open_database() -> sqlite3.Connection:
|
||||
DATABASE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
db = sqlite3.connect(DATABASE_PATH, timeout=15)
|
||||
db.row_factory = sqlite3.Row
|
||||
db.execute("PRAGMA foreign_keys = ON")
|
||||
db.execute("PRAGMA busy_timeout = 15000")
|
||||
return db
|
||||
|
||||
|
||||
def _session_hash(token: str) -> str:
|
||||
return hmac.new(
|
||||
SESSION_SECRET,
|
||||
token.encode("utf-8"),
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
|
||||
|
||||
def public_user(row: sqlite3.Row | dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"username": row["username"],
|
||||
"email": row["email"],
|
||||
"status": row["status"],
|
||||
"isPlatformAdmin": bool(row["is_platform_admin"]),
|
||||
"createdAt": row["created_at"],
|
||||
"approvedAt": row["approved_at"],
|
||||
"lastLoginAt": row["last_login_at"],
|
||||
}
|
||||
|
||||
|
||||
def initialize_account_database() -> None:
|
||||
with open_database() as db:
|
||||
db.execute("PRAGMA journal_mode = WAL")
|
||||
db.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
password_hash TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending'
|
||||
CHECK(status IN ('pending','active','disabled','banned','denied')),
|
||||
is_platform_admin INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
approved_at INTEGER,
|
||||
last_login_at INTEGER
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_sessions (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
last_seen_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_sessions_user ON user_sessions(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_sessions_expiry ON user_sessions(expires_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS groups (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
slug TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
status TEXT NOT NULL DEFAULT 'active',
|
||||
owner_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||
max_users INTEGER NOT NULL DEFAULT 10,
|
||||
max_rooms INTEGER NOT NULL DEFAULT 10,
|
||||
storage_limit_mb INTEGER NOT NULL DEFAULT 1024,
|
||||
media_enabled INTEGER NOT NULL DEFAULT 1,
|
||||
subscription_status TEXT NOT NULL DEFAULT 'active',
|
||||
expires_at INTEGER,
|
||||
custom_branding_json TEXT NOT NULL DEFAULT '{}',
|
||||
custom_domain TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS group_memberships (
|
||||
group_id INTEGER NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
role TEXT NOT NULL DEFAULT 'member'
|
||||
CHECK(role IN ('owner','admin','moderator','member')),
|
||||
created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY(group_id, user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_memberships_user ON group_memberships(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS managed_rooms (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
group_id INTEGER NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
|
||||
room_name TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
display_name TEXT NOT NULL DEFAULT '',
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
created_by_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_managed_rooms_group ON managed_rooms(group_id);
|
||||
CREATE TABLE IF NOT EXISTS role_permissions (
|
||||
role TEXT NOT NULL CHECK(role IN ('member','moderator','admin','owner')),
|
||||
action TEXT NOT NULL CHECK(action IN ('media_access','user_permissions','room_permissions','password_resets','account_approvals')),
|
||||
allowed INTEGER NOT NULL CHECK(allowed IN (0,1)),
|
||||
PRIMARY KEY(role,action)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS room_memberships (
|
||||
room_id INTEGER NOT NULL REFERENCES managed_rooms(id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
role TEXT NOT NULL DEFAULT 'member'
|
||||
CHECK(role IN ('owner','admin','moderator','member')),
|
||||
created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY(room_id,user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_room_memberships_user ON room_memberships(user_id);
|
||||
"""
|
||||
)
|
||||
now = int(time.time())
|
||||
db.execute("DELETE FROM user_sessions WHERE expires_at <= ?", (now,))
|
||||
db.commit()
|
||||
|
||||
bootstrap_admin()
|
||||
|
||||
|
||||
def bootstrap_admin() -> None:
|
||||
username = os.getenv("KRONICK_ADMIN_USERNAME", "").strip()
|
||||
email = os.getenv("KRONICK_ADMIN_EMAIL", "").strip().lower()
|
||||
password = os.getenv("KRONICK_ADMIN_PASSWORD", "")
|
||||
if not username or not email or not password:
|
||||
return
|
||||
if len(password) < PASSWORD_MIN_LENGTH:
|
||||
raise RuntimeError("KRONICK_ADMIN_PASSWORD must be at least 8 characters")
|
||||
|
||||
now = int(time.time())
|
||||
with open_database() as db:
|
||||
row = db.execute(
|
||||
"SELECT id FROM users WHERE username = ? OR email = ?",
|
||||
(username, email),
|
||||
).fetchone()
|
||||
if row:
|
||||
db.execute(
|
||||
"UPDATE users SET status='active', is_platform_admin=1 WHERE id=?",
|
||||
(row["id"],),
|
||||
)
|
||||
else:
|
||||
db.execute(
|
||||
"""INSERT INTO users
|
||||
(username,email,password_hash,status,is_platform_admin,created_at,approved_at)
|
||||
VALUES (?,?,?,?,?,?,?)""",
|
||||
(username, email, password_hasher.hash(password), "active", 1, now, now),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
|
||||
def signup_account(data: dict[str, Any]) -> dict[str, Any]:
|
||||
username = str(data.get("username") or "").strip()
|
||||
email = str(data.get("email") or "").strip().lower()
|
||||
password = str(data.get("password") or "")
|
||||
|
||||
if "@" not in email or len(email) > 254:
|
||||
raise AccountError(400, "Enter a valid email address.")
|
||||
if not USERNAME_RE.fullmatch(username):
|
||||
raise AccountError(
|
||||
400,
|
||||
"Username must be 3-32 characters and use letters, numbers, dot, dash, or underscore.",
|
||||
)
|
||||
if len(password) < PASSWORD_MIN_LENGTH:
|
||||
raise AccountError(400, "Password must be at least 8 characters.")
|
||||
|
||||
now = int(time.time())
|
||||
try:
|
||||
with open_database() as db:
|
||||
db.execute(
|
||||
"""INSERT INTO users(username,email,password_hash,status,created_at)
|
||||
VALUES (?,?,?,?,?)""",
|
||||
(username, email, password_hasher.hash(password), "pending", now),
|
||||
)
|
||||
db.commit()
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise AccountError(409, "That username or email is already registered.") from exc
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"status": "pending",
|
||||
"message": "Account request submitted for administrator approval.",
|
||||
}
|
||||
|
||||
|
||||
def login_account(data: dict[str, Any]) -> tuple[dict[str, Any], str]:
|
||||
login_value = str(data.get("login") or "").strip()
|
||||
password = str(data.get("password") or "")
|
||||
|
||||
with open_database() as db:
|
||||
user = db.execute(
|
||||
"SELECT * FROM users WHERE username=? OR email=?",
|
||||
(login_value, login_value),
|
||||
).fetchone()
|
||||
|
||||
if not user:
|
||||
raise AccountError(401, "Incorrect username/email or password.")
|
||||
|
||||
try:
|
||||
valid = password_hasher.verify(user["password_hash"], password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
valid = False
|
||||
|
||||
if not valid:
|
||||
raise AccountError(401, "Incorrect username/email or password.")
|
||||
|
||||
if user["status"] != "active":
|
||||
messages = {
|
||||
"pending": "Your account is waiting for administrator approval.",
|
||||
"disabled": "Your account is disabled.",
|
||||
"banned": "Your account is banned.",
|
||||
"denied": "Your account request was denied.",
|
||||
}
|
||||
raise AccountError(403, messages.get(user["status"], "Your account is not active."))
|
||||
|
||||
if 'must_change_password' in user.keys() and user['must_change_password']:
|
||||
raise AccountError(403,'Password change required. Sign in through Kronic Chat to set your new password.')
|
||||
|
||||
token = secrets.token_urlsafe(48)
|
||||
token_hash = _session_hash(token)
|
||||
now = int(time.time())
|
||||
|
||||
with open_database() as db:
|
||||
db.execute(
|
||||
"INSERT INTO user_sessions(token_hash,user_id,created_at,expires_at,last_seen_at) VALUES (?,?,?,?,?)",
|
||||
(token_hash, user["id"], now, now + SESSION_TTL_SECONDS, now),
|
||||
)
|
||||
db.execute("UPDATE users SET last_login_at=? WHERE id=?", (now, user["id"]))
|
||||
db.commit()
|
||||
|
||||
refreshed = session_user(token)
|
||||
return {"ok": True, "user": public_user(refreshed)}, token
|
||||
|
||||
|
||||
def logout_account(token: str | None) -> None:
|
||||
if not token:
|
||||
return
|
||||
with open_database() as db:
|
||||
db.execute("DELETE FROM user_sessions WHERE token_hash=?", (_session_hash(token),))
|
||||
db.commit()
|
||||
|
||||
|
||||
def session_user(token: str | None, *, require_active: bool = True) -> sqlite3.Row:
|
||||
if not token:
|
||||
raise AccountError(401, "Login required.")
|
||||
|
||||
now = int(time.time())
|
||||
token_hash = _session_hash(token)
|
||||
with open_database() as db:
|
||||
row = db.execute(
|
||||
"""SELECT u.* FROM user_sessions s
|
||||
JOIN users u ON u.id=s.user_id
|
||||
WHERE s.token_hash=? AND s.expires_at>?""",
|
||||
(token_hash, now),
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise AccountError(401, "Session expired. Please log in again.")
|
||||
if require_active and row["status"] != "active":
|
||||
raise AccountError(403, f"Account is {row['status']}.")
|
||||
db.execute("UPDATE user_sessions SET last_seen_at=? WHERE token_hash=?", (now, token_hash))
|
||||
db.commit()
|
||||
return row
|
||||
|
||||
|
||||
def media_context(token: str | None) -> dict[str, Any]:
|
||||
user = session_user(token)
|
||||
now = int(time.time())
|
||||
from room_access_scope import current
|
||||
room_id = current(user["id"])
|
||||
|
||||
with open_database() as db:
|
||||
groups = db.execute(
|
||||
"""SELECT g.*, gm.role
|
||||
FROM groups g
|
||||
JOIN group_memberships gm ON gm.group_id=g.id
|
||||
WHERE gm.user_id=?
|
||||
AND g.status='active'
|
||||
AND g.media_enabled=1
|
||||
AND g.subscription_status IN ('active','trial','free')
|
||||
AND (g.expires_at IS NULL OR g.expires_at > ?)
|
||||
AND (? IS NULL OR g.id=(SELECT group_id FROM managed_rooms WHERE id=?))
|
||||
ORDER BY g.name""",
|
||||
(user["id"], now, room_id, room_id),
|
||||
).fetchall()
|
||||
|
||||
permissions: set[str] = set()
|
||||
if user["is_platform_admin"]:
|
||||
permissions.update({
|
||||
"view_media", "play_media", "manage_media",
|
||||
"manage_members", "manage_group", "platform_admin",
|
||||
})
|
||||
else:
|
||||
for group in groups:
|
||||
permissions.update(ROLE_PERMISSIONS.get(group["role"], {"view_media", "play_media"}))
|
||||
|
||||
has_media_access = bool(user["is_platform_admin"] or groups)
|
||||
allowed = allowed_media_libraries(int(user['id'])) if has_media_access else {key:False for key in MEDIA_KEYS}
|
||||
can_manage = 'manage_media' in permissions and not global_media_restricted(int(user['id']))
|
||||
|
||||
return {
|
||||
"user": public_user(user),
|
||||
"groups": [dict(row) for row in groups],
|
||||
"permissions": sorted(permissions),
|
||||
"hasMediaAccess": has_media_access,
|
||||
"allowedLibraries": allowed,
|
||||
"canManageMedia": can_manage,
|
||||
"selectedRoomId": room_id,
|
||||
"isPlatformAdmin": bool(user["is_platform_admin"]),
|
||||
}
|
||||
|
||||
|
||||
MEDIA_KEYS = ('movies','tv','music','iptv','tube','twitch')
|
||||
|
||||
|
||||
def allowed_media_libraries(user_id: int) -> dict[str,bool]:
|
||||
# Scoped requests only consider the selected room. Legacy internal calls remain conservative.
|
||||
from room_access_scope import current
|
||||
room_id=current(user_id)
|
||||
from admin_policies import policies
|
||||
rules=policies(user_id)
|
||||
result={key:all(key in r['types'] for r in rules) for key in MEDIA_KEYS}
|
||||
with open_database() as db:
|
||||
user=db.execute("SELECT is_platform_admin FROM users WHERE id=?",(user_id,)).fetchone()
|
||||
if user and user["is_platform_admin"]:
|
||||
return {key:True for key in MEDIA_KEYS}
|
||||
if not db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='room_media_permissions'").fetchone():
|
||||
return result
|
||||
rows=db.execute('''SELECT library_key,enabled FROM room_media_permissions p
|
||||
JOIN room_memberships rm ON rm.user_id=p.user_id AND rm.room_id=p.room_id
|
||||
WHERE p.user_id=? AND (? IS NULL OR p.room_id=?)''',(user_id,room_id,room_id)).fetchall()
|
||||
for row in rows:
|
||||
if row['library_key'] in result and not row['enabled']:
|
||||
result[row['library_key']]=False
|
||||
return result
|
||||
|
||||
|
||||
def enforce_media_library(user_id:int,key:str)->None:
|
||||
if key in MEDIA_KEYS and not allowed_media_libraries(user_id)[key]:
|
||||
raise AccountError(403,f'Access to {key} is disabled by your room administrator.')
|
||||
|
||||
|
||||
def require_media_access(token: str | None) -> dict[str, Any]:
|
||||
context = media_context(token)
|
||||
if not context["hasMediaAccess"]:
|
||||
raise AccountError(
|
||||
403,
|
||||
"Your account is active but is not assigned to a media-enabled group.",
|
||||
)
|
||||
return context
|
||||
|
||||
|
||||
def global_media_restricted(user_id: int) -> bool:
|
||||
"""Unscoped tools can alter shared state, so preserve their conservative gate."""
|
||||
from admin_policies import policies
|
||||
from room_access_scope import clear, restore
|
||||
scope=clear()
|
||||
try:
|
||||
return bool(policies(user_id)) or not all(allowed_media_libraries(user_id).values())
|
||||
finally: restore(scope)
|
||||
|
||||
|
||||
def require_manage_media(token: str | None) -> dict[str, Any]:
|
||||
context = require_media_access(token)
|
||||
if not context["canManageMedia"] or not all(context["allowedLibraries"].values()):
|
||||
raise AccountError(403, "Media management permission required.")
|
||||
return context
|
||||
|
||||
|
||||
def require_admin(token: str | None) -> sqlite3.Row:
|
||||
user = session_user(token)
|
||||
if not user["is_platform_admin"]:
|
||||
raise AccountError(403, "Platform administrator access required.")
|
||||
return user
|
||||
|
||||
|
||||
# These role rules apply to chat-room administration, NOT the right to play media.
|
||||
# The platform-admin account has an unconditional instance-level override.
|
||||
ROOM_PERMISSION_ACTIONS = ('media_access', 'user_permissions', 'room_permissions', 'password_resets', 'account_approvals')
|
||||
ROOM_PERMISSION_ROLES = ('member', 'moderator', 'admin', 'owner')
|
||||
DEFAULT_ROOM_ROLE_POLICY = {
|
||||
'member': (False, False, False, False, False),
|
||||
'moderator': (False, False, False, False, False),
|
||||
'admin': (True, True, True, True, True),
|
||||
'owner': (True, True, True, True, True),
|
||||
}
|
||||
|
||||
|
||||
def admin_get_role_permissions(token: str | None) -> dict[str, Any]:
|
||||
require_admin(token)
|
||||
with open_database() as db:
|
||||
rows = db.execute('SELECT role,action,allowed FROM role_permissions').fetchall()
|
||||
policy = {role: dict(zip(ROOM_PERMISSION_ACTIONS, defaults))
|
||||
for role, defaults in DEFAULT_ROOM_ROLE_POLICY.items()}
|
||||
for row in rows:
|
||||
if row['role'] in policy and row['action'] in ROOM_PERMISSION_ACTIONS:
|
||||
policy[row['role']][row['action']] = bool(row['allowed'])
|
||||
return {'roles': policy, 'actions': list(ROOM_PERMISSION_ACTIONS)}
|
||||
|
||||
|
||||
def admin_set_role_permissions(token: str | None, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
require_admin(token)
|
||||
values = payload.get('roles')
|
||||
if not isinstance(values, dict) or set(values) != set(ROOM_PERMISSION_ROLES):
|
||||
raise AccountError(400, 'All room roles must be provided.')
|
||||
items = []
|
||||
for role in ROOM_PERMISSION_ROLES:
|
||||
options = values[role]
|
||||
if not isinstance(options, dict) or set(options) != set(ROOM_PERMISSION_ACTIONS):
|
||||
raise AccountError(400, f'Invalid actions for {role}.')
|
||||
for action, allowed in options.items():
|
||||
if type(allowed) is not bool:
|
||||
raise AccountError(400, 'Permission values must be true or false.')
|
||||
items.append((role, action, int(allowed)))
|
||||
# Prevent any admin-panel misconfiguration from removing all room policy authority.
|
||||
if not all(values['owner'].values()):
|
||||
raise AccountError(400, 'Room owners must retain every management capability.')
|
||||
with open_database() as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
db.executemany('''INSERT INTO role_permissions(role,action,allowed) VALUES (?,?,?)
|
||||
ON CONFLICT(role,action) DO UPDATE SET allowed=excluded.allowed''', items)
|
||||
db.commit()
|
||||
return admin_get_role_permissions(token)
|
||||
|
||||
|
||||
def admin_overview(token: str | None) -> dict[str, Any]:
|
||||
require_admin(token)
|
||||
with open_database() as db:
|
||||
users = db.execute("SELECT * FROM users ORDER BY created_at DESC").fetchall()
|
||||
groups = db.execute(
|
||||
"""SELECT g.*,
|
||||
(SELECT COUNT(*) FROM group_memberships gm WHERE gm.group_id=g.id) AS user_count,
|
||||
(SELECT COUNT(*) FROM managed_rooms mr WHERE mr.group_id=g.id) AS room_count
|
||||
FROM groups g ORDER BY g.name"""
|
||||
).fetchall()
|
||||
memberships = db.execute(
|
||||
"""SELECT gm.group_id,gm.user_id,gm.role,u.username,u.email,g.name AS group_name
|
||||
FROM group_memberships gm
|
||||
JOIN users u ON u.id=gm.user_id
|
||||
JOIN groups g ON g.id=gm.group_id
|
||||
ORDER BY g.name,u.username"""
|
||||
).fetchall()
|
||||
|
||||
rooms = db.execute("""SELECT mr.*,g.name AS group_name FROM managed_rooms mr
|
||||
JOIN groups g ON g.id=mr.group_id ORDER BY mr.room_name""").fetchall()
|
||||
return {
|
||||
"rooms": [dict(row) for row in rooms],
|
||||
"users": [public_user(row) for row in users],
|
||||
"groups": [dict(row) for row in groups],
|
||||
"memberships": [dict(row) for row in memberships],
|
||||
"roles": {key: sorted(value) for key, value in ROLE_PERMISSIONS.items()},
|
||||
}
|
||||
|
||||
|
||||
|
||||
def admin_room_memberships(token: str | None) -> dict[str, Any]:
|
||||
require_admin(token)
|
||||
with open_database() as db:
|
||||
rows = db.execute("""SELECT rm.room_id,rm.user_id,rm.role,u.username,
|
||||
u.is_platform_admin,mr.room_name,mr.display_name,g.name AS group_name
|
||||
FROM room_memberships rm JOIN users u ON u.id=rm.user_id
|
||||
JOIN managed_rooms mr ON mr.id=rm.room_id
|
||||
JOIN groups g ON g.id=mr.group_id ORDER BY mr.room_name,u.username""").fetchall()
|
||||
return {"memberships": [dict(row) for row in rows]}
|
||||
|
||||
|
||||
def admin_assign_room_member(token: str | None, room_id: int, payload: dict) -> dict[str, bool]:
|
||||
require_admin(token)
|
||||
try:
|
||||
user_id = int(payload.get('user_id'))
|
||||
except (TypeError,ValueError):
|
||||
raise AccountError(400,'Invalid user ID')
|
||||
role = str(payload.get('role','')).strip().lower()
|
||||
if role not in ('member','moderator','admin','owner'):
|
||||
raise AccountError(400,'Invalid room role')
|
||||
with open_database() as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
room = db.execute('SELECT id,group_id FROM managed_rooms WHERE id=?',(room_id,)).fetchone()
|
||||
user = db.execute('SELECT status FROM users WHERE id=?',(user_id,)).fetchone()
|
||||
if not room:
|
||||
raise AccountError(404,'Room not found')
|
||||
if not user or user['status']!='active':
|
||||
raise AccountError(400,'An active user is required')
|
||||
member = db.execute('SELECT 1 FROM group_memberships WHERE group_id=? AND user_id=?',
|
||||
(room['group_id'],user_id)).fetchone()
|
||||
if not member:
|
||||
group = db.execute('SELECT max_users FROM groups WHERE id=?',(room['group_id'],)).fetchone()
|
||||
count = db.execute('SELECT COUNT(*) FROM group_memberships WHERE group_id=?',
|
||||
(room['group_id'],)).fetchone()[0]
|
||||
if count >= group['max_users']:
|
||||
raise AccountError(409,'Parent group is full')
|
||||
db.execute('INSERT INTO group_memberships(group_id,user_id,role,created_at) VALUES(?,?,?,?)',
|
||||
(room['group_id'],user_id,'member',int(time.time())))
|
||||
# An owner can hand ownership to another member, but may not leave a room ownerless.
|
||||
existing = db.execute('SELECT role FROM room_memberships WHERE room_id=? AND user_id=?',
|
||||
(room_id,user_id)).fetchone()
|
||||
if existing and existing['role'] == 'owner' and role != 'owner':
|
||||
owners = db.execute("SELECT COUNT(*) FROM room_memberships WHERE room_id=? AND role='owner'",
|
||||
(room_id,)).fetchone()[0]
|
||||
if owners <= 1:
|
||||
raise AccountError(409, 'Assign another room owner before demoting the last owner.')
|
||||
db.execute("""INSERT INTO room_memberships(room_id,user_id,role,created_at)
|
||||
VALUES(?,?,?,?) ON CONFLICT(room_id,user_id) DO UPDATE SET role=excluded.role""",
|
||||
(room_id,user_id,role,int(time.time())))
|
||||
db.commit()
|
||||
return {'ok':True}
|
||||
|
||||
|
||||
def admin_remove_room_member(token: str | None, room_id: int, user_id: int) -> dict[str, bool]:
|
||||
require_admin(token)
|
||||
with open_database() as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
old_role = db.execute('SELECT role FROM room_memberships WHERE room_id=? AND user_id=?',
|
||||
(room_id,user_id)).fetchone()
|
||||
if old_role and old_role['role'] == 'owner':
|
||||
owners = db.execute("SELECT COUNT(*) FROM room_memberships WHERE room_id=? AND role='owner'",
|
||||
(room_id,)).fetchone()[0]
|
||||
if owners <= 1:
|
||||
raise AccountError(409, 'Assign another room owner before removing the last owner.')
|
||||
cur = db.execute('DELETE FROM room_memberships WHERE room_id=? AND user_id=?',
|
||||
(room_id,user_id))
|
||||
if not cur.rowcount:
|
||||
raise AccountError(404,'Room membership not found')
|
||||
db.commit()
|
||||
return {'ok':True}
|
||||
|
||||
def admin_set_user_status(token: str | None, user_id: int, status: str) -> dict[str, Any]:
|
||||
admin = require_admin(token)
|
||||
status = str(status or "").strip().lower()
|
||||
if status not in {"pending", "active", "disabled", "banned", "denied"}:
|
||||
raise AccountError(400, "Invalid account status.")
|
||||
if admin["id"] == user_id and status != "active":
|
||||
raise AccountError(400, "You cannot disable your own administrator account.")
|
||||
|
||||
now = int(time.time())
|
||||
with open_database() as db:
|
||||
result = db.execute(
|
||||
"UPDATE users SET status=?, approved_at=CASE WHEN ?='active' THEN COALESCE(approved_at,?) ELSE approved_at END WHERE id=?",
|
||||
(status, status, now, user_id),
|
||||
)
|
||||
if result.rowcount == 0:
|
||||
raise AccountError(404, "User not found.")
|
||||
if status != "active":
|
||||
db.execute("DELETE FROM user_sessions WHERE user_id=?", (user_id,))
|
||||
db.commit()
|
||||
return {"ok": True, "status": status}
|
||||
|
||||
|
||||
|
||||
def admin_delete_user(token: str | None, user_id: int) -> dict[str, Any]:
|
||||
"""Permanently delete a non-platform-admin account and dependent account rows."""
|
||||
actor = require_admin(token)
|
||||
if actor["id"] == user_id:
|
||||
raise AccountError(400, "You cannot delete your own account.")
|
||||
with open_database() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
target = db.execute("SELECT id,username,is_platform_admin FROM users WHERE id=?", (user_id,)).fetchone()
|
||||
if target is None:
|
||||
raise AccountError(404, "Account not found.")
|
||||
if target["is_platform_admin"]:
|
||||
raise AccountError(403, "Platform administrator accounts cannot be deleted from this interface.")
|
||||
# Database FK cascades remove sessions, memberships, room requests,
|
||||
# invitation redemptions, and password reset state. References in
|
||||
# authored/owned objects are ON DELETE SET NULL.
|
||||
db.execute("DELETE FROM users WHERE id=?", (user_id,))
|
||||
db.commit()
|
||||
return {"ok": True, "deletedUserId": user_id}
|
||||
|
||||
def admin_create_group(token: str | None, data: dict[str, Any]) -> dict[str, Any]:
|
||||
admin = require_admin(token)
|
||||
name = str(data.get("name") or "").strip()
|
||||
slug = str(data.get("slug") or "").strip().lower()
|
||||
max_users = max(1, min(int(data.get("max_users") or 10), 10000))
|
||||
media_enabled = bool(data.get("media_enabled", True))
|
||||
|
||||
if not name:
|
||||
raise AccountError(400, "Group name is required.")
|
||||
if not SLUG_RE.fullmatch(slug):
|
||||
raise AccountError(400, "Group slug must be 3-48 lowercase letters/numbers/dash/underscore.")
|
||||
|
||||
now = int(time.time())
|
||||
try:
|
||||
with open_database() as db:
|
||||
cursor = db.execute(
|
||||
"""INSERT INTO groups
|
||||
(name,slug,status,owner_user_id,max_users,max_rooms,storage_limit_mb,media_enabled,subscription_status,custom_domain,created_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(name, slug, "active", admin["id"], max_users, 1, 1024, int(media_enabled), "active", "", now),
|
||||
)
|
||||
group_id = cursor.lastrowid
|
||||
db.execute(
|
||||
"INSERT INTO group_memberships(group_id,user_id,role,created_at) VALUES (?,?,?,?)",
|
||||
(group_id, admin["id"], "owner", now),
|
||||
)
|
||||
db.commit()
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise AccountError(409, "That group slug already exists.") from exc
|
||||
|
||||
return {"ok": True, "groupId": group_id}
|
||||
|
||||
|
||||
def admin_create_managed_room(token: str | None, group_id: int, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Explicitly create a chat room within an existing media group.
|
||||
|
||||
Room creation is separate from group creation; avoid creating implicit
|
||||
rooms or approving accounts as a side effect.
|
||||
"""
|
||||
admin = require_admin(token)
|
||||
room_name = str(data.get("room_name") or "").strip().lower()
|
||||
display_name = str(data.get("display_name") or "").strip() or room_name
|
||||
if not SLUG_RE.fullmatch(room_name):
|
||||
raise AccountError(400, "Room name must be 3-48 lowercase letters, digits, hyphens or underscores.")
|
||||
if len(display_name) > 100:
|
||||
raise AccountError(400, "Display name is too long.")
|
||||
now = int(time.time())
|
||||
try:
|
||||
with open_database() as db:
|
||||
group = db.execute("SELECT id,max_rooms,status FROM groups WHERE id=?", (group_id,)).fetchone()
|
||||
if group is None or group["status"] != "active":
|
||||
raise AccountError(404, "Active group not found.")
|
||||
used = db.execute("SELECT COUNT(*) FROM managed_rooms WHERE group_id=?", (group_id,)).fetchone()[0]
|
||||
if used >= group["max_rooms"]:
|
||||
raise AccountError(409, "This group has reached its room limit.")
|
||||
cursor = db.execute(
|
||||
"""INSERT INTO managed_rooms(group_id,room_name,display_name,enabled,created_by_user_id,created_at)
|
||||
VALUES (?,?,?,?,?,?)""",
|
||||
(group_id, room_name, display_name, 1, admin["id"], now),
|
||||
)
|
||||
room_id = cursor.lastrowid
|
||||
from admin_policies import copy_template
|
||||
copy_template(db,room_id,data.get("template_id"))
|
||||
db.execute(
|
||||
"""INSERT INTO room_memberships(room_id,user_id,role,created_at)
|
||||
SELECT ?,user_id,role,? FROM group_memberships WHERE group_id=?""",
|
||||
(room_id,now,group_id),
|
||||
)
|
||||
db.commit()
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise AccountError(409, "That room name already exists.") from exc
|
||||
return {"ok": True, "roomId": room_id, "room": room_name}
|
||||
|
||||
|
||||
def admin_toggle_group_media(token: str | None, group_id: int, enabled: bool) -> dict[str, Any]:
|
||||
require_admin(token)
|
||||
with open_database() as db:
|
||||
result = db.execute(
|
||||
"UPDATE groups SET media_enabled=? WHERE id=?",
|
||||
(int(bool(enabled)), group_id),
|
||||
)
|
||||
if result.rowcount == 0:
|
||||
raise AccountError(404, "Group not found.")
|
||||
db.commit()
|
||||
return {"ok": True, "media_enabled": bool(enabled)}
|
||||
|
||||
|
||||
def admin_assign_member(token: str | None, group_id: int, data: dict[str, Any]) -> dict[str, Any]:
|
||||
require_admin(token)
|
||||
user_id = int(data.get("user_id"))
|
||||
role = str(data.get("role") or "member").strip().lower()
|
||||
if role not in ROLE_PERMISSIONS:
|
||||
raise AccountError(400, "Invalid role.")
|
||||
|
||||
now = int(time.time())
|
||||
with open_database() as db:
|
||||
group = db.execute("SELECT max_users FROM groups WHERE id=?", (group_id,)).fetchone()
|
||||
user = db.execute("SELECT status FROM users WHERE id=?", (user_id,)).fetchone()
|
||||
if not group:
|
||||
raise AccountError(404, "Group not found.")
|
||||
if not user:
|
||||
raise AccountError(404, "User not found.")
|
||||
if user["status"] != "active":
|
||||
raise AccountError(400, "Only active users can be assigned to groups.")
|
||||
existing = db.execute(
|
||||
"SELECT 1 FROM group_memberships WHERE group_id=? AND user_id=?",
|
||||
(group_id, user_id),
|
||||
).fetchone()
|
||||
count = db.execute(
|
||||
"SELECT COUNT(*) AS n FROM group_memberships WHERE group_id=?",
|
||||
(group_id,),
|
||||
).fetchone()["n"]
|
||||
if not existing and count >= group["max_users"]:
|
||||
raise AccountError(409, "This group has reached its user limit.")
|
||||
|
||||
db.execute(
|
||||
"""INSERT INTO group_memberships(group_id,user_id,role,created_at) VALUES (?,?,?,?)
|
||||
ON CONFLICT(group_id,user_id) DO UPDATE SET role=excluded.role""",
|
||||
(group_id, user_id, role, now),
|
||||
)
|
||||
db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
def admin_remove_member(token: str | None, group_id: int, user_id: int) -> dict[str, Any]:
|
||||
require_admin(token)
|
||||
with open_database() as db:
|
||||
db.execute(
|
||||
"DELETE FROM group_memberships WHERE group_id=? AND user_id=?",
|
||||
(group_id, user_id),
|
||||
)
|
||||
db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
def create_sso_session(identity: dict[str, Any]) -> str:
|
||||
"""Create a short-lived Media session after Chat's server validates its cookie.
|
||||
|
||||
Matching local accounts are preserved. Chat groups become non-privileged
|
||||
Media groups with isolated 'sso-' slugs to avoid overriding existing ACLs.
|
||||
"""
|
||||
user = identity.get("user") or {}
|
||||
username = str(user.get("username") or "")
|
||||
email = str(user.get("email") or "").lower()
|
||||
if (not USERNAME_RE.fullmatch(username) or "@" not in email or
|
||||
user.get("status") != "active"):
|
||||
raise AccountError(403, "Invalid or inactive Chat account")
|
||||
groups = identity.get("mediaGroups") or []
|
||||
if not groups and not bool(user.get("isPlatformAdmin")):
|
||||
raise AccountError(403, "No media-enabled Chat group assigned")
|
||||
now = int(time.time())
|
||||
token = secrets.token_urlsafe(48)
|
||||
with open_database() as db:
|
||||
row = db.execute("SELECT * FROM users WHERE username=? OR email=?", (username, email)).fetchone()
|
||||
if row and (row["username"].lower() != username.lower() or
|
||||
row["email"].lower() != email):
|
||||
raise AccountError(409, "Media account identity conflict; contact the administrator")
|
||||
sso_marker = f"!sso-managed:{user.get('id')}"
|
||||
if row and row["password_hash"] != sso_marker:
|
||||
raise AccountError(409, "Existing Media account needs explicit SSO migration")
|
||||
if row and row["status"] != "active":
|
||||
raise AccountError(403, "Media account is disabled or pending")
|
||||
if row:
|
||||
user_id = row["id"]
|
||||
else:
|
||||
db.execute(
|
||||
"""INSERT INTO users(username,email,password_hash,status,created_at,approved_at)
|
||||
VALUES (?,?,?,?,?,?)""",
|
||||
(username, email, sso_marker,
|
||||
"active", now, now),
|
||||
)
|
||||
user_id = db.execute("SELECT last_insert_rowid()").fetchone()[0]
|
||||
# Rebuild only SSO-controlled memberships, not local media permissions.
|
||||
db.execute(
|
||||
"""DELETE FROM group_memberships WHERE user_id=? AND group_id IN
|
||||
(SELECT id FROM groups WHERE slug LIKE 'sso-chat-%')""", (user_id,)
|
||||
)
|
||||
for group in groups:
|
||||
try:
|
||||
remote_id = int(group["id"])
|
||||
except (TypeError, ValueError, KeyError):
|
||||
continue
|
||||
if remote_id <= 0:
|
||||
continue
|
||||
slug = f"sso-chat-{remote_id}"
|
||||
name = "Chat: " + str(group.get("name") or slug)[:100]
|
||||
db.execute(
|
||||
"""INSERT OR IGNORE INTO groups(name,slug,status,media_enabled,
|
||||
subscription_status,created_at) VALUES (?,?,'active',1,'active',?)""",
|
||||
(name, slug, now),
|
||||
)
|
||||
media_group_id = db.execute("SELECT id FROM groups WHERE slug=?", (slug,)).fetchone()[0]
|
||||
db.execute(
|
||||
"""INSERT OR IGNORE INTO group_memberships
|
||||
(group_id,user_id,role,created_at) VALUES (?,?,'member',?)""",
|
||||
(media_group_id, user_id, now),
|
||||
)
|
||||
db.execute(
|
||||
"""INSERT INTO user_sessions(token_hash,user_id,created_at,expires_at,last_seen_at)
|
||||
VALUES (?,?,?,?,?)""",
|
||||
(_session_hash(token), user_id, now, now + 3600, now),
|
||||
)
|
||||
db.commit()
|
||||
return token
|
||||
|
||||
|
||||
# Room selection is based on explicit active room memberships, not group roles.
|
||||
def assigned_rooms(token):
|
||||
user = session_user(token)
|
||||
with open_database() as db:
|
||||
rows = db.execute("""SELECT mr.id,mr.room_name,mr.display_name,rm.role
|
||||
FROM managed_rooms mr JOIN groups g ON g.id=mr.group_id
|
||||
JOIN room_memberships rm ON rm.room_id=mr.id
|
||||
WHERE rm.user_id=? AND mr.enabled=1 AND g.status='active'
|
||||
ORDER BY mr.display_name COLLATE NOCASE,mr.room_name""", (user['id'],)).fetchall()
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
|
||||
def rename_room_display(token, room_id, data, *, instance_only=False):
|
||||
user = session_user(token)
|
||||
from admin_policies import appearance
|
||||
if not user['is_platform_admin'] and not appearance()['allow_owner_rename']:
|
||||
raise AccountError(403,'Room title customization disabled by instance administrator')
|
||||
title = data.get('display_name')
|
||||
if not isinstance(title, str) or not title.strip() or len(title.strip()) > 100 or any(ord(c)<32 for c in title):
|
||||
raise AccountError(400, 'Enter a display title of 1–100 characters.')
|
||||
with open_database() as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
room = db.execute("""SELECT mr.id,rm.role FROM managed_rooms mr
|
||||
JOIN groups g ON g.id=mr.group_id
|
||||
LEFT JOIN room_memberships rm ON rm.room_id=mr.id AND rm.user_id=?
|
||||
WHERE mr.id=? AND mr.enabled=1 AND g.status='active'""",(user['id'],room_id)).fetchone()
|
||||
if not room or not (user['is_platform_admin'] or (not instance_only and room['role']=='owner')):
|
||||
raise AccountError(403, 'Room owner or instance administrator required.')
|
||||
db.execute('UPDATE managed_rooms SET display_name=? WHERE id=?',(title.strip(),room_id))
|
||||
db.commit()
|
||||
return {'ok':True,'display_name':title.strip()}
|
||||
Reference in New Issue
Block a user