darkfire514 commited on
Commit
ad47be8
·
verified ·
1 Parent(s): 42cfec1

Create api.py

Browse files
Files changed (1) hide show
  1. api.py +446 -0
api.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import os
3
+ import secrets
4
+ from datetime import datetime
5
+ from typing import List, Optional
6
+
7
+ import psycopg2
8
+ from fastapi import FastAPI, Header, HTTPException
9
+ from pydantic import BaseModel
10
+
11
+ app = FastAPI(
12
+ title="PostgreSQL General HF API",
13
+ description="A lightweight PostgreSQL API service for Hugging Face Docker Spaces.",
14
+ version="1.0.0",
15
+ )
16
+
17
+ POSTGRES_USER = os.environ.get("POSTGRES_USER", "admin")
18
+ POSTGRES_PASSWORD = os.environ.get("POSTGRES_PASSWORD")
19
+ POSTGRES_DB = os.environ.get("POSTGRES_DB", "appdb")
20
+
21
+ DATABASE_URL = os.environ.get(
22
+ "DATABASE_URL",
23
+ f"postgresql://{POSTGRES_USER}:{POSTGRES_PASSWORD}@127.0.0.1:5432/{POSTGRES_DB}",
24
+ )
25
+
26
+
27
+ def get_conn():
28
+ if not POSTGRES_PASSWORD and not os.environ.get("DATABASE_URL"):
29
+ raise HTTPException(status_code=500, detail="POSTGRES_PASSWORD or DATABASE_URL is not configured")
30
+ return psycopg2.connect(DATABASE_URL)
31
+
32
+
33
+ def hash_key(api_key: str) -> str:
34
+ return hashlib.sha256(api_key.encode("utf-8")).hexdigest()
35
+
36
+
37
+ def verify_admin(x_admin_user: Optional[str], x_admin_password: Optional[str]):
38
+ if x_admin_user != POSTGRES_USER or x_admin_password != POSTGRES_PASSWORD:
39
+ raise HTTPException(status_code=403, detail="Invalid admin credentials")
40
+
41
+
42
+ def init_tables():
43
+ conn = get_conn()
44
+ cur = conn.cursor()
45
+
46
+ cur.execute(
47
+ """
48
+ CREATE TABLE IF NOT EXISTS api_keys (
49
+ id SERIAL PRIMARY KEY,
50
+ name TEXT NOT NULL,
51
+ key_hash TEXT NOT NULL UNIQUE,
52
+ key_prefix TEXT NOT NULL,
53
+ scopes TEXT[] DEFAULT ARRAY['read', 'write'],
54
+ is_active BOOLEAN DEFAULT true,
55
+ created_at TIMESTAMP DEFAULT now(),
56
+ last_used_at TIMESTAMP
57
+ );
58
+ """
59
+ )
60
+
61
+ cur.execute(
62
+ """
63
+ CREATE TABLE IF NOT EXISTS files (
64
+ id SERIAL PRIMARY KEY,
65
+ user_id TEXT,
66
+ filename TEXT NOT NULL,
67
+ file_path TEXT NOT NULL,
68
+ file_size BIGINT,
69
+ mime_type TEXT,
70
+ created_at TIMESTAMP DEFAULT now()
71
+ );
72
+ """
73
+ )
74
+
75
+ cur.execute(
76
+ """
77
+ CREATE TABLE IF NOT EXISTS rss_articles (
78
+ id SERIAL PRIMARY KEY,
79
+ source TEXT,
80
+ title TEXT NOT NULL,
81
+ url TEXT UNIQUE,
82
+ summary TEXT,
83
+ published_at TIMESTAMP,
84
+ created_at TIMESTAMP DEFAULT now()
85
+ );
86
+ """
87
+ )
88
+
89
+ conn.commit()
90
+ cur.close()
91
+ conn.close()
92
+
93
+
94
+ @app.on_event("startup")
95
+ def startup():
96
+ init_tables()
97
+
98
+
99
+ def verify_api_key(authorization: Optional[str], required_scope: Optional[str] = None):
100
+ if not authorization:
101
+ raise HTTPException(status_code=401, detail="Missing Authorization header")
102
+
103
+ if not authorization.startswith("Bearer "):
104
+ raise HTTPException(status_code=401, detail="Invalid Authorization format")
105
+
106
+ api_key = authorization.replace("Bearer ", "", 1).strip()
107
+ key_hash = hash_key(api_key)
108
+
109
+ conn = get_conn()
110
+ cur = conn.cursor()
111
+
112
+ cur.execute(
113
+ """
114
+ SELECT id, name, scopes, is_active
115
+ FROM api_keys
116
+ WHERE key_hash = %s
117
+ LIMIT 1;
118
+ """,
119
+ (key_hash,),
120
+ )
121
+
122
+ row = cur.fetchone()
123
+
124
+ if not row:
125
+ cur.close()
126
+ conn.close()
127
+ raise HTTPException(status_code=403, detail="Invalid API key")
128
+
129
+ key_id, name, scopes, is_active = row
130
+
131
+ if not is_active:
132
+ cur.close()
133
+ conn.close()
134
+ raise HTTPException(status_code=403, detail="API key is inactive")
135
+
136
+ if required_scope and required_scope not in scopes:
137
+ cur.close()
138
+ conn.close()
139
+ raise HTTPException(status_code=403, detail="Insufficient API key scope")
140
+
141
+ cur.execute(
142
+ """
143
+ UPDATE api_keys
144
+ SET last_used_at = now()
145
+ WHERE id = %s;
146
+ """,
147
+ (key_id,),
148
+ )
149
+
150
+ conn.commit()
151
+ cur.close()
152
+ conn.close()
153
+
154
+ return {"id": key_id, "name": name, "scopes": scopes}
155
+
156
+
157
+ @app.get("/")
158
+ def root():
159
+ return {
160
+ "service": "PostgreSQL General HF API",
161
+ "status": "ok",
162
+ "docs": "/docs",
163
+ "health": "/api/health",
164
+ }
165
+
166
+
167
+ @app.get("/api/health")
168
+ def health():
169
+ return {"status": "ok", "time": datetime.utcnow().isoformat()}
170
+
171
+
172
+ @app.get("/api/db-health")
173
+ def db_health(authorization: Optional[str] = Header(default=None)):
174
+ verify_api_key(authorization, required_scope="read")
175
+
176
+ conn = get_conn()
177
+ cur = conn.cursor()
178
+ cur.execute("SELECT 1;")
179
+ result = cur.fetchone()
180
+ cur.close()
181
+ conn.close()
182
+
183
+ return {"status": "ok", "db": result[0]}
184
+
185
+
186
+ class CreateApiKeyRequest(BaseModel):
187
+ name: str
188
+ scopes: List[str] = ["read", "write"]
189
+
190
+
191
+ @app.post("/admin/api-keys")
192
+ def create_api_key(
193
+ body: CreateApiKeyRequest,
194
+ x_admin_user: Optional[str] = Header(default=None),
195
+ x_admin_password: Optional[str] = Header(default=None),
196
+ ):
197
+ verify_admin(x_admin_user, x_admin_password)
198
+
199
+ allowed_scopes = {"read", "write"}
200
+ invalid_scopes = [scope for scope in body.scopes if scope not in allowed_scopes]
201
+ if invalid_scopes:
202
+ raise HTTPException(status_code=400, detail=f"Invalid scopes: {invalid_scopes}")
203
+
204
+ raw_key = "pgk_" + secrets.token_hex(24)
205
+ key_hash = hash_key(raw_key)
206
+ key_prefix = raw_key[:12]
207
+
208
+ conn = get_conn()
209
+ cur = conn.cursor()
210
+
211
+ cur.execute(
212
+ """
213
+ INSERT INTO api_keys (name, key_hash, key_prefix, scopes)
214
+ VALUES (%s, %s, %s, %s)
215
+ RETURNING id, created_at;
216
+ """,
217
+ (body.name, key_hash, key_prefix, body.scopes),
218
+ )
219
+
220
+ row = cur.fetchone()
221
+ conn.commit()
222
+ cur.close()
223
+ conn.close()
224
+
225
+ return {
226
+ "id": row[0],
227
+ "name": body.name,
228
+ "api_key": raw_key,
229
+ "key_prefix": key_prefix,
230
+ "scopes": body.scopes,
231
+ "created_at": row[1],
232
+ "warning": "This API key is shown only once. Save it now.",
233
+ }
234
+
235
+
236
+ @app.get("/admin/api-keys")
237
+ def list_api_keys(
238
+ x_admin_user: Optional[str] = Header(default=None),
239
+ x_admin_password: Optional[str] = Header(default=None),
240
+ ):
241
+ verify_admin(x_admin_user, x_admin_password)
242
+
243
+ conn = get_conn()
244
+ cur = conn.cursor()
245
+
246
+ cur.execute(
247
+ """
248
+ SELECT id, name, key_prefix, scopes, is_active, created_at, last_used_at
249
+ FROM api_keys
250
+ ORDER BY id DESC;
251
+ """
252
+ )
253
+
254
+ rows = cur.fetchall()
255
+ cur.close()
256
+ conn.close()
257
+
258
+ return [
259
+ {
260
+ "id": row[0],
261
+ "name": row[1],
262
+ "key_prefix": row[2],
263
+ "scopes": row[3],
264
+ "is_active": row[4],
265
+ "created_at": row[5],
266
+ "last_used_at": row[6],
267
+ }
268
+ for row in rows
269
+ ]
270
+
271
+
272
+ class RevokeApiKeyRequest(BaseModel):
273
+ id: int
274
+
275
+
276
+ @app.post("/admin/api-keys/revoke")
277
+ def revoke_api_key(
278
+ body: RevokeApiKeyRequest,
279
+ x_admin_user: Optional[str] = Header(default=None),
280
+ x_admin_password: Optional[str] = Header(default=None),
281
+ ):
282
+ verify_admin(x_admin_user, x_admin_password)
283
+
284
+ conn = get_conn()
285
+ cur = conn.cursor()
286
+
287
+ cur.execute(
288
+ """
289
+ UPDATE api_keys
290
+ SET is_active = false
291
+ WHERE id = %s
292
+ RETURNING id, name;
293
+ """,
294
+ (body.id,),
295
+ )
296
+
297
+ row = cur.fetchone()
298
+ conn.commit()
299
+ cur.close()
300
+ conn.close()
301
+
302
+ if not row:
303
+ raise HTTPException(status_code=404, detail="API key not found")
304
+
305
+ return {"id": row[0], "name": row[1], "status": "revoked"}
306
+
307
+
308
+ class FileRecord(BaseModel):
309
+ user_id: Optional[str] = None
310
+ filename: str
311
+ file_path: str
312
+ file_size: Optional[int] = None
313
+ mime_type: Optional[str] = None
314
+
315
+
316
+ @app.post("/api/files")
317
+ def create_file(record: FileRecord, authorization: Optional[str] = Header(default=None)):
318
+ verify_api_key(authorization, required_scope="write")
319
+
320
+ conn = get_conn()
321
+ cur = conn.cursor()
322
+
323
+ cur.execute(
324
+ """
325
+ INSERT INTO files (user_id, filename, file_path, file_size, mime_type)
326
+ VALUES (%s, %s, %s, %s, %s)
327
+ RETURNING id, created_at;
328
+ """,
329
+ (record.user_id, record.filename, record.file_path, record.file_size, record.mime_type),
330
+ )
331
+
332
+ row = cur.fetchone()
333
+ conn.commit()
334
+ cur.close()
335
+ conn.close()
336
+
337
+ return {
338
+ "id": row[0],
339
+ "created_at": row[1],
340
+ "filename": record.filename,
341
+ "file_path": record.file_path,
342
+ }
343
+
344
+
345
+ @app.get("/api/files")
346
+ def list_files(authorization: Optional[str] = Header(default=None)):
347
+ verify_api_key(authorization, required_scope="read")
348
+
349
+ conn = get_conn()
350
+ cur = conn.cursor()
351
+
352
+ cur.execute(
353
+ """
354
+ SELECT id, user_id, filename, file_path, file_size, mime_type, created_at
355
+ FROM files
356
+ ORDER BY id DESC
357
+ LIMIT 100;
358
+ """
359
+ )
360
+
361
+ rows = cur.fetchall()
362
+ cur.close()
363
+ conn.close()
364
+
365
+ return [
366
+ {
367
+ "id": row[0],
368
+ "user_id": row[1],
369
+ "filename": row[2],
370
+ "file_path": row[3],
371
+ "file_size": row[4],
372
+ "mime_type": row[5],
373
+ "created_at": row[6],
374
+ }
375
+ for row in rows
376
+ ]
377
+
378
+
379
+ class ArticleRecord(BaseModel):
380
+ source: Optional[str] = None
381
+ title: str
382
+ url: str
383
+ summary: Optional[str] = None
384
+ published_at: Optional[str] = None
385
+
386
+
387
+ @app.post("/api/rss/articles")
388
+ def create_article(article: ArticleRecord, authorization: Optional[str] = Header(default=None)):
389
+ verify_api_key(authorization, required_scope="write")
390
+
391
+ conn = get_conn()
392
+ cur = conn.cursor()
393
+
394
+ cur.execute(
395
+ """
396
+ INSERT INTO rss_articles (source, title, url, summary, published_at)
397
+ VALUES (%s, %s, %s, %s, %s)
398
+ ON CONFLICT (url) DO UPDATE SET
399
+ title = EXCLUDED.title,
400
+ summary = EXCLUDED.summary,
401
+ published_at = EXCLUDED.published_at
402
+ RETURNING id;
403
+ """,
404
+ (article.source, article.title, article.url, article.summary, article.published_at),
405
+ )
406
+
407
+ row = cur.fetchone()
408
+ conn.commit()
409
+ cur.close()
410
+ conn.close()
411
+
412
+ return {"id": row[0], "status": "saved"}
413
+
414
+
415
+ @app.get("/api/rss/articles")
416
+ def list_articles(authorization: Optional[str] = Header(default=None)):
417
+ verify_api_key(authorization, required_scope="read")
418
+
419
+ conn = get_conn()
420
+ cur = conn.cursor()
421
+
422
+ cur.execute(
423
+ """
424
+ SELECT id, source, title, url, summary, published_at, created_at
425
+ FROM rss_articles
426
+ ORDER BY id DESC
427
+ LIMIT 100;
428
+ """
429
+ )
430
+
431
+ rows = cur.fetchall()
432
+ cur.close()
433
+ conn.close()
434
+
435
+ return [
436
+ {
437
+ "id": row[0],
438
+ "source": row[1],
439
+ "title": row[2],
440
+ "url": row[3],
441
+ "summary": row[4],
442
+ "published_at": row[5],
443
+ "created_at": row[6],
444
+ }
445
+ for row in rows
446
+ ]