|
|
| |
|
|
| import json |
| from pathlib import Path |
| from typing import Any, Dict, List, Optional |
|
|
|
|
| from .config import get_user_dir |
|
|
|
|
| def _get_users_json() -> Path: |
| """ |
| Returns: Path to the main users.json file. |
| """ |
| root = Path(__file__).resolve().parents[2] |
| auth_dir = root / "data" / "auth" |
| auth_dir.mkdir(parents=True, exist_ok=True) |
| users_file = auth_dir / "users.json" |
|
|
| if not users_file.exists(): |
| users_file.write_text("{}", encoding="utf-8") |
|
|
| return users_file |
|
|
|
|
| def _load_users() -> Dict[str, Dict]: |
| users_file = _get_users_json() |
| try: |
| return json.loads(users_file.read_text(encoding="utf-8")) |
| except Exception: |
| return {} |
|
|
|
|
| def _save_users(data: Dict[str, Dict]) -> None: |
| users_file = _get_users_json() |
| users_file.write_text(json.dumps(data, indent=2), encoding="utf-8") |
|
|
|
|
| |
| |
| |
|
|
| def register_user(username: str, password: str) -> bool: |
| if not username or not password: |
| return False |
|
|
| users = _load_users() |
| if username in users: |
| return False |
|
|
| users[username] = { |
| "password": password, |
| "prefs": { |
| "target_language": "english", |
| "native_language": "english", |
| "cefr_level": "B1", |
| "topic": "general conversation", |
| }, |
| } |
| _save_users(users) |
|
|
| |
| get_user_dir(username) |
|
|
| return True |
|
|
|
|
| def authenticate_user(username: str, password: str) -> bool: |
| users = _load_users() |
| entry = users.get(username) |
| if not entry: |
| return False |
| return entry.get("password") == password |
|
|
|
|
| def get_user_prefs(username: str) -> Dict: |
| users = _load_users() |
| entry = users.get(username, {}) |
| return entry.get("prefs", {}) |
|
|
|
|
| def update_user_prefs(username: str, prefs: Dict) -> None: |
| users = _load_users() |
| if username not in users: |
| return |
| users[username]["prefs"] = prefs |
| _save_users(users) |
|
|
|
|