Upload files to "/"
This commit is contained in:
@@ -0,0 +1,153 @@
|
|||||||
|
"""Instance-managed, additive media policies. Existing room denials remain in force."""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from media_accounts import open_database, require_admin, AccountError, MEDIA_KEYS
|
||||||
|
|
||||||
|
def init(db):
|
||||||
|
db.execute("CREATE TABLE IF NOT EXISTS instance_appearance (id INTEGER PRIMARY KEY CHECK(id=1), settings TEXT NOT NULL)")
|
||||||
|
db.execute("CREATE TABLE IF NOT EXISTS room_appearance (room_id INTEGER PRIMARY KEY REFERENCES managed_rooms(id) ON DELETE CASCADE, settings TEXT NOT NULL)")
|
||||||
|
db.execute("CREATE TABLE IF NOT EXISTS instance_media_policy (user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, policy TEXT NOT NULL)")
|
||||||
|
db.execute("CREATE TABLE IF NOT EXISTS room_templates (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL, policy TEXT NOT NULL)")
|
||||||
|
db.execute("CREATE TABLE IF NOT EXISTS room_template_policy (room_id INTEGER PRIMARY KEY REFERENCES managed_rooms(id) ON DELETE CASCADE, policy TEXT NOT NULL)")
|
||||||
|
|
||||||
|
def validate(data):
|
||||||
|
from library_index import get_media_sources
|
||||||
|
if not isinstance(data,dict) or not isinstance(data.get('types'),list) or not isinstance(data.get('libraries'),list):
|
||||||
|
raise AccountError(400,'Invalid media policy')
|
||||||
|
types=data['types']; libraries=data['libraries']
|
||||||
|
if any(not isinstance(x,str) or x not in MEDIA_KEYS for x in types) or any(type(x) is not int for x in libraries):
|
||||||
|
raise AccountError(400,'Invalid media type or library')
|
||||||
|
if not set(libraries)<= {s['id'] for s in get_media_sources()}:
|
||||||
|
raise AccountError(400,'Unknown library')
|
||||||
|
return {'types':sorted(set(types)), 'libraries':sorted(set(libraries))}
|
||||||
|
|
||||||
|
def policies(uid):
|
||||||
|
from room_access_scope import current
|
||||||
|
rid=current(uid)
|
||||||
|
with open_database() as db:
|
||||||
|
init(db)
|
||||||
|
user=db.execute('SELECT is_platform_admin FROM users WHERE id=?',(uid,)).fetchone()
|
||||||
|
if user and user['is_platform_admin']: return []
|
||||||
|
rows=db.execute('SELECT policy FROM instance_media_policy WHERE user_id=?',(uid,)).fetchall()
|
||||||
|
rows+=db.execute('SELECT p.policy FROM room_template_policy p JOIN room_memberships m ON m.room_id=p.room_id JOIN managed_rooms r ON r.id=m.room_id WHERE m.user_id=? AND r.enabled=1 AND (? IS NULL OR r.id=?)',(uid,rid,rid)).fetchall()
|
||||||
|
return [json.loads(r['policy']) for r in rows]
|
||||||
|
|
||||||
|
def source_allowed(uid,source, rules=None):
|
||||||
|
if not source: return False
|
||||||
|
rules=policies(uid) if rules is None else rules
|
||||||
|
key='tv' if source['library_type']=='shows' else 'movies'
|
||||||
|
return all(source['id'] in r['libraries'] and key in r['types'] for r in rules)
|
||||||
|
|
||||||
|
def enforce_source(uid,source):
|
||||||
|
from media_accounts import enforce_media_library
|
||||||
|
if not source or not source_allowed(uid,source): raise AccountError(403,'Library access denied')
|
||||||
|
enforce_media_library(uid,'tv' if source['library_type']=='shows' else 'movies')
|
||||||
|
|
||||||
|
def snapshot(token):
|
||||||
|
from library_index import get_media_sources
|
||||||
|
require_admin(token)
|
||||||
|
with open_database() as db:
|
||||||
|
init(db)
|
||||||
|
return {'users':[dict(r) for r in db.execute('SELECT id,username,is_platform_admin FROM users ORDER BY username')], 'sources':[{k:s[k] for k in ('id','name','library_type')} for s in get_media_sources()], 'policies':{str(r['user_id']):json.loads(r['policy']) for r in db.execute('SELECT * FROM instance_media_policy')}, 'rooms':[dict(r) for r in db.execute('SELECT id,room_name,display_name FROM managed_rooms ORDER BY display_name')], 'room_policies':{str(r['room_id']):json.loads(r['policy']) for r in db.execute('SELECT * FROM room_template_policy')}, 'templates':[{'id':r['id'],'name':r['name'],'policy':json.loads(r['policy'])} for r in db.execute('SELECT * FROM room_templates ORDER BY name')]}
|
||||||
|
|
||||||
|
def save_user(token,data):
|
||||||
|
require_admin(token)
|
||||||
|
uid=data.get('user_id')
|
||||||
|
if type(uid) is not int: raise AccountError(400,'Invalid user')
|
||||||
|
with open_database() as db:
|
||||||
|
init(db)
|
||||||
|
u=db.execute('SELECT is_platform_admin FROM users WHERE id=?',(uid,)).fetchone()
|
||||||
|
if not u or u['is_platform_admin']: raise AccountError(400,'Select a non-platform-admin account')
|
||||||
|
if data.get('inherit') is True: db.execute('DELETE FROM instance_media_policy WHERE user_id=?',(uid,))
|
||||||
|
else: db.execute('INSERT INTO instance_media_policy VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET policy=excluded.policy',(uid,json.dumps(validate(data))))
|
||||||
|
return {'ok':True}
|
||||||
|
|
||||||
|
def save_template(token,data):
|
||||||
|
require_admin(token)
|
||||||
|
name=str(data.get('name') or '').strip()
|
||||||
|
if not name or len(name)>100: raise AccountError(400,'Enter a template name')
|
||||||
|
policy=validate(data)
|
||||||
|
actions=('media_access','user_permissions','room_permissions','password_resets','account_approvals')
|
||||||
|
roles=data.get('roles',{})
|
||||||
|
if not isinstance(roles,dict) or any(r not in ('member','moderator','admin','owner') or not isinstance(v,list) or any(a not in actions for a in v) for r,v in roles.items()):
|
||||||
|
raise AccountError(400,'Invalid role policy')
|
||||||
|
from history_scopes import validate as validate_history
|
||||||
|
policy['history']=validate_history(data.get('history',{}))
|
||||||
|
policy['roles']=roles
|
||||||
|
policy['ai_chat']=data.get('ai_chat') is True
|
||||||
|
policy['ai_tools']=policy['ai_chat'] and data.get('ai_tools') is True
|
||||||
|
with open_database() as db:
|
||||||
|
init(db)
|
||||||
|
db.execute('INSERT INTO room_templates(name,policy) VALUES(?,?) ON CONFLICT(name) DO UPDATE SET policy=excluded.policy',(name,json.dumps(policy)))
|
||||||
|
return {'ok':True}
|
||||||
|
|
||||||
|
def copy_template(db,room_id,template_id):
|
||||||
|
if template_id in (None,''): return
|
||||||
|
init(db)
|
||||||
|
row=db.execute('SELECT policy FROM room_templates WHERE id=?',(template_id,)).fetchone()
|
||||||
|
if not row: raise AccountError(400,'Unknown room template')
|
||||||
|
db.execute('INSERT INTO room_template_policy VALUES(?,?)',(room_id,row['policy']))
|
||||||
|
history=json.loads(row['policy']).get('history')
|
||||||
|
if history is not None:
|
||||||
|
from history_scopes import put
|
||||||
|
put(db,room_id,history)
|
||||||
|
|
||||||
|
|
||||||
|
def enforce_external_owner(uid,media):
|
||||||
|
from room_access_scope import current
|
||||||
|
rid=current(uid)
|
||||||
|
from library_index import get_media_source
|
||||||
|
import time
|
||||||
|
with open_database() as db:
|
||||||
|
user=db.execute('SELECT status,is_platform_admin FROM users WHERE id=?',(uid,)).fetchone()
|
||||||
|
if not user or user['status']!='active': raise AccountError(403,'External link owner inactive')
|
||||||
|
if not user['is_platform_admin'] and not db.execute("SELECT 1 FROM groups g JOIN group_memberships m ON m.group_id=g.id WHERE m.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=?))",(uid,int(time.time()),rid,rid)).fetchone():
|
||||||
|
raise AccountError(403,'External link owner lacks media access')
|
||||||
|
enforce_source(uid,get_media_source(media.get('source_id')))
|
||||||
|
|
||||||
|
|
||||||
|
def apply_template(token,data):
|
||||||
|
require_admin(token)
|
||||||
|
rid=data.get('room_id')
|
||||||
|
if type(rid) is not int: raise AccountError(400,'Invalid room')
|
||||||
|
with open_database() as db:
|
||||||
|
init(db)
|
||||||
|
db.execute('BEGIN IMMEDIATE')
|
||||||
|
if not db.execute('SELECT 1 FROM managed_rooms WHERE id=?',(rid,)).fetchone(): raise AccountError(404,'Room not found')
|
||||||
|
db.execute('DELETE FROM room_template_policy WHERE room_id=?',(rid,))
|
||||||
|
copy_template(db,rid,data.get('template_id'))
|
||||||
|
return {'ok':True}
|
||||||
|
|
||||||
|
DEFAULT_BRAND={'name':'','login_title':'Welcome','login_subtitle':'Sign in to your private hangout','powered_by':False,'allow_owner_rename':True}
|
||||||
|
def appearance(room_id=None):
|
||||||
|
with open_database() as db:
|
||||||
|
init(db)
|
||||||
|
row=db.execute('SELECT settings FROM instance_appearance WHERE id=1').fetchone()
|
||||||
|
result={**DEFAULT_BRAND,**(json.loads(row['settings']) if row else {})}
|
||||||
|
if room_id is not None:
|
||||||
|
room=db.execute('SELECT settings FROM room_appearance WHERE room_id=?',(room_id,)).fetchone()
|
||||||
|
result['room']=json.loads(room['settings']) if room else {}
|
||||||
|
return result
|
||||||
|
|
||||||
|
def save_appearance(token,data):
|
||||||
|
require_admin(token)
|
||||||
|
result={}
|
||||||
|
for key in ('name','login_title','login_subtitle'):
|
||||||
|
value=data.get(key,DEFAULT_BRAND[key])
|
||||||
|
if not isinstance(value,str) or len(value)>120 or any(ord(c)<32 for c in value): raise AccountError(400,'Invalid branding text')
|
||||||
|
result[key]=value.strip()
|
||||||
|
result.update(powered_by=data.get('powered_by') is True,allow_owner_rename=data.get('allow_owner_rename') is True)
|
||||||
|
with open_database() as db:
|
||||||
|
init(db)
|
||||||
|
db.execute('INSERT INTO instance_appearance VALUES(1,?) ON CONFLICT(id) DO UPDATE SET settings=excluded.settings',(json.dumps(result),))
|
||||||
|
return {'ok':True}
|
||||||
|
|
||||||
|
def save_room_appearance(token,data):
|
||||||
|
require_admin(token)
|
||||||
|
rid=data.get('room_id');accent=data.get('accent','');icon=data.get('icon','')
|
||||||
|
if type(rid) is not int or not isinstance(accent,str) or (accent and not re.fullmatch(r'#[0-9a-fA-F]{6}',accent)) or not isinstance(icon,str) or len(icon)>12 or any(ord(c)<32 for c in icon): raise AccountError(400,'Invalid room appearance')
|
||||||
|
with open_database() as db:
|
||||||
|
init(db)
|
||||||
|
if not db.execute('SELECT 1 FROM managed_rooms WHERE id=?',(rid,)).fetchone(): raise AccountError(404,'Room not found')
|
||||||
|
db.execute('INSERT INTO room_appearance VALUES(?,?) ON CONFLICT(room_id) DO UPDATE SET settings=excluded.settings',(rid,json.dumps({'accent':accent,'icon':icon})))
|
||||||
|
return {'ok':True}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
"""Room-aware history. Scope is derived on the server, never supplied as a storage key."""
|
||||||
|
import json
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from media_accounts import open_database, require_admin, assigned_rooms, session_user, AccountError
|
||||||
|
from datetime import datetime
|
||||||
|
import library_index as li
|
||||||
|
|
||||||
|
KINDS=('tube','movies','tv')
|
||||||
|
MODES=('shared','group','room','user','off')
|
||||||
|
DEFAULT={k:'shared' for k in KINDS}
|
||||||
|
|
||||||
|
def validate(data):
|
||||||
|
if not isinstance(data,dict) or any(k not in KINDS or v not in MODES for k,v in data.items()):
|
||||||
|
raise AccountError(400,'Invalid history settings')
|
||||||
|
return {**DEFAULT,**data}
|
||||||
|
|
||||||
|
def init(db):
|
||||||
|
db.execute('CREATE TABLE IF NOT EXISTS room_history_settings (room_id INTEGER PRIMARY KEY REFERENCES managed_rooms(id) ON DELETE CASCADE, settings TEXT NOT NULL)')
|
||||||
|
|
||||||
|
def settings(db,rid):
|
||||||
|
init(db)
|
||||||
|
row=db.execute('SELECT settings FROM room_history_settings WHERE room_id=?',(rid,)).fetchone()
|
||||||
|
return {**DEFAULT,**(json.loads(row[0]) if row else {})}
|
||||||
|
|
||||||
|
def put(db,rid,data):
|
||||||
|
init(db)
|
||||||
|
db.execute('INSERT INTO room_history_settings VALUES(?,?) ON CONFLICT(room_id) DO UPDATE SET settings=excluded.settings',(rid,json.dumps(validate(data))))
|
||||||
|
|
||||||
|
def admin_get(token,rid):
|
||||||
|
require_admin(token)
|
||||||
|
with open_database() as db:
|
||||||
|
if not db.execute('SELECT 1 FROM managed_rooms WHERE id=?',(rid,)).fetchone(): raise AccountError(404,'Room not found')
|
||||||
|
return settings(db,rid)
|
||||||
|
|
||||||
|
def admin_save(token,data):
|
||||||
|
require_admin(token)
|
||||||
|
rid=data.get('room_id')
|
||||||
|
if type(rid) is not int: raise AccountError(400,'Invalid room')
|
||||||
|
with open_database() as db:
|
||||||
|
if not db.execute('SELECT 1 FROM managed_rooms WHERE id=?',(rid,)).fetchone(): raise AccountError(404,'Room not found')
|
||||||
|
put(db,rid,data.get('history'))
|
||||||
|
return {'ok':True}
|
||||||
|
|
||||||
|
def resolve(token,room_header,kind):
|
||||||
|
user=session_user(token)
|
||||||
|
if not room_header or not str(room_header).isdigit(): raise AccountError(400,'Select a room and refresh the page to use media history')
|
||||||
|
rid=int(room_header)
|
||||||
|
if rid not in {r['id'] for r in assigned_rooms(token)}: raise AccountError(403,'Room history access denied')
|
||||||
|
with open_database() as db:
|
||||||
|
mode=settings(db,rid)[kind]
|
||||||
|
if mode=='shared': return 'shared'
|
||||||
|
if mode=='off': return None
|
||||||
|
if mode=='room': return f'room:{rid}'
|
||||||
|
if mode=='user': return f'user:{user["id"]}'
|
||||||
|
group=db.execute('SELECT group_id FROM managed_rooms WHERE id=?',(rid,)).fetchone()
|
||||||
|
if not group: raise AccountError(403,'Room history unavailable')
|
||||||
|
return f'group:{group[0]}'
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def connect():
|
||||||
|
db=li.get_db()
|
||||||
|
db.execute('CREATE TABLE IF NOT EXISTS scoped_progress (scope TEXT NOT NULL, kind TEXT NOT NULL, item TEXT NOT NULL, position_seconds REAL NOT NULL, duration_seconds REAL, completed INTEGER NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY(scope,kind,item))')
|
||||||
|
db.execute('CREATE TABLE IF NOT EXISTS scoped_tube_history (scope TEXT NOT NULL, video_id TEXT NOT NULL, title TEXT NOT NULL, channel_name TEXT, thumbnail_url TEXT, duration_seconds REAL, first_played_at TEXT NOT NULL, last_played_at TEXT NOT NULL, watch_count INTEGER NOT NULL, PRIMARY KEY(scope,video_id))')
|
||||||
|
try:
|
||||||
|
with db:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
def get_progress(scope,kind,item):
|
||||||
|
if scope=='shared': return li.get_youtube_playback_progress(item) if kind=='tube' else li.get_playback_progress(item)
|
||||||
|
result={'position_seconds':0.0,'duration_seconds':None,'completed':False,'updated_at':None}
|
||||||
|
if scope is None: return result
|
||||||
|
with connect() as db:
|
||||||
|
row=db.execute('SELECT position_seconds,duration_seconds,completed,updated_at FROM scoped_progress WHERE scope=? AND kind=? AND item=?',(scope,kind,str(item))).fetchone()
|
||||||
|
if row: result.update(dict(row));result['completed']=bool(result['completed'])
|
||||||
|
return result
|
||||||
|
|
||||||
|
def save_progress(scope,kind,item,position,duration=None,completed=False):
|
||||||
|
if scope is None: return
|
||||||
|
if scope=='shared':
|
||||||
|
return (li.save_youtube_playback_progress if kind=='tube' else li.save_playback_progress)(item,position,duration,completed)
|
||||||
|
position=max(0.,float(position or 0));duration=max(0.,float(duration)) if duration not in (None,'') else None
|
||||||
|
with connect() as db:
|
||||||
|
db.execute('''INSERT INTO scoped_progress VALUES(?,?,?,?,?,?,?) ON CONFLICT(scope,kind,item) DO UPDATE SET position_seconds=excluded.position_seconds,duration_seconds=COALESCE(excluded.duration_seconds,scoped_progress.duration_seconds),completed=excluded.completed,updated_at=excluded.updated_at''',(scope,kind,str(item),position,duration,int(bool(completed)),datetime.now().isoformat()))
|
||||||
|
|
||||||
|
def reset_progress(scope,kind,item):
|
||||||
|
if scope is None: return
|
||||||
|
if scope=='shared': return (li.reset_youtube_playback_progress if kind=='tube' else li.reset_playback_progress)(item)
|
||||||
|
with connect() as db: db.execute('DELETE FROM scoped_progress WHERE scope=? AND kind=? AND item=?',(scope,kind,str(item)))
|
||||||
|
|
||||||
|
def record_watch(scope,video_id,title,channel_name=None,thumbnail_url=None,duration_seconds=None):
|
||||||
|
if scope is None: return
|
||||||
|
if scope=='shared': return li.record_youtube_watch(video_id,title,channel_name,thumbnail_url,duration_seconds)
|
||||||
|
try: duration=float(duration_seconds) if duration_seconds not in (None,'') else None
|
||||||
|
except (ValueError,TypeError): duration=None
|
||||||
|
now=datetime.now().isoformat()
|
||||||
|
with connect() as db:
|
||||||
|
db.execute('''INSERT INTO scoped_tube_history VALUES(?,?,?,?,?,?,?,?,1) ON CONFLICT(scope,video_id) DO UPDATE SET title=excluded.title,channel_name=COALESCE(excluded.channel_name,scoped_tube_history.channel_name),thumbnail_url=COALESCE(excluded.thumbnail_url,scoped_tube_history.thumbnail_url),duration_seconds=COALESCE(excluded.duration_seconds,scoped_tube_history.duration_seconds),last_played_at=excluded.last_played_at,watch_count=scoped_tube_history.watch_count+1''',(scope,video_id,title or video_id,channel_name,thumbnail_url,duration,now,now))
|
||||||
|
|
||||||
|
def history(scope,limit=50):
|
||||||
|
if scope is None: return []
|
||||||
|
if scope=='shared': return li.get_youtube_history(limit)
|
||||||
|
with connect() as db:
|
||||||
|
rows=db.execute('''SELECT h.video_id,h.title,h.channel_name,h.thumbnail_url,COALESCE(p.duration_seconds,h.duration_seconds) duration_seconds,h.first_played_at,h.last_played_at,h.watch_count,COALESCE(p.position_seconds,0) position_seconds,COALESCE(p.completed,0) completed,c.video_id IS NOT NULL cached,c.size_bytes cache_size_bytes FROM scoped_tube_history h LEFT JOIN scoped_progress p ON p.scope=h.scope AND p.kind='tube' AND p.item=h.video_id LEFT JOIN youtube_video_cache c ON c.video_id=h.video_id WHERE h.scope=? ORDER BY h.last_played_at DESC LIMIT ?''',(scope,max(1,min(int(limit),500)))).fetchall()
|
||||||
|
return [{**dict(r),'completed':bool(r['completed']),'cached':bool(r['cached'])} for r in rows]
|
||||||
@@ -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()}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""Request-local, verified room identity; never use a global last-room cookie."""
|
||||||
|
from contextvars import ContextVar
|
||||||
|
from functools import wraps
|
||||||
|
from urllib.parse import urlsplit, parse_qs
|
||||||
|
|
||||||
|
_current = ContextVar('kronic_room_access', default=None)
|
||||||
|
|
||||||
|
def current(uid):
|
||||||
|
scope = _current.get()
|
||||||
|
return scope[1] if scope and scope[0] == int(uid) else None
|
||||||
|
|
||||||
|
def clear():
|
||||||
|
return _current.set(None)
|
||||||
|
|
||||||
|
def restore(token):
|
||||||
|
_current.reset(token)
|
||||||
|
|
||||||
|
def bind(uid, room_id):
|
||||||
|
from media_accounts import open_database, AccountError
|
||||||
|
with open_database() as db:
|
||||||
|
row = db.execute('''SELECT r.id FROM managed_rooms r JOIN groups g ON g.id=r.group_id
|
||||||
|
JOIN room_memberships m ON m.room_id=r.id
|
||||||
|
WHERE r.id=? AND m.user_id=? AND r.enabled=1 AND g.status='active' ''', (room_id,uid)).fetchone()
|
||||||
|
if not row: raise AccountError(403,'Selected room is not assigned to this account')
|
||||||
|
_current.set((int(uid),int(row['id'])))
|
||||||
|
return int(row['id'])
|
||||||
|
|
||||||
|
def bind_request(handler):
|
||||||
|
from media_accounts import session_user, assigned_rooms, AccountError
|
||||||
|
# A handler can call the same authorization guard more than once.
|
||||||
|
# The enclosing HTTP-method decorator resets this context for every request.
|
||||||
|
if _current.get() is not None: return _current.get()[1]
|
||||||
|
token=handler.get_session_token(); user=session_user(token); uid=int(user['id'])
|
||||||
|
rooms=assigned_rooms(token)
|
||||||
|
raw=handler.headers.get('X-Kronic-Room')
|
||||||
|
url_room=parse_qs(urlsplit(handler.path).query,keep_blank_values=True).get('kronic_room',[])
|
||||||
|
if len(url_room)>1 or (url_room and raw is not None and raw!=url_room[0]): raise AccountError(400,'Conflicting room selectors')
|
||||||
|
if url_room: raw=url_room[0]
|
||||||
|
ref=urlsplit(handler.headers.get('Referer',''))
|
||||||
|
name=None
|
||||||
|
if ref.path in ('/','/app','/m','/m/','/desktop','/desktop/') and ref.netloc.lower()==(handler.headers.get('Host') or '').lower():
|
||||||
|
name=parse_qs(ref.query).get('room',[None])[0]
|
||||||
|
if raw is not None:
|
||||||
|
if not raw.isascii() or not raw.isdigit() or len(raw)>19 or not 0<int(raw)<=9223372036854775807: raise AccountError(400,'Invalid selected room')
|
||||||
|
rid=int(raw)
|
||||||
|
if name and not any(r['id']==rid and r['room_name']==name for r in rooms): raise AccountError(403,'Room context mismatch')
|
||||||
|
elif name:
|
||||||
|
rid=next((r['id'] for r in rooms if r['room_name']==name),None)
|
||||||
|
if rid is None: raise AccountError(403,'Selected room is not assigned to this account')
|
||||||
|
elif len(rooms)==1:
|
||||||
|
rid=rooms[0]['id']
|
||||||
|
else:
|
||||||
|
raise AccountError(403,'Select a room before accessing media')
|
||||||
|
return bind(uid,rid)
|
||||||
|
|
||||||
|
def isolated_request(fn):
|
||||||
|
@wraps(fn)
|
||||||
|
def wrapper(*args,**kwargs):
|
||||||
|
token=clear()
|
||||||
|
try: return fn(*args,**kwargs)
|
||||||
|
finally: restore(token)
|
||||||
|
return wrapper
|
||||||
+3040
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user