fraudTech commited on
Commit
e00400b
·
1 Parent(s): 6614244

multi user auth

Browse files
Files changed (2) hide show
  1. README.md +45 -0
  2. app.py +126 -1
README.md CHANGED
@@ -8,3 +8,48 @@ pinned: false
8
  ---
9
 
10
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  ---
9
 
10
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
11
+
12
+ ## Authentication
13
+
14
+ The gateway uses JWT for authenticated access to proxy endpoints.
15
+
16
+ ### Multi-user login
17
+
18
+ Configure one or more users via environment variables:
19
+
20
+ - `APP_USERS_JSON`: JSON object mapping `username -> plaintext_password` (recommended for demos; store as secrets)
21
+ - `APP_USERS_HASHED_JSON`: JSON object mapping `username -> werkzeug_password_hash` (recommended for production)
22
+ - `APP_USER` / `APP_PASSWORD`: legacy single-user plaintext credentials (still supported)
23
+ - `TEST_USER_PASSWORD`: if set, enables a `test_user` account with this password
24
+
25
+ Examples:
26
+
27
+ - `APP_USERS_JSON={"alice":"pw1","bob":"pw2","test_user":"pw3"}`
28
+ - `TEST_USER_PASSWORD=changeme` (creates user `test_user`)
29
+
30
+ Notes:
31
+
32
+ - Do not hardcode passwords in the repo. Use Hugging Face Space secrets or your deployment secret store.
33
+ - The JWT identity is set to the username.
34
+
35
+ ### Admin-only user registration
36
+
37
+ The gateway can create users at runtime via `POST /register`.
38
+
39
+ - Requires a valid JWT (`Authorization: Bearer ...`).
40
+ - Only allowed if the JWT identity (username) is in `ADMIN_USERS`.
41
+
42
+ Env vars:
43
+
44
+ - `ADMIN_USERS`: comma-separated usernames who can call `/register` (e.g. `ADMIN_USERS=alice,bob`)
45
+ - If `ADMIN_USERS` is not set but `APP_USER` is set, `APP_USER` is treated as the admin for convenience.
46
+
47
+ Request body:
48
+
49
+ ```json
50
+ { "username": "new_user", "password": "pw", "overwrite": false }
51
+ ```
52
+
53
+ Notes:
54
+
55
+ - Users created via `/register` are stored in-memory (no persistence across restarts).
app.py CHANGED
@@ -1,11 +1,15 @@
1
  # app.py in GATEWAY Space
2
 
3
  import os
 
 
4
  from flask import Flask, request, jsonify, Response, stream_with_context
5
  from flask_cors import CORS
6
  import requests
7
  from datetime import timedelta
8
 
 
 
