-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathadmin_api.py
More file actions
266 lines (211 loc) · 7.37 KB
/
admin_api.py
File metadata and controls
266 lines (211 loc) · 7.37 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
import secrets
from datetime import datetime
from typing import Literal
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from proxy_app.auth import SessionUser, get_db_session, require_admin
from proxy_app.db import hash_password
from proxy_app.db_models import User
from proxy_app.usage_recorder import get_usage_retention_days, prune_usage_events
from proxy_app.usage_queries import (
fetch_usage_by_day,
fetch_usage_by_model,
fetch_usage_summary,
)
router = APIRouter(prefix="/api/admin", tags=["admin"])
class AdminUserItem(BaseModel):
id: int
username: str
role: str
is_active: bool
created_at: datetime
last_login_at: datetime | None
class AdminUserListResponse(BaseModel):
users: list[AdminUserItem]
class CreateAdminUserRequest(BaseModel):
username: str
password: str
role: Literal["admin", "user"] = "user"
is_active: bool = True
class ResetPasswordRequest(BaseModel):
password: str | None = None
class ResetPasswordResponse(BaseModel):
id: int
username: str
password: str
class UsageTotals(BaseModel):
request_count: int
prompt_tokens: int
completion_tokens: int
total_tokens: int
cost_usd: float | None
class UsageByDayItem(UsageTotals):
day: str
class UsageByDayResponse(BaseModel):
days: int
rows: list[UsageByDayItem]
class UsageByModelItem(UsageTotals):
model: str | None
class UsageByModelResponse(BaseModel):
days: int
rows: list[UsageByModelItem]
class UsagePruneResponse(BaseModel):
ok: bool
deleted: int
retention_days: int
def _serialize_user(user: User) -> AdminUserItem:
return AdminUserItem(
id=user.id,
username=user.username,
role=user.role,
is_active=user.is_active,
created_at=user.created_at,
last_login_at=user.last_login_at,
)
async def _require_target_user(session: AsyncSession, user_id: int) -> User:
user = await session.get(User, user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found",
)
return user
@router.get("/users", response_model=AdminUserListResponse)
async def admin_list_users(
_: SessionUser = Depends(require_admin),
session: AsyncSession = Depends(get_db_session),
) -> AdminUserListResponse:
rows = await session.scalars(select(User).order_by(User.created_at.asc()))
return AdminUserListResponse(users=[_serialize_user(row) for row in rows])
@router.post("/users", response_model=AdminUserItem)
async def admin_create_user(
payload: CreateAdminUserRequest,
_: SessionUser = Depends(require_admin),
session: AsyncSession = Depends(get_db_session),
) -> AdminUserItem:
username = payload.username.strip()
if not username:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Username cannot be empty",
)
if not payload.password:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Password cannot be empty",
)
existing = await session.scalar(select(User).where(User.username == username))
if existing:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Username already exists",
)
user = User(
username=username,
password_hash=hash_password(payload.password),
role=payload.role,
is_active=payload.is_active,
)
session.add(user)
await session.commit()
await session.refresh(user)
return _serialize_user(user)
@router.post("/users/{id}/disable")
async def admin_disable_user(
id: int,
current_admin: SessionUser = Depends(require_admin),
session: AsyncSession = Depends(get_db_session),
) -> dict[str, bool]:
if current_admin.id == id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Cannot disable your own account",
)
user = await session.get(User, id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found",
)
if user.is_active:
user.is_active = False
await session.commit()
return {"ok": True}
@router.post("/users/{id}/enable")
async def admin_enable_user(
id: int,
_: SessionUser = Depends(require_admin),
session: AsyncSession = Depends(get_db_session),
) -> dict[str, bool]:
user = await session.get(User, id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found",
)
if not user.is_active:
user.is_active = True
await session.commit()
return {"ok": True}
@router.post("/users/{id}/reset-password", response_model=ResetPasswordResponse)
async def admin_reset_password(
id: int,
payload: ResetPasswordRequest,
_: SessionUser = Depends(require_admin),
session: AsyncSession = Depends(get_db_session),
) -> ResetPasswordResponse:
user = await session.get(User, id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found",
)
new_password = payload.password or secrets.token_urlsafe(12)
user.password_hash = hash_password(new_password)
await session.commit()
return ResetPasswordResponse(id=user.id, username=user.username, password=new_password)
@router.get("/users/{id}/usage/summary", response_model=UsageTotals)
async def admin_user_usage_summary(
id: int,
_: SessionUser = Depends(require_admin),
session: AsyncSession = Depends(get_db_session),
) -> UsageTotals:
await _require_target_user(session, id)
return UsageTotals(**(await fetch_usage_summary(session, user_id=id)))
@router.get("/users/{id}/usage/by-day", response_model=UsageByDayResponse)
async def admin_user_usage_by_day(
id: int,
days: int = Query(default=30, ge=1, le=365),
_: SessionUser = Depends(require_admin),
session: AsyncSession = Depends(get_db_session),
) -> UsageByDayResponse:
await _require_target_user(session, id)
rows = await fetch_usage_by_day(session, user_id=id, days=days)
return UsageByDayResponse(days=days, rows=[UsageByDayItem(**row) for row in rows])
@router.get("/users/{id}/usage/by-model", response_model=UsageByModelResponse)
async def admin_user_usage_by_model(
id: int,
days: int = Query(default=30, ge=1, le=365),
_: SessionUser = Depends(require_admin),
session: AsyncSession = Depends(get_db_session),
) -> UsageByModelResponse:
await _require_target_user(session, id)
rows = await fetch_usage_by_model(session, user_id=id, days=days)
return UsageByModelResponse(
days=days,
rows=[UsageByModelItem(**row) for row in rows],
)
@router.post("/usage/prune", response_model=UsagePruneResponse)
async def admin_prune_usage(
request: Request,
_: SessionUser = Depends(require_admin),
) -> UsagePruneResponse:
retention_days = get_usage_retention_days()
session_maker = request.app.state.db_session_maker
deleted = await prune_usage_events(
session_maker,
retention_days=retention_days,
)
return UsagePruneResponse(ok=True, deleted=deleted, retention_days=retention_days)