File size: 8,932 Bytes
5f20dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afd7fcd
5f20dc6
 
 
 
 
 
 
 
 
 
 
d7a4fa1
 
 
 
 
 
 
 
951488d
d7a4fa1
 
 
 
 
 
 
 
 
 
 
 
 
951488d
 
d7a4fa1
 
 
 
951488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f20dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7a4fa1
 
5f20dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
"""
Auth module — pbkdf2 password hashing, manually-provisioned users,
session-based login, per-user recovery codes.

Storage: reads USERS_JSON env var first (Cloud Run), falls back to users.json (local).
"""
import os
import json
import time
import hmac
import base64
import hashlib
import secrets
from functools import wraps
from flask import session, jsonify, redirect, url_for, request

# ---------- Hashing (pbkdf2, stdlib) ----------
PBKDF2_ITERATIONS = 200_000

def hash_password(password, salt=None):
    """Hash a password with pbkdf2_hmac + random salt. Returns base64 string."""
    salt = salt or os.urandom(16)
    dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, PBKDF2_ITERATIONS)
    return base64.b64encode(salt + dk).decode("ascii")

def check_password(password, stored):
    """Verify password against stored pbkdf2 hash."""
    try:
        raw = base64.b64decode(stored.encode("ascii"))
        salt, expected = raw[:16], raw[16:]
        dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, PBKDF2_ITERATIONS)
        return hmac.compare_digest(dk, expected)
    except Exception:
        return False

# ---------- Storage ----------
_DATA_DIR = os.environ.get("DATA_DIR", ".")
LOCAL_USERS_FILE = os.environ.get("USERS_FILE", "users.json")
from modules.storage import load_json, save_json

def _load_users_raw():
    data = load_json(LOCAL_USERS_FILE, default=None)
    if data is None:
        return []
    return data.get("users", [])

def _save_users_raw(users):
    return save_json(LOCAL_USERS_FILE, {"users": users})

def get_user_alerts(email):
    """Return user's alert preferences with defaults for missing fields."""
    u = get_user(email)
    if not u:
        return None
    return {
        "alert_btc_1pct": bool(u.get("alert_btc_1pct", True)),
        "alert_eth_1pct": bool(u.get("alert_eth_1pct", True)),
        "high_score_alerts": bool(u.get("high_score_alerts", True)),
    }


def update_user_alerts(email, prefs):
    """Update alert preferences for a user. Returns True on success."""
    email = (email or "").strip().lower()
    users = _load_users_raw()
    for u in users:
        if u.get("email", "").lower() == email:
            if "alert_btc_1pct" in prefs:
                u["alert_btc_1pct"] = bool(prefs["alert_btc_1pct"])
            if "alert_eth_1pct" in prefs:
                u["alert_eth_1pct"] = bool(prefs["alert_eth_1pct"])
            if "high_score_alerts" in prefs:
                u["high_score_alerts"] = bool(prefs["high_score_alerts"])
            return _save_users_raw(users)
    return False




def get_dismissed_alerts(email):
    u = get_user(email)
    if not u:
        return {}
    d = u.get("dismissed_alerts") or {}
    return d if isinstance(d, dict) else {}


def add_dismissed_alert(email, symbol):
    import time as _t
    email = (email or "").strip().lower()
    symbol = (symbol or "").strip().upper()
    if not email or not symbol:
        return False
    users = _load_users_raw()
    for u in users:
        if u.get("email", "").lower() == email:
            d = u.get("dismissed_alerts") or {}
            if not isinstance(d, dict):
                d = {}
            d[symbol] = int(_t.time())
            u["dismissed_alerts"] = d
            return _save_users_raw(users)
    return False

# ---------- Lookups ----------
def get_user(email):
    email = (email or "").strip().lower()
    for u in _load_users_raw():
        if u.get("email", "").lower() == email:
            return u
    return None

def verify_login(email, password):
    """Returns (user, error_code). error_code is None on success."""
    user = get_user(email)
    if not user:
        return None, "invalid"
    if not check_password(password or "", user.get("password_hash", "")):
        return None, "invalid"
    status = user.get("status", "active")
    if status == "pending":
        return None, "pending"
    if status == "rejected":
        return None, "rejected"
    if status != "active":
        return None, "invalid"
    return user, None

