File size: 2,087 Bytes
e82864c
 
 
 
 
 
 
 
45e6864
e82864c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

# src/app/auth.py

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")


# ------------------------------------------------------------
# AUTH FUNCTIONS
# ------------------------------------------------------------

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)

    # create the user folder
    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)