yt-dlf/scripts/add_user.py

42 lines
1.2 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""Add or update a user in the yt-dlf user database.
Usage: python3 scripts/add_user.py <username> <password> [users_file]
Default users_file: users.txt (relative to current directory)
"""
import sys
import os
import hashlib
from pathlib import Path
if len(sys.argv) < 3:
print(f'Usage: {sys.argv[0]} <username> <password> [users_file]', file=sys.stderr)
sys.exit(1)
username = sys.argv[1]
password = sys.argv[2].encode()
users_file = Path(sys.argv[3]) if len(sys.argv) >= 4 else Path('users.txt')
salt = os.urandom(16)
key = hashlib.scrypt(password, salt=salt, n=16384, r=8, p=1, dklen=32)
new_entry = f'{username}:{salt.hex()}:{key.hex()}\n'
lines = users_file.read_text().splitlines(keepends=True) if users_file.exists() else []
updated = False
for i, line in enumerate(lines):
parts = line.strip().split(':')
if parts and parts[0] == username:
lines[i] = new_entry
updated = True
break
if not updated:
if lines and not lines[-1].endswith('\n'):
lines.append('\n')
lines.append(new_entry)
users_file.write_text(''.join(lines))
print(f"{'Updated' if updated else 'Added'} user '{username}' in {users_file}")