def verify_recovery(email, code):
    user = get_user(email)
    if not user:
        return None
    stored = user.get("recovery_code", "")
    if not stored:
        return None
    if not hmac.compare_digest(str(stored), str(code or "")):
        return None
    return user

def update_password(email, new_password):
    email = (email or "").strip().lower()
    users = _load_users_raw()
    for u in users:
        if u.get("email", "").lower() == email:
            u["password_hash"] = hash_password(new_password)
            u["password_updated_at"] = int(time.time())
            return _save_users_raw(users)
    return False

# ---------- User management (Phase 11) ----------
def create_user(email, password, first_name="", last_name="", role="user", status="pending", reg_message=""):
    """Create a new user. Returns the user dict, or None if email exists."""
    email = (email or "").strip().lower()
    if not email:
        return None
    if get_user(email):
        return None
    users = _load_users_raw()
    recovery = secrets.token_hex(16)
    user = {
        "email": email,
        "password_hash": hash_password(password),
        "recovery_code": recovery,
        "role": role,
        "status": status,
        "alert_btc_1pct": True,
        "alert_eth_1pct": True,
        "first_name": first_name,
        "last_name": last_name,
        "reg_message": (reg_message or "").strip()[:80],
        "created_at": int(time.time()),
        "approved_at": int(time.time()) if status == "active" else None,
        "approved_by": None,
        "approved_note": None,
        "rejected_note": None,
    }
    users.append(user)
    _save_users_raw(users)
    return user


def update_user_status(email, status, by_email=None, note=""):
    """Set status for a user. Statuses: pending / active / rejected. Stores admin note."""
    email = (email or "").strip().lower()
    note = (note or "").strip()[:80]
    users = _load_users_raw()
    for u in users:
        if u.get("email", "").lower() == email:
            u["status"] = status
            u["reviewed_at"] = int(time.time())
            u["reviewed_by"] = by_email
            if status == "active":
                u["approved_at"] = int(time.time())
                u["approved_by"] = by_email
                u["approved_note"] = note or None
            elif status == "rejected":
                u["rejected_note"] = note or None
            _save_users_raw(users)
            return True
    return False


def list_all_users():
    """Return all users, sorted: pending first, then active, then rejected."""
    users = _load_users_raw()
    order = {"pending": 0, "active": 1, "rejected": 2}
    users = list(users)
    users.sort(key=lambda u: (order.get(u.get("status", "active"), 99),
                              -u.get("created_at", 0)))
    return users


def delete_user(email):
    """Remove a user by email. Returns True if removed."""
    email = (email or "").strip().lower()
    users = _load_users_raw()
    before = len(users)
    users = [u for u in users if u.get("email", "").lower() != email]
    if len(users) < before:
        _save_users_raw(users)
        return True
    return False


# ---------- Session ----------
SESSION_TTL = 60 * 60 * 12  # 12 hours

def login_user(user):
    session.permanent = True
    session["user_email"] = user["email"]
    session["user_role"] = user.get("role", "user")
    session["login_at"] = int(time.time())

def logout_user():
    session.clear()

def current_user():
    email = session.get("user_email")
    login_at = session.get("login_at", 0)
    if not email:
        return None
    if time.time() - login_at > SESSION_TTL:
        session.clear()
        return None
    return get_user(email)

def is_admin():
    u = current_user()
    return bool(u and u.get("role") == "admin")

def public_mode():
    """True if PUBLIC_MODE env var is 'true', OR no one is logged in."""
    if os.environ.get("PUBLIC_MODE", "false").lower() == "true":
        return True
    return current_user() is None

# ---------- Decorators ----------
def require_login(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        if not current_user():
            if request.path.startswith("/api/"):
                return jsonify({"error": "login required"}), 401
            return redirect(url_for("login_page", next=request.path))
        return f(*args, **kwargs)
    return wrapper

def require_admin(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        if not current_user():
            if request.path.startswith("/api/"):
                return jsonify({"error": "login required"}), 401
            return redirect(url_for("login_page", next=request.path))
        if not is_admin():
            return jsonify({"error": "admin only"}), 403
        return f(*args, **kwargs)
    return wrapper