9
  from flask_jwt_extended import (
10
  JWTManager,
11
  create_access_token,
@@ -27,6 +31,83 @@ HF_TOKEN = os.environ.get("HF_TOKEN")
27
  # Very simple “user DB” via env vars
28
  APP_USER = os.environ.get("APP_USER")
29
  APP_PASSWORD = os.environ.get("APP_PASSWORD")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
 
32
  # ============================================================
@@ -41,13 +122,57 @@ def login():
41
  if not username or not password:
42
  return jsonify({"ok": False, "error": "Missing credentials"}), 400
43
 
44
- if username != APP_USER or password != APP_PASSWORD:
 
 
 
 
 
 
 
45
  return jsonify({"ok": False, "error": "Invalid credentials"}), 401
46
 
47
  access_token = create_access_token(identity=username)
48
  return jsonify({"ok": True, "token": access_token}), 200
49
 
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  # ============================================================
52
  # NON-STREAMING CHAT (JSON → JSON)
53
  # ============================================================
 
1
  # app.py in GATEWAY Space
2
 
3
  import os
4
+ import json
5
+ from typing import Dict
6
  from flask import Flask, request, jsonify, Response, stream_with_context
7
  from flask_cors import CORS
8
  import requests
9
  from datetime import timedelta
10
 
11
+ from werkzeug.security import check_password_hash, generate_password_hash
12
+
13
  from flask_jwt_extended import (
14
  JWTManager,
15
  create_access_token,
 
31
  # Very simple “user DB” via env vars
32
  APP_USER = os.environ.get("APP_USER")
33
  APP_PASSWORD = os.environ.get("APP_PASSWORD")
34
+ ADMIN_USERS_ENV = os.environ.get("ADMIN_USERS")
35
+
36
+
37
+ def _parse_admin_users() -> set[str]:
38
+ admins: set[str] = set()
39
+ if ADMIN_USERS_ENV:
40
+ for part in ADMIN_USERS_ENV.split(","):
41
+ name = part.strip()
42
+ if name:
43
+ admins.add(name)
44
+
45
+ # Back-compat convenience: if a legacy single user is configured and no
46
+ # explicit admin list is provided, treat that user as the admin.
47
+ if not admins and APP_USER:
48
+ admins.add(str(APP_USER).strip())
49
+
50
+ return admins
51
+
52
+
53
+ def _load_users_from_env() -> Dict[str, str]:
54
+ """Build a username -> password_hash mapping.
55
+
56
+ Supported env vars:
57
+ - APP_USERS_JSON: JSON object mapping username -> plaintext password
58
+ - APP_USERS_HASHED_JSON: JSON object mapping username -> werkzeug password hash
59
+ - APP_USER/APP_PASSWORD: legacy single-user plaintext
60
+ - TEST_USER_PASSWORD: optional plaintext password for username 'test_user'
61
+ """
62
+
63
+ users: Dict[str, str] = {}
64
+
65
+ users_json = (os.environ.get("APP_USERS_JSON") or "").strip()
66
+ if users_json:
67
+ try:
68
+ parsed = json.loads(users_json)
69
+ if not isinstance(parsed, dict):
70
+ raise ValueError("APP_USERS_JSON must be a JSON object")
71
+ for username, password in parsed.items():
72
+ username = str(username).strip()
73
+ password = "" if password is None else str(password)
74
+ if username and password:
75
+ users[username] = generate_password_hash(password)
76
+ except Exception as e:
77
+ raise RuntimeError(f"Invalid APP_USERS_JSON: {e}")
78
+
79
+ users_hashed_json = (os.environ.get("APP_USERS_HASHED_JSON") or "").strip()
80
+ if users_hashed_json:
81
+ try:
82
+ parsed = json.loads(users_hashed_json)
83
+ if not isinstance(parsed, dict):
84
+ raise ValueError("APP_USERS_HASHED_JSON must be a JSON object")
85
+ for username, password_hash in parsed.items():
86
+ username = str(username).strip()
87
+ password_hash = "" if password_hash is None else str(password_hash).strip()
88
+ if username and password_hash:
89
+ users[username] = password_hash
90
+ except Exception as e:
91
+ raise RuntimeError(f"Invalid APP_USERS_HASHED_JSON: {e}")
92
+
93
+ if APP_USER and APP_PASSWORD:
94
+ users[str(APP_USER).strip()] = generate_password_hash(str(APP_PASSWORD))
95
+
96
+ test_user_password = (os.environ.get("TEST_USER_PASSWORD") or "").strip()
97
+ if test_user_password:
98
+ users["test_user"] = generate_password_hash(test_user_password)
99
+
100
+ return users
101
+
102
+
103
+ try:
104
+ USER_STORE = _load_users_from_env()
105
+ except Exception as e:
106
+ # Fail fast with a clear error in logs; health endpoint still starts.
107
+ USER_STORE = {}
108
+ print(f"[gateway] auth user store error: {e}")
109
+
110
+ ADMIN_USERS = _parse_admin_users()
111
 
112
 
113
  # ============================================================
 
122
  if not username or not password:
123
  return jsonify({"ok": False, "error": "Missing credentials"}), 400
124
 
125
+ if not USER_STORE:
126
+ return (
127
+ jsonify({"ok": False, "error": "Authentication is not configured"}),
128
+ 500,
129
+ )
130
+
131
+ password_hash = USER_STORE.get(username)
132
+ if not password_hash or not check_password_hash(password_hash, password):
133
  return jsonify({"ok": False, "error": "Invalid credentials"}), 401
134
 
135
  access_token = create_access_token(identity=username)
136
  return jsonify({"ok": True, "token": access_token}), 200
137
 
138
 
139
+ # ============================================================
140
+ # REGISTER ENDPOINT (ADMIN ONLY)
141
+ # ============================================================
142
+ @app.post("/register")
143
+ @jwt_required()
144
+ def register():
145
+ identity = (get_jwt_identity() or "").strip()
146
+ if not ADMIN_USERS or identity not in ADMIN_USERS:
147
+ return (
148
+ jsonify(
149
+ {
150
+ "ok": False,
151
+ "error": "Admin privileges required",
152
+ }
153
+ ),
154
+ 403,
155
+ )
156
+
157
+ try:
158
+ data = request.get_json(force=True) or {}
159
+ except Exception:
160
+ return jsonify({"ok": False, "error": "Invalid JSON"}), 400
161
+
162
+ username = (data.get("username") or "").strip()
163
+ password = (data.get("password") or "").strip()
164
+ overwrite = bool(data.get("overwrite", False))
165
+
166
+ if not username or not password:
167
+ return jsonify({"ok": False, "error": "Missing credentials"}), 400
168
+
169
+ if (not overwrite) and (username in USER_STORE):
170
+ return jsonify({"ok": False, "error": "User already exists"}), 409
171
+
172
+ USER_STORE[username] = generate_password_hash(password)
173
+ return jsonify({"ok": True, "username": username}), 200
174
+
175
+
176
  # ============================================================
177
  # NON-STREAMING CHAT (JSON → JSON)
178
  # ============================================================