-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroutes_admin.py
More file actions
346 lines (302 loc) · 12.4 KB
/
routes_admin.py
File metadata and controls
346 lines (302 loc) · 12.4 KB
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
"""Admin-only routes for managing users and viewing audit log."""
import datetime
import re
from typing import Dict, List, Optional
import mariadb
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from db_utils import get_db_connection, validate_table_and_columns, write_audit_log
from security import User, UserCreate, get_current_admin, get_password_hash
from settings import logger
router = APIRouter(prefix="/admin", tags=["admin"])
class AuditLogEntry(BaseModel):
id: int
actor: str
action: str
table_name: str
row_id: Optional[int] = None
details: Optional[str] = None
created_at: datetime.datetime
@router.post("/users", response_model=User)
async def create_user(user: UserCreate, current_admin: User = Depends(get_current_admin)):
role = user.role.lower()
if role not in ("user", "admin"):
raise HTTPException(status_code=400, detail="Role must be 'user' or 'admin'")
hashed_password = get_password_hash(user.password)
conn = get_db_connection()
try:
cur = conn.cursor()
cur.execute(
"INSERT INTO users (username, password_hash, role) VALUES (%s, %s, %s)",
(user.username, hashed_password, role),
)
conn.commit()
user_id = cur.lastrowid
except mariadb.Error as e:
conn.rollback()
logger.exception("Error creating user '%s'", user.username)
raise HTTPException(status_code=400, detail=f"Error creating user: {e}")
finally:
conn.close()
write_audit_log(current_admin.username, "create_user", "users", user_id, {"username": user.username, "role": role})
return User(id=user_id, username=user.username, role=role)
@router.get("/users", response_model=List[User])
async def list_users(current_admin: User = Depends(get_current_admin)):
conn = get_db_connection()
try:
cur = conn.cursor(dictionary=True)
cur.execute("SELECT id, username, role FROM users")
rows = cur.fetchall()
return [User(id=row["id"], username=row["username"], role=row["role"]) for row in rows]
finally:
conn.close()
@router.get("/audit", response_model=List[AuditLogEntry])
async def get_audit_log(limit: int = 100, current_admin: User = Depends(get_current_admin)):
if limit <= 0 or limit > 1000:
raise HTTPException(status_code=400, detail="Limit must be between 1 and 1000")
conn = get_db_connection()
try:
cur = conn.cursor(dictionary=True)
cur.execute(
"SELECT id, actor, action, table_name, row_id, details, created_at "
"FROM audit_log ORDER BY created_at DESC, id DESC LIMIT %s",
(limit,),
)
rows = cur.fetchall()
result: List[AuditLogEntry] = []
for row in rows:
result.append(
AuditLogEntry(
id=row["id"],
actor=row["actor"],
action=row["action"],
table_name=row["table_name"],
row_id=row.get("row_id"),
details=row.get("details"),
created_at=row["created_at"],
)
)
return result
except mariadb.Error as e:
logger.exception("Error reading audit log")
raise HTTPException(status_code=500, detail=f"Error reading audit log: {e}")
finally:
conn.close()
class ColumnInfo(BaseModel):
name: str
data_type: str
is_nullable: bool
is_primary_key: bool
class TableSchema(BaseModel):
table: str
columns: List[ColumnInfo]
class NewTableColumn(BaseModel):
"""Column definition for creating a new table.
type is a logical type, mapped to MariaDB types:
- "string" -> VARCHAR(length or 255)
- "text" -> TEXT
- "int" -> INT
- "bigint" -> BIGINT
- "float" -> DOUBLE
- "bool" -> TINYINT(1)
- "datetime" -> DATETIME
- "date" -> DATE
- "time" -> TIME
Additional options:
- nullable: whether the column can be NULL
- unique: whether the column has a UNIQUE constraint
- default: default value as string (validated and converted based on type)
"""
name: str
type: str
nullable: bool = True
length: Optional[int] = None
unique: bool = False
default: Optional[str] = None
class CreateTableRequest(BaseModel):
table: str
columns: List[NewTableColumn]
@router.post("/tables")
async def create_table(req: CreateTableRequest, current_admin: User = Depends(get_current_admin)):
"""Create a new table with an auto-increment 'id' primary key and custom columns.
Admins specify table name and a list of columns (name, type, nullable, optional length).
"""
# Basic name validation to avoid SQL injection via identifiers
identifier_re = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
table_name = req.table.strip()
if not table_name or not identifier_re.match(table_name):
raise HTTPException(status_code=400, detail="Invalid table name. Use letters, numbers and '_' and do not start with a digit.")
if not req.columns:
raise HTTPException(status_code=400, detail="At least one column must be defined")
if len(req.columns) > 50:
raise HTTPException(status_code=400, detail="Too many columns (max 50)")
# Validate columns and build SQL fragments
seen_cols = set()
user_columns_sql: List[str] = []
def map_type(col: NewTableColumn) -> str:
t = col.type.strip().lower()
if t in {"string", "varchar"}:
length = col.length or 255
if length <= 0 or length > 65535:
raise HTTPException(status_code=400, detail=f"Invalid length for column '{col.name}'")
return f"VARCHAR({length})"
if t in {"text"}:
return "TEXT"
if t in {"int", "integer"}:
return "INT"
if t in {"bigint"}:
return "BIGINT"
if t in {"float", "double", "number"}:
return "DOUBLE"
if t in {"bool", "boolean"}:
return "TINYINT(1)"
if t in {"datetime", "timestamp"}:
return "DATETIME"
if t in {"date"}:
return "DATE"
if t in {"time"}:
return "TIME"
raise HTTPException(status_code=400, detail=f"Unsupported column type '{col.type}' for column '{col.name}'")
def build_default_sql(col: NewTableColumn) -> Optional[str]:
if col.default is None or col.default == "":
return None
raw = col.default.strip()
# Disallow semicolons to avoid multi-statement injection
if ";" in raw:
raise HTTPException(status_code=400, detail=f"Invalid default value for column '{col.name}'")
t = col.type.strip().lower()
# String-like
if t in {"string", "varchar", "text"}:
escaped = raw.replace("'", "''")
return f"'{escaped}'"
# Numeric
if t in {"int", "integer", "bigint"}:
try:
int(raw)
except ValueError:
raise HTTPException(status_code=400, detail=f"Default for column '{col.name}' must be an integer")
return raw
if t in {"float", "double", "number"}:
try:
float(raw)
except ValueError:
raise HTTPException(status_code=400, detail=f"Default for column '{col.name}' must be a number")
return raw
# Bool
if t in {"bool", "boolean"}:
lower = raw.lower()
if lower in {"1", "true", "yes"}:
return "1"
if lower in {"0", "false", "no"}:
return "0"
raise HTTPException(status_code=400, detail=f"Default for column '{col.name}' must be boolean (true/false)")
# Date / time / datetime – keep as string, lightly validated
if t in {"datetime", "timestamp", "date", "time"}:
escaped = raw.replace("'", "''")
return f"'{escaped}'"
# Fallback (should not be reached because map_type guards types)
escaped = raw.replace("'", "''")
return f"'{escaped}'"
for col in req.columns:
col_name = col.name.strip()
if not col_name or not identifier_re.match(col_name):
raise HTTPException(status_code=400, detail=f"Invalid column name '{col.name}'. Use letters, numbers and '_' and do not start with a digit.")
if col_name.lower() == "id":
raise HTTPException(status_code=400, detail="Column name 'id' is reserved for the primary key")
if col_name in seen_cols:
raise HTTPException(status_code=400, detail=f"Duplicate column name '{col_name}'")
seen_cols.add(col_name)
sql_type = map_type(col)
nullable_sql = " NULL" if col.nullable else " NOT NULL"
unique_sql = " UNIQUE" if col.unique else ""
default_sql = build_default_sql(col)
default_clause = f" DEFAULT {default_sql}" if default_sql is not None else ""
user_columns_sql.append(f"`{col_name}` {sql_type}{nullable_sql}{unique_sql}{default_clause}")
conn = get_db_connection()
try:
cur = conn.cursor()
# Check if table already exists
cur.execute(
"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s",
(table_name,),
)
if cur.fetchone():
raise HTTPException(status_code=400, detail="Table already exists")
# Build CREATE TABLE statement with an auto-increment primary key 'id'
columns_sql = ["`id` INT AUTO_INCREMENT PRIMARY KEY"] + user_columns_sql
create_sql = f"CREATE TABLE `{table_name}` (" + ", ".join(columns_sql) + ")"
cur.execute(create_sql)
conn.commit()
# Audit log
details: Dict[str, object] = {
"columns": [
{
"name": c.name,
"type": c.type,
"nullable": c.nullable,
"length": c.length,
"unique": c.unique,
"default": c.default,
}
for c in req.columns
]
}
write_audit_log(current_admin.username, "create_table", table_name, None, details)
return {
"table": table_name,
"columns": [
{"name": "id", "data_type": "INT", "is_nullable": False, "is_primary_key": True}
]
+ [
{
"name": c.name,
"data_type": map_type(c),
"is_nullable": c.nullable,
"is_primary_key": False,
"unique": c.unique,
"default": c.default,
}
for c in req.columns
],
}
except mariadb.Error as e:
conn.rollback()
logger.exception("Error creating table '%s'", table_name)
raise HTTPException(status_code=400, detail=f"Error creating table: {e}")
finally:
conn.close()
@router.get("/schema", response_model=List[TableSchema])
async def get_schema(current_admin: User = Depends(get_current_admin), table: Optional[str] = None):
"""Return schema information (tables and columns) for the current database."""
conn = get_db_connection()
try:
cur = conn.cursor(dictionary=True)
params: List[str] = []
sql = (
"SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_KEY "
"FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE()"
)
if table:
sql += " AND TABLE_NAME = %s"
params.append(table)
sql += " ORDER BY TABLE_NAME, ORDINAL_POSITION"
cur.execute(sql, params)
rows = cur.fetchall()
schemas: Dict[str, List[ColumnInfo]] = {}
for row in rows:
tname = row["TABLE_NAME"]
cols = schemas.setdefault(tname, [])
cols.append(
ColumnInfo(
name=row["COLUMN_NAME"],
data_type=row["DATA_TYPE"],
is_nullable=row["IS_NULLABLE"] == "YES",
is_primary_key=row.get("COLUMN_KEY") == "PRI",
)
)
return [TableSchema(table=t, columns=c) for t, c in schemas.items()]
except mariadb.Error as e:
logger.exception("Error reading schema information")
raise HTTPException(status_code=500, detail=f"Error reading schema: {e}")
finally:
conn.close()