"""Explicitly link ONE existing Media account to its matching Chat account. Usage: python link_existing_media_account.py USERNAME CHAT_USER_ID EMAIL Only do this after verifying the Chat account identity in the Chat admin UI. Back up kronick_accounts.sqlite3 first. Never use for admin accounts. """ import sys from media_accounts import open_database if len(sys.argv) != 4: raise SystemExit('Usage: python link_existing_media_account.py USERNAME CHAT_USER_ID EMAIL') username, chat_id, email = sys.argv[1:] chat_id = int(chat_id) if chat_id < 1: raise SystemExit('Invalid Chat user ID') with open_database() as db: row = db.execute('SELECT * FROM users WHERE username=?', (username,)).fetchone() if not row or row['email'].lower() != email.lower(): raise SystemExit('Media account username/email do not match supplied details') if row['is_platform_admin']: raise SystemExit('Refusing to link an existing Media administrator automatically') memberships = db.execute('SELECT role FROM group_memberships WHERE user_id=?', (row['id'],)).fetchall() if any(m['role'] != 'member' for m in memberships): raise SystemExit('Refusing to link an existing Media privileged group member') print(f"Link Media user {row['username']} ({row['email']}) to Chat ID {chat_id}?") if input('Type LINK to continue: ').strip() != 'LINK': raise SystemExit('Cancelled') db.execute('UPDATE users SET password_hash=? WHERE id=?', (f'!sso-managed:{chat_id}', row['id'])) db.execute('DELETE FROM user_sessions WHERE user_id=?', (row['id'],)) db.commit() print('Linked. This Media account now signs in through Chat only.')