Jimmy commited on
Commit ·
467ce6a
1
Parent(s): 9eb834a
Improve error messages and ensure unique user key names
Browse files- api/accounts.py +4 -4
- api/support.py +2 -2
- services/auth_service.py +43 -5
- test/test_account_image_capabilities.py +16 -0
- web/src/components/top-nav.tsx +2 -1
api/accounts.py
CHANGED
|
@@ -122,20 +122,20 @@ def create_router() -> APIRouter:
|
|
| 122 |
if value is not None
|
| 123 |
}
|
| 124 |
if not updates:
|
| 125 |
-
raise HTTPException(status_code=400, detail={"error": "
|
| 126 |
try:
|
| 127 |
item = auth_service.update_key(key_id, updates, role="user")
|
| 128 |
except ValueError as exc:
|
| 129 |
raise HTTPException(status_code=400, detail={"error": str(exc)}) from exc
|
| 130 |
if item is None:
|
| 131 |
-
raise HTTPException(status_code=404, detail={"error": "
|
| 132 |
return {"item": item, "items": auth_service.list_keys(role="user")}
|
| 133 |
|
| 134 |
@router.delete("/api/auth/users/{key_id}")
|
| 135 |
async def delete_user_key(key_id: str, authorization: str | None = Header(default=None)):
|
| 136 |
require_admin(authorization)
|
| 137 |
if not auth_service.delete_key(key_id, role="user"):
|
| 138 |
-
raise HTTPException(status_code=404, detail={"error": "
|
| 139 |
return {"items": auth_service.list_keys(role="user")}
|
| 140 |
|
| 141 |
@router.get("/api/accounts")
|
|
@@ -184,7 +184,7 @@ def create_router() -> APIRouter:
|
|
| 184 |
raise HTTPException(status_code=400, detail={"error": "access_token is required"})
|
| 185 |
updates = {key: value for key, value in {"type": body.type, "status": body.status, "quota": body.quota}.items() if value is not None}
|
| 186 |
if not updates:
|
| 187 |
-
raise HTTPException(status_code=400, detail={"error": "
|
| 188 |
account = account_service.update_account(access_token, updates)
|
| 189 |
if account is None:
|
| 190 |
raise HTTPException(status_code=404, detail={"error": "account not found"})
|
|
|
|
| 122 |
if value is not None
|
| 123 |
}
|
| 124 |
if not updates:
|
| 125 |
+
raise HTTPException(status_code=400, detail={"error": "还没有检测到改动,请修改后再保存"})
|
| 126 |
try:
|
| 127 |
item = auth_service.update_key(key_id, updates, role="user")
|
| 128 |
except ValueError as exc:
|
| 129 |
raise HTTPException(status_code=400, detail={"error": str(exc)}) from exc
|
| 130 |
if item is None:
|
| 131 |
+
raise HTTPException(status_code=404, detail={"error": "这条用户密钥不存在,可能已经被删除"})
|
| 132 |
return {"item": item, "items": auth_service.list_keys(role="user")}
|
| 133 |
|
| 134 |
@router.delete("/api/auth/users/{key_id}")
|
| 135 |
async def delete_user_key(key_id: str, authorization: str | None = Header(default=None)):
|
| 136 |
require_admin(authorization)
|
| 137 |
if not auth_service.delete_key(key_id, role="user"):
|
| 138 |
+
raise HTTPException(status_code=404, detail={"error": "这条用户密钥不存在,可能已经被删除"})
|
| 139 |
return {"items": auth_service.list_keys(role="user")}
|
| 140 |
|
| 141 |
@router.get("/api/accounts")
|
|
|
|
| 184 |
raise HTTPException(status_code=400, detail={"error": "access_token is required"})
|
| 185 |
updates = {key: value for key, value in {"type": body.type, "status": body.status, "quota": body.quota}.items() if value is not None}
|
| 186 |
if not updates:
|
| 187 |
+
raise HTTPException(status_code=400, detail={"error": "还没有检测到改动,请修改后再保存"})
|
| 188 |
account = account_service.update_account(access_token, updates)
|
| 189 |
if account is None:
|
| 190 |
raise HTTPException(status_code=404, detail={"error": "account not found"})
|
api/support.py
CHANGED
|
@@ -31,7 +31,7 @@ def require_identity(authorization: str | None) -> dict[str, object]:
|
|
| 31 |
token = extract_bearer_token(authorization)
|
| 32 |
identity = _legacy_admin_identity(token) or auth_service.authenticate(token)
|
| 33 |
if identity is None:
|
| 34 |
-
raise HTTPException(status_code=401, detail={"error": "
|
| 35 |
return identity
|
| 36 |
|
| 37 |
|
|
@@ -42,7 +42,7 @@ def require_auth_key(authorization: str | None) -> None:
|
|
| 42 |
def require_admin(authorization: str | None) -> dict[str, object]:
|
| 43 |
identity = require_identity(authorization)
|
| 44 |
if identity.get("role") != "admin":
|
| 45 |
-
raise HTTPException(status_code=403, detail={"error": "
|
| 46 |
return identity
|
| 47 |
|
| 48 |
|
|
|
|
| 31 |
token = extract_bearer_token(authorization)
|
| 32 |
identity = _legacy_admin_identity(token) or auth_service.authenticate(token)
|
| 33 |
if identity is None:
|
| 34 |
+
raise HTTPException(status_code=401, detail={"error": "密钥无效或已失效,请重新登录"})
|
| 35 |
return identity
|
| 36 |
|
| 37 |
|
|
|
|
| 42 |
def require_admin(authorization: str | None) -> dict[str, object]:
|
| 43 |
identity = require_identity(authorization)
|
| 44 |
if identity.get("role") != "admin":
|
| 45 |
+
raise HTTPException(status_code=403, detail={"error": "需要管理员权限才能执行这个操作"})
|
| 46 |
return identity
|
| 47 |
|
| 48 |
|
services/auth_service.py
CHANGED
|
@@ -105,19 +105,52 @@ class AuthService:
|
|
| 105 |
def _build_key_hash_locked(self, raw_key: str, *, exclude_id: str = "") -> str:
|
| 106 |
candidate = self._clean(raw_key)
|
| 107 |
if not candidate:
|
| 108 |
-
raise ValueError("
|
| 109 |
admin_key = self._clean(config.auth_key)
|
| 110 |
if admin_key and hmac.compare_digest(candidate, admin_key):
|
| 111 |
-
raise ValueError("
|
| 112 |
key_hash = _hash_key(candidate)
|
| 113 |
if self._has_key_hash_locked(key_hash, exclude_id=exclude_id):
|
| 114 |
-
raise ValueError("
|
| 115 |
return key_hash
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
def create_key(self, *, role: AuthRole, name: str = "") -> tuple[dict[str, object], str]:
|
| 118 |
-
normalized_name = self._clean(name) or self._default_name(role)
|
| 119 |
with self._lock:
|
| 120 |
self._reload_locked()
|
|
|
|
| 121 |
while True:
|
| 122 |
raw_key = f"sk-{secrets.token_urlsafe(24)}"
|
| 123 |
try:
|
|
@@ -156,8 +189,13 @@ class AuthService:
|
|
| 156 |
if role is not None and item.get("role") != role:
|
| 157 |
return None
|
| 158 |
next_item = dict(item)
|
|
|
|
| 159 |
if "name" in updates and updates.get("name") is not None:
|
| 160 |
-
next_item["name"] = self.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
if "enabled" in updates and updates.get("enabled") is not None:
|
| 162 |
next_item["enabled"] = bool(updates.get("enabled"))
|
| 163 |
if "key" in updates and updates.get("key") is not None:
|
|
|
|
| 105 |
def _build_key_hash_locked(self, raw_key: str, *, exclude_id: str = "") -> str:
|
| 106 |
candidate = self._clean(raw_key)
|
| 107 |
if not candidate:
|
| 108 |
+
raise ValueError("请输入新的专用密钥")
|
| 109 |
admin_key = self._clean(config.auth_key)
|
| 110 |
if admin_key and hmac.compare_digest(candidate, admin_key):
|
| 111 |
+
raise ValueError("这个密钥和管理员密钥冲突了,请换一个新的密钥")
|
| 112 |
key_hash = _hash_key(candidate)
|
| 113 |
if self._has_key_hash_locked(key_hash, exclude_id=exclude_id):
|
| 114 |
+
raise ValueError("这个专用密钥已经存在,请换一个新的密钥")
|
| 115 |
return key_hash
|
| 116 |
|
| 117 |
+
def _has_name_locked(self, name: str, *, role: AuthRole | None = None, exclude_id: str = "") -> bool:
|
| 118 |
+
candidate = self._clean(name)
|
| 119 |
+
if not candidate:
|
| 120 |
+
return False
|
| 121 |
+
for item in self._items:
|
| 122 |
+
item_id = self._clean(item.get("id"))
|
| 123 |
+
if exclude_id and item_id == exclude_id:
|
| 124 |
+
continue
|
| 125 |
+
if role is not None and item.get("role") != role:
|
| 126 |
+
continue
|
| 127 |
+
if self._clean(item.get("name")) == candidate:
|
| 128 |
+
return True
|
| 129 |
+
return False
|
| 130 |
+
|
| 131 |
+
def _build_default_name_locked(self, role: AuthRole, *, exclude_id: str = "") -> str:
|
| 132 |
+
base_name = self._default_name(role)
|
| 133 |
+
if not self._has_name_locked(base_name, role=role, exclude_id=exclude_id):
|
| 134 |
+
return base_name
|
| 135 |
+
suffix = 2
|
| 136 |
+
while True:
|
| 137 |
+
candidate = f"{base_name} {suffix}"
|
| 138 |
+
if not self._has_name_locked(candidate, role=role, exclude_id=exclude_id):
|
| 139 |
+
return candidate
|
| 140 |
+
suffix += 1
|
| 141 |
+
|
| 142 |
+
def _build_name_locked(self, name: str, *, role: AuthRole, exclude_id: str = "") -> str:
|
| 143 |
+
candidate = self._clean(name)
|
| 144 |
+
if not candidate:
|
| 145 |
+
return self._build_default_name_locked(role, exclude_id=exclude_id)
|
| 146 |
+
if self._has_name_locked(candidate, role=role, exclude_id=exclude_id):
|
| 147 |
+
raise ValueError("这个名称已经在使用中了,换一个更容易区分的名称吧")
|
| 148 |
+
return candidate
|
| 149 |
+
|
| 150 |
def create_key(self, *, role: AuthRole, name: str = "") -> tuple[dict[str, object], str]:
|
|
|
|
| 151 |
with self._lock:
|
| 152 |
self._reload_locked()
|
| 153 |
+
normalized_name = self._build_name_locked(name, role=role)
|
| 154 |
while True:
|
| 155 |
raw_key = f"sk-{secrets.token_urlsafe(24)}"
|
| 156 |
try:
|
|
|
|
| 189 |
if role is not None and item.get("role") != role:
|
| 190 |
return None
|
| 191 |
next_item = dict(item)
|
| 192 |
+
next_role = "admin" if str(next_item.get("role") or "").strip().lower() == "admin" else "user"
|
| 193 |
if "name" in updates and updates.get("name") is not None:
|
| 194 |
+
next_item["name"] = self._build_name_locked(
|
| 195 |
+
str(updates.get("name") or ""),
|
| 196 |
+
role=next_role,
|
| 197 |
+
exclude_id=normalized_id,
|
| 198 |
+
)
|
| 199 |
if "enabled" in updates and updates.get("enabled") is not None:
|
| 200 |
next_item["enabled"] = bool(updates.get("enabled"))
|
| 201 |
if "key" in updates and updates.get("key") is not None:
|
test/test_account_image_capabilities.py
CHANGED
|
@@ -133,6 +133,22 @@ class AuthServiceTests(unittest.TestCase):
|
|
| 133 |
self.assertIsNotNone(authed)
|
| 134 |
self.assertEqual(authed["id"], item["id"])
|
| 135 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
if __name__ == "__main__":
|
| 138 |
unittest.main()
|
|
|
|
| 133 |
self.assertIsNotNone(authed)
|
| 134 |
self.assertEqual(authed["id"], item["id"])
|
| 135 |
|
| 136 |
+
def test_user_key_name_must_be_unique(self) -> None:
|
| 137 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 138 |
+
service = AuthService(JSONStorageBackend(Path(tmp_dir) / "accounts.json", Path(tmp_dir) / "auth_keys.json"))
|
| 139 |
+
first, _ = service.create_key(role="user", name="Alice")
|
| 140 |
+
second, _ = service.create_key(role="user", name="Bob")
|
| 141 |
+
|
| 142 |
+
with self.assertRaisesRegex(ValueError, "这个名称已经在使用中了"):
|
| 143 |
+
service.create_key(role="user", name="Alice")
|
| 144 |
+
|
| 145 |
+
with self.assertRaisesRegex(ValueError, "这个名称已经在使用中了"):
|
| 146 |
+
service.update_key(second["id"], {"name": "Alice"}, role="user")
|
| 147 |
+
|
| 148 |
+
updated = service.update_key(first["id"], {"name": "Alice"}, role="user")
|
| 149 |
+
self.assertIsNotNone(updated)
|
| 150 |
+
self.assertEqual(updated["name"], "Alice")
|
| 151 |
+
|
| 152 |
|
| 153 |
if __name__ == "__main__":
|
| 154 |
unittest.main()
|
web/src/components/top-nav.tsx
CHANGED
|
@@ -62,6 +62,7 @@ export function TopNav() {
|
|
| 62 |
|
| 63 |
const navItems = session.role === "admin" ? adminNavItems : userNavItems;
|
| 64 |
const roleLabel = session.role === "admin" ? "管理员" : "普通用户";
|
|
|
|
| 65 |
|
| 66 |
return (
|
| 67 |
<header className="border-b border-stone-100/50">
|
|
@@ -113,7 +114,7 @@ export function TopNav() {
|
|
| 113 |
</nav>
|
| 114 |
<div className="hidden items-center justify-end gap-2 sm:flex sm:gap-3">
|
| 115 |
<span className="hidden rounded-md bg-stone-100 px-2 py-1 text-[10px] font-medium text-stone-500 sm:inline-block sm:text-[11px]">
|
| 116 |
-
{roleLabel}
|
| 117 |
</span>
|
| 118 |
<span className="hidden rounded-md bg-stone-100 px-2 py-1 text-[10px] font-medium text-stone-500 sm:inline-block sm:text-[11px]">
|
| 119 |
v{webConfig.appVersion}
|
|
|
|
| 62 |
|
| 63 |
const navItems = session.role === "admin" ? adminNavItems : userNavItems;
|
| 64 |
const roleLabel = session.role === "admin" ? "管理员" : "普通用户";
|
| 65 |
+
const displayName = session.name.trim() || roleLabel;
|
| 66 |
|
| 67 |
return (
|
| 68 |
<header className="border-b border-stone-100/50">
|
|
|
|
| 114 |
</nav>
|
| 115 |
<div className="hidden items-center justify-end gap-2 sm:flex sm:gap-3">
|
| 116 |
<span className="hidden rounded-md bg-stone-100 px-2 py-1 text-[10px] font-medium text-stone-500 sm:inline-block sm:text-[11px]">
|
| 117 |
+
{roleLabel} · {displayName}
|
| 118 |
</span>
|
| 119 |
<span className="hidden rounded-md bg-stone-100 px-2 py-1 text-[10px] font-medium text-stone-500 sm:inline-block sm:text-[11px]">
|
| 120 |
v{webConfig.appVersion}
|