Lyonle commited on
Commit
2b05f4d
·
1 Parent(s): 6be82e3

feat(auth): 增加 admin/user 密钥角色与访问控制

Browse files
api/accounts.py CHANGED
@@ -4,8 +4,10 @@ from fastapi import APIRouter, Header, HTTPException
4
  from fastapi.concurrency import run_in_threadpool
5
  from pydantic import BaseModel, Field
6
 
 
 
7
  from api.support import (
8
- require_auth_key,
9
  sanitize_cpa_pool,
10
  sanitize_cpa_pools,
11
  sanitize_sub2api_server,
@@ -21,6 +23,16 @@ from services.sub2api_service import (
21
  )
22
 
23
 
 
 
 
 
 
 
 
 
 
 
24
  class AccountCreateRequest(BaseModel):
25
  tokens: list[str] = Field(default_factory=list)
26
 
@@ -81,14 +93,54 @@ class Sub2APIImportRequest(BaseModel):
81
  def create_router() -> APIRouter:
82
  router = APIRouter()
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  @router.get("/api/accounts")
85
  async def get_accounts(authorization: str | None = Header(default=None)):
86
- require_auth_key(authorization)
87
  return {"items": account_service.list_accounts()}
88
 
89
  @router.post("/api/accounts")
90
  async def create_accounts(body: AccountCreateRequest, authorization: str | None = Header(default=None)):
91
- require_auth_key(authorization)
92
  tokens = [str(token or "").strip() for token in body.tokens if str(token or "").strip()]
93
  if not tokens:
94
  raise HTTPException(status_code=400, detail={"error": "tokens is required"})
@@ -103,7 +155,7 @@ def create_router() -> APIRouter:
103
 
104
  @router.delete("/api/accounts")
105
  async def delete_accounts(body: AccountDeleteRequest, authorization: str | None = Header(default=None)):
106
- require_auth_key(authorization)
107
  tokens = [str(token or "").strip() for token in body.tokens if str(token or "").strip()]
108
  if not tokens:
109
  raise HTTPException(status_code=400, detail={"error": "tokens is required"})
@@ -111,7 +163,7 @@ def create_router() -> APIRouter:
111
 
112
  @router.post("/api/accounts/refresh")
113
  async def refresh_accounts(body: AccountRefreshRequest, authorization: str | None = Header(default=None)):
114
- require_auth_key(authorization)
115
  access_tokens = [str(token or "").strip() for token in body.access_tokens if str(token or "").strip()]
116
  if not access_tokens:
117
  access_tokens = account_service.list_tokens()
@@ -121,7 +173,7 @@ def create_router() -> APIRouter:
121
 
122
  @router.post("/api/accounts/update")
123
  async def update_account(body: AccountUpdateRequest, authorization: str | None = Header(default=None)):
124
- require_auth_key(authorization)
125
  access_token = str(body.access_token or "").strip()
126
  if not access_token:
127
  raise HTTPException(status_code=400, detail={"error": "access_token is required"})
@@ -135,12 +187,12 @@ def create_router() -> APIRouter:
135
 
136
  @router.get("/api/cpa/pools")
137
  async def list_cpa_pools(authorization: str | None = Header(default=None)):
138
- require_auth_key(authorization)
139
  return {"pools": sanitize_cpa_pools(cpa_config.list_pools())}
140
 
141
  @router.post("/api/cpa/pools")
142
  async def create_cpa_pool(body: CPAPoolCreateRequest, authorization: str | None = Header(default=None)):
143
- require_auth_key(authorization)
144
  if not body.base_url.strip():
145
  raise HTTPException(status_code=400, detail={"error": "base_url is required"})
146
  if not body.secret_key.strip():
@@ -150,7 +202,7 @@ def create_router() -> APIRouter:
150
 
151
  @router.post("/api/cpa/pools/{pool_id}")
152
  async def update_cpa_pool(pool_id: str, body: CPAPoolUpdateRequest, authorization: str | None = Header(default=None)):
153
- require_auth_key(authorization)
154
  pool = cpa_config.update_pool(pool_id, body.model_dump(exclude_none=True))
155
  if pool is None:
156
  raise HTTPException(status_code=404, detail={"error": "pool not found"})
@@ -158,14 +210,14 @@ def create_router() -> APIRouter:
158
 
159
  @router.delete("/api/cpa/pools/{pool_id}")
160
  async def delete_cpa_pool(pool_id: str, authorization: str | None = Header(default=None)):
161
- require_auth_key(authorization)
162
  if not cpa_config.delete_pool(pool_id):
163
  raise HTTPException(status_code=404, detail={"error": "pool not found"})
164
  return {"pools": sanitize_cpa_pools(cpa_config.list_pools())}
165
 
166
  @router.get("/api/cpa/pools/{pool_id}/files")
167
  async def cpa_pool_files(pool_id: str, authorization: str | None = Header(default=None)):
168
- require_auth_key(authorization)
169
  pool = cpa_config.get_pool(pool_id)
170
  if pool is None:
171
  raise HTTPException(status_code=404, detail={"error": "pool not found"})
@@ -173,7 +225,7 @@ def create_router() -> APIRouter:
173
 
174
  @router.post("/api/cpa/pools/{pool_id}/import")
175
  async def cpa_pool_import(pool_id: str, body: CPAImportRequest, authorization: str | None = Header(default=None)):
176
- require_auth_key(authorization)
177
  pool = cpa_config.get_pool(pool_id)
178
  if pool is None:
179
  raise HTTPException(status_code=404, detail={"error": "pool not found"})
@@ -185,7 +237,7 @@ def create_router() -> APIRouter:
185
 
186
  @router.get("/api/cpa/pools/{pool_id}/import")
187
  async def cpa_pool_import_progress(pool_id: str, authorization: str | None = Header(default=None)):
188
- require_auth_key(authorization)
189
  pool = cpa_config.get_pool(pool_id)
190
  if pool is None:
191
  raise HTTPException(status_code=404, detail={"error": "pool not found"})
@@ -193,12 +245,12 @@ def create_router() -> APIRouter:
193
 
194
  @router.get("/api/sub2api/servers")
195
  async def list_sub2api_servers(authorization: str | None = Header(default=None)):
196
- require_auth_key(authorization)
197
  return {"servers": sanitize_sub2api_servers(sub2api_config.list_servers())}
198
 
199
  @router.post("/api/sub2api/servers")
200
  async def create_sub2api_server(body: Sub2APIServerCreateRequest, authorization: str | None = Header(default=None)):
201
- require_auth_key(authorization)
202
  if not body.base_url.strip():
203
  raise HTTPException(status_code=400, detail={"error": "base_url is required"})
204
  has_login = body.email.strip() and body.password.strip()
@@ -217,7 +269,7 @@ def create_router() -> APIRouter:
217
 
218
  @router.post("/api/sub2api/servers/{server_id}")
219
  async def update_sub2api_server(server_id: str, body: Sub2APIServerUpdateRequest, authorization: str | None = Header(default=None)):
220
- require_auth_key(authorization)
221
  server = sub2api_config.update_server(server_id, body.model_dump(exclude_none=True))
222
  if server is None:
223
  raise HTTPException(status_code=404, detail={"error": "server not found"})
@@ -225,14 +277,14 @@ def create_router() -> APIRouter:
225
 
226
  @router.delete("/api/sub2api/servers/{server_id}")
227
  async def delete_sub2api_server(server_id: str, authorization: str | None = Header(default=None)):
228
- require_auth_key(authorization)
229
  if not sub2api_config.delete_server(server_id):
230
  raise HTTPException(status_code=404, detail={"error": "server not found"})
231
  return {"servers": sanitize_sub2api_servers(sub2api_config.list_servers())}
232
 
233
  @router.get("/api/sub2api/servers/{server_id}/groups")
234
  async def sub2api_server_groups(server_id: str, authorization: str | None = Header(default=None)):
235
- require_auth_key(authorization)
236
  server = sub2api_config.get_server(server_id)
237
  if server is None:
238
  raise HTTPException(status_code=404, detail={"error": "server not found"})
@@ -244,7 +296,7 @@ def create_router() -> APIRouter:
244
 
245
  @router.get("/api/sub2api/servers/{server_id}/accounts")
246
  async def sub2api_server_accounts(server_id: str, authorization: str | None = Header(default=None)):
247
- require_auth_key(authorization)
248
  server = sub2api_config.get_server(server_id)
249
  if server is None:
250
  raise HTTPException(status_code=404, detail={"error": "server not found"})
@@ -256,7 +308,7 @@ def create_router() -> APIRouter:
256
 
257
  @router.post("/api/sub2api/servers/{server_id}/import")
258
  async def sub2api_server_import(server_id: str, body: Sub2APIImportRequest, authorization: str | None = Header(default=None)):
259
- require_auth_key(authorization)
260
  server = sub2api_config.get_server(server_id)
261
  if server is None:
262
  raise HTTPException(status_code=404, detail={"error": "server not found"})
@@ -268,7 +320,7 @@ def create_router() -> APIRouter:
268
 
269
  @router.get("/api/sub2api/servers/{server_id}/import")
270
  async def sub2api_server_import_progress(server_id: str, authorization: str | None = Header(default=None)):
271
- require_auth_key(authorization)
272
  server = sub2api_config.get_server(server_id)
273
  if server is None:
274
  raise HTTPException(status_code=404, detail={"error": "server not found"})
 
4
  from fastapi.concurrency import run_in_threadpool
5
  from pydantic import BaseModel, Field
6
 
7
+ from services.auth_service import auth_service
8
+
9
  from api.support import (
10
+ require_admin,
11
  sanitize_cpa_pool,
12
  sanitize_cpa_pools,
13
  sanitize_sub2api_server,
 
23
  )
24
 
25
 
26
+
27
+ class UserKeyCreateRequest(BaseModel):
28
+ name: str = ""
29
+
30
+
31
+ class UserKeyUpdateRequest(BaseModel):
32
+ name: str | None = None
33
+ enabled: bool | None = None
34
+
35
+
36
  class AccountCreateRequest(BaseModel):
37
  tokens: list[str] = Field(default_factory=list)
38
 
 
93
  def create_router() -> APIRouter:
94
  router = APIRouter()
95
 
96
+ @router.get("/api/auth/users")
97
+ async def list_user_keys(authorization: str | None = Header(default=None)):
98
+ require_admin(authorization)
99
+ return {"items": auth_service.list_keys(role="user")}
100
+
101
+ @router.post("/api/auth/users")
102
+ async def create_user_key(body: UserKeyCreateRequest, authorization: str | None = Header(default=None)):
103
+ require_admin(authorization)
104
+ item, raw_key = auth_service.create_key(role="user", name=body.name)
105
+ return {"item": item, "key": raw_key, "items": auth_service.list_keys(role="user")}
106
+
107
+ @router.post("/api/auth/users/{key_id}")
108
+ async def update_user_key(
109
+ key_id: str,
110
+ body: UserKeyUpdateRequest,
111
+ authorization: str | None = Header(default=None),
112
+ ):
113
+ require_admin(authorization)
114
+ updates = {
115
+ key: value
116
+ for key, value in {
117
+ "name": body.name,
118
+ "enabled": body.enabled,
119
+ }.items()
120
+ if value is not None
121
+ }
122
+ if not updates:
123
+ raise HTTPException(status_code=400, detail={"error": "no updates provided"})
124
+ item = auth_service.update_key(key_id, updates, role="user")
125
+ if item is None:
126
+ raise HTTPException(status_code=404, detail={"error": "user key not found"})
127
+ return {"item": item, "items": auth_service.list_keys(role="user")}
128
+
129
+ @router.delete("/api/auth/users/{key_id}")
130
+ async def delete_user_key(key_id: str, authorization: str | None = Header(default=None)):
131
+ require_admin(authorization)
132
+ if not auth_service.delete_key(key_id, role="user"):
133
+ raise HTTPException(status_code=404, detail={"error": "user key not found"})
134
+ return {"items": auth_service.list_keys(role="user")}
135
+
136
  @router.get("/api/accounts")
137
  async def get_accounts(authorization: str | None = Header(default=None)):
138
+ require_admin(authorization)
139
  return {"items": account_service.list_accounts()}
140
 
141
  @router.post("/api/accounts")
142
  async def create_accounts(body: AccountCreateRequest, authorization: str | None = Header(default=None)):
143
+ require_admin(authorization)
144
  tokens = [str(token or "").strip() for token in body.tokens if str(token or "").strip()]
145
  if not tokens:
146
  raise HTTPException(status_code=400, detail={"error": "tokens is required"})
 
155
 
156
  @router.delete("/api/accounts")
157
  async def delete_accounts(body: AccountDeleteRequest, authorization: str | None = Header(default=None)):
158
+ require_admin(authorization)
159
  tokens = [str(token or "").strip() for token in body.tokens if str(token or "").strip()]
160
  if not tokens:
161
  raise HTTPException(status_code=400, detail={"error": "tokens is required"})
 
163
 
164
  @router.post("/api/accounts/refresh")
165
  async def refresh_accounts(body: AccountRefreshRequest, authorization: str | None = Header(default=None)):
166
+ require_admin(authorization)
167
  access_tokens = [str(token or "").strip() for token in body.access_tokens if str(token or "").strip()]
168
  if not access_tokens:
169
  access_tokens = account_service.list_tokens()
 
173
 
174
  @router.post("/api/accounts/update")
175
  async def update_account(body: AccountUpdateRequest, authorization: str | None = Header(default=None)):
176
+ require_admin(authorization)
177
  access_token = str(body.access_token or "").strip()
178
  if not access_token:
179
  raise HTTPException(status_code=400, detail={"error": "access_token is required"})
 
187
 
188
  @router.get("/api/cpa/pools")
189
  async def list_cpa_pools(authorization: str | None = Header(default=None)):
190
+ require_admin(authorization)
191
  return {"pools": sanitize_cpa_pools(cpa_config.list_pools())}
192
 
193
  @router.post("/api/cpa/pools")
194
  async def create_cpa_pool(body: CPAPoolCreateRequest, authorization: str | None = Header(default=None)):
195
+ require_admin(authorization)
196
  if not body.base_url.strip():
197
  raise HTTPException(status_code=400, detail={"error": "base_url is required"})
198
  if not body.secret_key.strip():
 
202
 
203
  @router.post("/api/cpa/pools/{pool_id}")
204
  async def update_cpa_pool(pool_id: str, body: CPAPoolUpdateRequest, authorization: str | None = Header(default=None)):
205
+ require_admin(authorization)
206
  pool = cpa_config.update_pool(pool_id, body.model_dump(exclude_none=True))
207
  if pool is None:
208
  raise HTTPException(status_code=404, detail={"error": "pool not found"})
 
210
 
211
  @router.delete("/api/cpa/pools/{pool_id}")
212
  async def delete_cpa_pool(pool_id: str, authorization: str | None = Header(default=None)):
213
+ require_admin(authorization)
214
  if not cpa_config.delete_pool(pool_id):
215
  raise HTTPException(status_code=404, detail={"error": "pool not found"})
216
  return {"pools": sanitize_cpa_pools(cpa_config.list_pools())}
217
 
218
  @router.get("/api/cpa/pools/{pool_id}/files")
219
  async def cpa_pool_files(pool_id: str, authorization: str | None = Header(default=None)):
220
+ require_admin(authorization)
221
  pool = cpa_config.get_pool(pool_id)
222
  if pool is None:
223
  raise HTTPException(status_code=404, detail={"error": "pool not found"})
 
225
 
226
  @router.post("/api/cpa/pools/{pool_id}/import")
227
  async def cpa_pool_import(pool_id: str, body: CPAImportRequest, authorization: str | None = Header(default=None)):
228
+ require_admin(authorization)
229
  pool = cpa_config.get_pool(pool_id)
230
  if pool is None:
231
  raise HTTPException(status_code=404, detail={"error": "pool not found"})
 
237
 
238
  @router.get("/api/cpa/pools/{pool_id}/import")
239
  async def cpa_pool_import_progress(pool_id: str, authorization: str | None = Header(default=None)):
240
+ require_admin(authorization)
241
  pool = cpa_config.get_pool(pool_id)
242
  if pool is None:
243
  raise HTTPException(status_code=404, detail={"error": "pool not found"})
 
245
 
246
  @router.get("/api/sub2api/servers")
247
  async def list_sub2api_servers(authorization: str | None = Header(default=None)):
248
+ require_admin(authorization)
249
  return {"servers": sanitize_sub2api_servers(sub2api_config.list_servers())}
250
 
251
  @router.post("/api/sub2api/servers")
252
  async def create_sub2api_server(body: Sub2APIServerCreateRequest, authorization: str | None = Header(default=None)):
253
+ require_admin(authorization)
254
  if not body.base_url.strip():
255
  raise HTTPException(status_code=400, detail={"error": "base_url is required"})
256
  has_login = body.email.strip() and body.password.strip()
 
269
 
270
  @router.post("/api/sub2api/servers/{server_id}")
271
  async def update_sub2api_server(server_id: str, body: Sub2APIServerUpdateRequest, authorization: str | None = Header(default=None)):
272
+ require_admin(authorization)
273
  server = sub2api_config.update_server(server_id, body.model_dump(exclude_none=True))
274
  if server is None:
275
  raise HTTPException(status_code=404, detail={"error": "server not found"})
 
277
 
278
  @router.delete("/api/sub2api/servers/{server_id}")
279
  async def delete_sub2api_server(server_id: str, authorization: str | None = Header(default=None)):
280
+ require_admin(authorization)
281
  if not sub2api_config.delete_server(server_id):
282
  raise HTTPException(status_code=404, detail={"error": "server not found"})
283
  return {"servers": sanitize_sub2api_servers(sub2api_config.list_servers())}
284
 
285
  @router.get("/api/sub2api/servers/{server_id}/groups")
286
  async def sub2api_server_groups(server_id: str, authorization: str | None = Header(default=None)):
287
+ require_admin(authorization)
288
  server = sub2api_config.get_server(server_id)
289
  if server is None:
290
  raise HTTPException(status_code=404, detail={"error": "server not found"})
 
296
 
297
  @router.get("/api/sub2api/servers/{server_id}/accounts")
298
  async def sub2api_server_accounts(server_id: str, authorization: str | None = Header(default=None)):
299
+ require_admin(authorization)
300
  server = sub2api_config.get_server(server_id)
301
  if server is None:
302
  raise HTTPException(status_code=404, detail={"error": "server not found"})
 
308
 
309
  @router.post("/api/sub2api/servers/{server_id}/import")
310
  async def sub2api_server_import(server_id: str, body: Sub2APIImportRequest, authorization: str | None = Header(default=None)):
311
+ require_admin(authorization)
312
  server = sub2api_config.get_server(server_id)
313
  if server is None:
314
  raise HTTPException(status_code=404, detail={"error": "server not found"})
 
320
 
321
  @router.get("/api/sub2api/servers/{server_id}/import")
322
  async def sub2api_server_import_progress(server_id: str, authorization: str | None = Header(default=None)):
323
+ require_admin(authorization)
324
  server = sub2api_config.get_server(server_id)
325
  if server is None:
326
  raise HTTPException(status_code=404, detail={"error": "server not found"})
api/ai.py CHANGED
@@ -5,7 +5,7 @@ from fastapi.concurrency import run_in_threadpool
5
  from fastapi.responses import StreamingResponse
6
  from pydantic import BaseModel, ConfigDict, Field
7
 
8
- from api.support import raise_image_quota_error, require_auth_key, resolve_image_base_url
9
  from services.account_service import account_service
10
  from services.chatgpt_service import ChatGPTService, ImageGenerationError
11
  from utils.helper import is_image_chat_request, sse_json_stream
@@ -45,7 +45,7 @@ def create_router(chatgpt_service: ChatGPTService) -> APIRouter:
45
 
46
  @router.get("/v1/models")
47
  async def list_models(authorization: str | None = Header(default=None)):
48
- require_auth_key(authorization)
49
  try:
50
  return await run_in_threadpool(chatgpt_service.list_models)
51
  except Exception as exc:
@@ -57,7 +57,7 @@ def create_router(chatgpt_service: ChatGPTService) -> APIRouter:
57
  request: Request,
58
  authorization: str | None = Header(default=None),
59
  ):
60
- require_auth_key(authorization)
61
  base_url = resolve_image_base_url(request)
62
  if body.stream:
63
  try:
@@ -92,7 +92,7 @@ def create_router(chatgpt_service: ChatGPTService) -> APIRouter:
92
  response_format: str = Form(default="b64_json"),
93
  stream: bool | None = Form(default=None),
94
  ):
95
- require_auth_key(authorization)
96
  if n < 1 or n > 4:
97
  raise HTTPException(status_code=400, detail={"error": "n must be between 1 and 4"})
98
  uploads = [*(image or []), *(image_list or [])]
@@ -121,7 +121,7 @@ def create_router(chatgpt_service: ChatGPTService) -> APIRouter:
121
 
122
  @router.post("/v1/chat/completions")
123
  async def create_chat_completion(body: ChatCompletionRequest, authorization: str | None = Header(default=None)):
124
- require_auth_key(authorization)
125
  payload = body.model_dump(mode="python")
126
  if bool(payload.get("stream")):
127
  if is_image_chat_request(payload):
@@ -137,7 +137,7 @@ def create_router(chatgpt_service: ChatGPTService) -> APIRouter:
137
 
138
  @router.post("/v1/responses")
139
  async def create_response(body: ResponseCreateRequest, authorization: str | None = Header(default=None)):
140
- require_auth_key(authorization)
141
  payload = body.model_dump(mode="python")
142
  if bool(payload.get("stream")):
143
  return StreamingResponse(
 
5
  from fastapi.responses import StreamingResponse
6
  from pydantic import BaseModel, ConfigDict, Field
7
 
8
+ from api.support import raise_image_quota_error, require_identity, resolve_image_base_url
9
  from services.account_service import account_service
10
  from services.chatgpt_service import ChatGPTService, ImageGenerationError
11
  from utils.helper import is_image_chat_request, sse_json_stream
 
45
 
46
  @router.get("/v1/models")
47
  async def list_models(authorization: str | None = Header(default=None)):
48
+ require_identity(authorization)
49
  try:
50
  return await run_in_threadpool(chatgpt_service.list_models)
51
  except Exception as exc:
 
57
  request: Request,
58
  authorization: str | None = Header(default=None),
59
  ):
60
+ require_identity(authorization)
61
  base_url = resolve_image_base_url(request)
62
  if body.stream:
63
  try:
 
92
  response_format: str = Form(default="b64_json"),
93
  stream: bool | None = Form(default=None),
94
  ):
95
+ require_identity(authorization)
96
  if n < 1 or n > 4:
97
  raise HTTPException(status_code=400, detail={"error": "n must be between 1 and 4"})
98
  uploads = [*(image or []), *(image_list or [])]
 
121
 
122
  @router.post("/v1/chat/completions")
123
  async def create_chat_completion(body: ChatCompletionRequest, authorization: str | None = Header(default=None)):
124
+ require_identity(authorization)
125
  payload = body.model_dump(mode="python")
126
  if bool(payload.get("stream")):
127
  if is_image_chat_request(payload):
 
137
 
138
  @router.post("/v1/responses")
139
  async def create_response(body: ResponseCreateRequest, authorization: str | None = Header(default=None)):
140
+ require_identity(authorization)
141
  payload = body.model_dump(mode="python")
142
  if bool(payload.get("stream")):
143
  return StreamingResponse(
api/support.py CHANGED
@@ -6,6 +6,7 @@ from threading import Event, Thread
6
  from fastapi import HTTPException, Request
7
 
8
  from services.account_service import account_service
 
9
  from services.config import config
10
 
11
  BASE_DIR = Path(__file__).resolve().parents[1]
@@ -19,10 +20,30 @@ def extract_bearer_token(authorization: str | None) -> str:
19
  return value.strip()
20
 
21
 
22
- def require_auth_key(authorization: str | None) -> None:
23
  auth_key = str(config.auth_key or "").strip()
24
- if not auth_key or extract_bearer_token(authorization) != auth_key:
 
 
 
 
 
 
 
 
25
  raise HTTPException(status_code=401, detail={"error": "authorization is invalid"})
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
 
28
  def resolve_image_base_url(request: Request) -> str:
 
6
  from fastapi import HTTPException, Request
7
 
8
  from services.account_service import account_service
9
+ from services.auth_service import auth_service
10
  from services.config import config
11
 
12
  BASE_DIR = Path(__file__).resolve().parents[1]
 
20
  return value.strip()
21
 
22
 
23
+ def _legacy_admin_identity(token: str) -> dict[str, object] | None:
24
  auth_key = str(config.auth_key or "").strip()
25
+ if auth_key and token == auth_key:
26
+ return {"id": "admin", "name": "管理员", "role": "admin"}
27
+ return None
28
+
29
+
30
+ 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": "authorization is invalid"})
35
+ return identity
36
+
37
+
38
+ def require_auth_key(authorization: str | None) -> None:
39
+ require_identity(authorization)
40
+
41
+
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": "admin permission required"})
46
+ return identity
47
 
48
 
49
  def resolve_image_base_url(request: Request) -> str:
api/system.py CHANGED
@@ -4,7 +4,7 @@ from fastapi import APIRouter, Header, HTTPException
4
  from fastapi.concurrency import run_in_threadpool
5
  from pydantic import BaseModel, ConfigDict
6
 
7
- from api.support import require_auth_key
8
  from services.config import config
9
  from services.proxy_service import test_proxy
10
 
@@ -22,8 +22,14 @@ def create_router(app_version: str) -> APIRouter:
22
 
23
  @router.post("/auth/login")
24
  async def login(authorization: str | None = Header(default=None)):
25
- require_auth_key(authorization)
26
- return {"ok": True, "version": app_version}
 
 
 
 
 
 
27
 
28
  @router.get("/version")
29
  async def get_version():
@@ -31,17 +37,17 @@ def create_router(app_version: str) -> APIRouter:
31
 
32
  @router.get("/api/settings")
33
  async def get_settings(authorization: str | None = Header(default=None)):
34
- require_auth_key(authorization)
35
  return {"config": config.get()}
36
 
37
  @router.post("/api/settings")
38
  async def save_settings(body: SettingsUpdateRequest, authorization: str | None = Header(default=None)):
39
- require_auth_key(authorization)
40
  return {"config": config.update(body.model_dump(mode="python"))}
41
 
42
  @router.post("/api/proxy/test")
43
  async def test_proxy_endpoint(body: ProxyTestRequest, authorization: str | None = Header(default=None)):
44
- require_auth_key(authorization)
45
  candidate = (body.url or "").strip() or config.get_proxy_settings()
46
  if not candidate:
47
  raise HTTPException(status_code=400, detail={"error": "proxy url is required"})
 
4
  from fastapi.concurrency import run_in_threadpool
5
  from pydantic import BaseModel, ConfigDict
6
 
7
+ from api.support import require_admin, require_identity
8
  from services.config import config
9
  from services.proxy_service import test_proxy
10
 
 
22
 
23
  @router.post("/auth/login")
24
  async def login(authorization: str | None = Header(default=None)):
25
+ identity = require_identity(authorization)
26
+ return {
27
+ "ok": True,
28
+ "version": app_version,
29
+ "role": identity.get("role"),
30
+ "subject_id": identity.get("id"),
31
+ "name": identity.get("name"),
32
+ }
33
 
34
  @router.get("/version")
35
  async def get_version():
 
37
 
38
  @router.get("/api/settings")
39
  async def get_settings(authorization: str | None = Header(default=None)):
40
+ require_admin(authorization)
41
  return {"config": config.get()}
42
 
43
  @router.post("/api/settings")
44
  async def save_settings(body: SettingsUpdateRequest, authorization: str | None = Header(default=None)):
45
+ require_admin(authorization)
46
  return {"config": config.update(body.model_dump(mode="python"))}
47
 
48
  @router.post("/api/proxy/test")
49
  async def test_proxy_endpoint(body: ProxyTestRequest, authorization: str | None = Header(default=None)):
50
+ require_admin(authorization)
51
  candidate = (body.url or "").strip() or config.get_proxy_settings()
52
  if not candidate:
53
  raise HTTPException(status_code=400, detail={"error": "proxy url is required"})
pyproject.toml CHANGED
@@ -17,6 +17,11 @@ dependencies = [
17
  "gitpython>=3.1.0",
18
  ]
19
 
 
 
 
 
 
20
  [[tool.uv.index]]
21
  url = "https://mirrors.aliyun.com/pypi/simple"
22
  default = true
 
17
  "gitpython>=3.1.0",
18
  ]
19
 
20
+ [dependency-groups]
21
+ dev = [
22
+ "httpx>=0.28.1",
23
+ ]
24
+
25
  [[tool.uv.index]]
26
  url = "https://mirrors.aliyun.com/pypi/simple"
27
  default = true
services/auth_service.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import json
6
+ import secrets
7
+ import uuid
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+ from threading import Lock
11
+ from typing import Literal
12
+
13
+
14
+ BASE_DIR = Path(__file__).resolve().parents[1]
15
+ DATA_DIR = BASE_DIR / "data"
16
+ AUTH_KEYS_FILE = DATA_DIR / "auth_keys.json"
17
+
18
+ AuthRole = Literal["admin", "user"]
19
+
20
+
21
+ def _now_iso() -> str:
22
+ return datetime.now(timezone.utc).isoformat()
23
+
24
+
25
+ def _hash_key(value: str) -> str:
26
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
27
+
28
+
29
+ class AuthService:
30
+ def __init__(self, store_file: Path):
31
+ self.store_file = store_file
32
+ self._lock = Lock()
33
+ self._items = self._load()
34
+
35
+ @staticmethod
36
+ def _clean(value: object) -> str:
37
+ return str(value or "").strip()
38
+
39
+ def _normalize_item(self, raw: object) -> dict[str, object] | None:
40
+ if not isinstance(raw, dict):
41
+ return None
42
+ role = self._clean(raw.get("role")).lower()
43
+ if role not in {"admin", "user"}:
44
+ return None
45
+ key_hash = self._clean(raw.get("key_hash"))
46
+ if not key_hash:
47
+ return None
48
+ item_id = self._clean(raw.get("id")) or uuid.uuid4().hex[:12]
49
+ name = self._clean(raw.get("name")) or ("管理员密钥" if role == "admin" else "普通用户")
50
+ created_at = self._clean(raw.get("created_at")) or _now_iso()
51
+ last_used_at = self._clean(raw.get("last_used_at")) or None
52
+ return {
53
+ "id": item_id,
54
+ "name": name,
55
+ "role": role,
56
+ "key_hash": key_hash,
57
+ "enabled": bool(raw.get("enabled", True)),
58
+ "created_at": created_at,
59
+ "last_used_at": last_used_at,
60
+ }
61
+
62
+ def _load(self) -> list[dict[str, object]]:
63
+ if not self.store_file.exists():
64
+ return []
65
+ try:
66
+ raw = json.loads(self.store_file.read_text(encoding="utf-8"))
67
+ except Exception:
68
+ return []
69
+ if isinstance(raw, dict):
70
+ items = raw.get("items")
71
+ else:
72
+ items = raw
73
+ if not isinstance(items, list):
74
+ return []
75
+ return [normalized for item in items if (normalized := self._normalize_item(item)) is not None]
76
+
77
+ def _save(self) -> None:
78
+ self.store_file.parent.mkdir(parents=True, exist_ok=True)
79
+ payload = {"items": self._items}
80
+ self.store_file.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
81
+
82
+ @staticmethod
83
+ def _public_item(item: dict[str, object]) -> dict[str, object]:
84
+ return {
85
+ "id": item.get("id"),
86
+ "name": item.get("name"),
87
+ "role": item.get("role"),
88
+ "enabled": bool(item.get("enabled", True)),
89
+ "created_at": item.get("created_at"),
90
+ "last_used_at": item.get("last_used_at"),
91
+ }
92
+
93
+ def list_keys(self, role: AuthRole | None = None) -> list[dict[str, object]]:
94
+ with self._lock:
95
+ items = [item for item in self._items if role is None or item.get("role") == role]
96
+ return [self._public_item(item) for item in items]
97
+
98
+ def create_key(self, *, role: AuthRole, name: str = "") -> tuple[dict[str, object], str]:
99
+ normalized_name = self._clean(name) or ("管理员密钥" if role == "admin" else "普通用户")
100
+ raw_key = f"cg2a_{role}_{secrets.token_urlsafe(24)}"
101
+ item = {
102
+ "id": uuid.uuid4().hex[:12],
103
+ "name": normalized_name,
104
+ "role": role,
105
+ "key_hash": _hash_key(raw_key),
106
+ "enabled": True,
107
+ "created_at": _now_iso(),
108
+ "last_used_at": None,
109
+ }
110
+ with self._lock:
111
+ self._items.append(item)
112
+ self._save()
113
+ return self._public_item(item), raw_key
114
+
115
+ def update_key(
116
+ self,
117
+ key_id: str,
118
+ updates: dict[str, object],
119
+ *,
120
+ role: AuthRole | None = None,
121
+ ) -> dict[str, object] | None:
122
+ normalized_id = self._clean(key_id)
123
+ if not normalized_id:
124
+ return None
125
+ with self._lock:
126
+ for index, item in enumerate(self._items):
127
+ if item.get("id") != normalized_id:
128
+ continue
129
+ if role is not None and item.get("role") != role:
130
+ return None
131
+ next_item = dict(item)
132
+ if "name" in updates and updates.get("name") is not None:
133
+ next_item["name"] = self._clean(updates.get("name")) or next_item.get("name") or "普通用户"
134
+ if "enabled" in updates and updates.get("enabled") is not None:
135
+ next_item["enabled"] = bool(updates.get("enabled"))
136
+ self._items[index] = next_item
137
+ self._save()
138
+ return self._public_item(next_item)
139
+ return None
140
+
141
+ def delete_key(self, key_id: str, *, role: AuthRole | None = None) -> bool:
142
+ normalized_id = self._clean(key_id)
143
+ if not normalized_id:
144
+ return False
145
+ with self._lock:
146
+ before = len(self._items)
147
+ self._items = [
148
+ item
149
+ for item in self._items
150
+ if not (item.get("id") == normalized_id and (role is None or item.get("role") == role))
151
+ ]
152
+ if len(self._items) == before:
153
+ return False
154
+ self._save()
155
+ return True
156
+
157
+ def authenticate(self, raw_key: str) -> dict[str, object] | None:
158
+ candidate = self._clean(raw_key)
159
+ if not candidate:
160
+ return None
161
+ candidate_hash = _hash_key(candidate)
162
+ with self._lock:
163
+ for index, item in enumerate(self._items):
164
+ if not bool(item.get("enabled", True)):
165
+ continue
166
+ stored_hash = self._clean(item.get("key_hash"))
167
+ if not stored_hash or not hmac.compare_digest(stored_hash, candidate_hash):
168
+ continue
169
+ next_item = dict(item)
170
+ next_item["last_used_at"] = _now_iso()
171
+ self._items[index] = next_item
172
+ self._save()
173
+ return self._public_item(next_item)
174
+ return None
175
+
176
+
177
+ auth_service = AuthService(AUTH_KEYS_FILE)
services/config.py CHANGED
@@ -125,7 +125,9 @@ class ConfigStore:
125
  return value or "0.0.0"
126
 
127
  def get(self) -> dict[str, object]:
128
- return dict(self.data)
 
 
129
 
130
  def get_proxy_settings(self) -> str:
131
  return str(self.data.get("proxy") or "").strip()
@@ -133,8 +135,6 @@ class ConfigStore:
133
  def update(self, data: dict[str, object]) -> dict[str, object]:
134
  next_data = dict(self.data)
135
  next_data.update(dict(data or {}))
136
- if _is_invalid_auth_key(next_data.get("auth-key")):
137
- next_data["auth-key"] = self.data.get("auth-key") or os.getenv("CHATGPT2API_AUTH_KEY") or ""
138
  self.data = next_data
139
  self._save()
140
  return self.get()
 
125
  return value or "0.0.0"
126
 
127
  def get(self) -> dict[str, object]:
128
+ data = dict(self.data)
129
+ data.pop("auth-key", None)
130
+ return data
131
 
132
  def get_proxy_settings(self) -> str:
133
  return str(self.data.get("proxy") or "").strip()
 
135
  def update(self, data: dict[str, object]) -> dict[str, object]:
136
  next_data = dict(self.data)
137
  next_data.update(dict(data or {}))
 
 
138
  self.data = next_data
139
  self._save()
140
  return self.get()
test/test_account_image_capabilities.py CHANGED
@@ -8,6 +8,7 @@ from pathlib import Path
8
  os.environ.setdefault("CHATGPT2API_AUTH_KEY", "test-auth")
9
 
10
  from services.account_service import AccountService
 
11
  from utils.helper import anonymize_token
12
 
13
 
@@ -74,5 +75,33 @@ class TokenLogTests(unittest.TestCase):
74
  self.assertNotIn(token, token_ref)
75
 
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  if __name__ == "__main__":
78
  unittest.main()
 
8
  os.environ.setdefault("CHATGPT2API_AUTH_KEY", "test-auth")
9
 
10
  from services.account_service import AccountService
11
+ from services.auth_service import AuthService
12
  from utils.helper import anonymize_token
13
 
14
 
 
75
  self.assertNotIn(token, token_ref)
76
 
77
 
78
+ class AuthServiceTests(unittest.TestCase):
79
+ def test_create_authenticate_disable_and_delete_user_key(self) -> None:
80
+ with tempfile.TemporaryDirectory() as tmp_dir:
81
+ service = AuthService(Path(tmp_dir) / "auth_keys.json")
82
+
83
+ item, raw_key = service.create_key(role="user", name="Alice")
84
+
85
+ self.assertEqual(item["role"], "user")
86
+ self.assertEqual(item["name"], "Alice")
87
+ self.assertTrue(item["enabled"])
88
+ self.assertTrue(raw_key.startswith("cg2a_user_"))
89
+
90
+ authed = service.authenticate(raw_key)
91
+ self.assertIsNotNone(authed)
92
+ self.assertEqual(authed["id"], item["id"])
93
+ self.assertEqual(authed["role"], "user")
94
+ self.assertIsNotNone(authed["last_used_at"])
95
+
96
+ updated = service.update_key(item["id"], {"enabled": False}, role="user")
97
+ self.assertIsNotNone(updated)
98
+ self.assertFalse(updated["enabled"])
99
+ self.assertIsNone(service.authenticate(raw_key))
100
+
101
+ self.assertTrue(service.delete_key(item["id"], role="user"))
102
+ self.assertFalse(service.delete_key(item["id"], role="user"))
103
+ self.assertEqual(service.list_keys(role="user"), [])
104
+
105
+
106
  if __name__ == "__main__":
107
  unittest.main()
uv.lock CHANGED
@@ -160,6 +160,11 @@ dependencies = [
160
  { name = "uvicorn" },
161
  ]
162
 
 
 
 
 
 
163
  [package.metadata]
164
  requires-dist = [
165
  { name = "curl-cffi", specifier = ">=0.15.0" },
@@ -174,6 +179,9 @@ requires-dist = [
174
  { name = "uvicorn", specifier = ">=0.44.0" },
175
  ]
176
 
 
 
 
177
  [[package]]
178
  name = "click"
179
  version = "8.3.2"
@@ -314,6 +322,34 @@ wheels = [
314
  { url = "https://mirrors.aliyun.com/pypi/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86" },
315
  ]
316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
  [[package]]
318
  name = "idna"
319
  version = "3.11"
 
160
  { name = "uvicorn" },
161
  ]
162
 
163
+ [package.dev-dependencies]
164
+ dev = [
165
+ { name = "httpx" },
166
+ ]
167
+
168
  [package.metadata]
169
  requires-dist = [
170
  { name = "curl-cffi", specifier = ">=0.15.0" },
 
179
  { name = "uvicorn", specifier = ">=0.44.0" },
180
  ]
181
 
182
+ [package.metadata.requires-dev]
183
+ dev = [{ name = "httpx", specifier = ">=0.28.1" }]
184
+
185
  [[package]]
186
  name = "click"
187
  version = "8.3.2"
 
322
  { url = "https://mirrors.aliyun.com/pypi/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86" },
323
  ]
324
 
325
+ [[package]]
326
+ name = "httpcore"
327
+ version = "1.0.9"
328
+ source = { registry = "https://pypi.org/simple" }
329
+ dependencies = [
330
+ { name = "certifi" },
331
+ { name = "h11" },
332
+ ]
333
+ sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" }
334
+ wheels = [
335
+ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" },
336
+ ]
337
+
338
+ [[package]]
339
+ name = "httpx"
340
+ version = "0.28.1"
341
+ source = { registry = "https://pypi.org/simple" }
342
+ dependencies = [
343
+ { name = "anyio" },
344
+ { name = "certifi" },
345
+ { name = "httpcore" },
346
+ { name = "idna" },
347
+ ]
348
+ sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" }
349
+ wheels = [
350
+ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" },
351
+ ]
352
+
353
  [[package]]
354
  name = "idna"
355
  version = "3.11"
web/src/app/accounts/page.tsx CHANGED
@@ -49,6 +49,7 @@ import {
49
  type AccountStatus,
50
  type AccountType,
51
  } from "@/lib/api";
 
52
  import { cn } from "@/lib/utils";
53
 
54
  import { AccountImportDialog } from "./components/account-import-dialog";
@@ -179,7 +180,7 @@ function normalizeAccounts(items: Account[]): Account[] {
179
  }));
180
  }
181
 
182
- export default function AccountsPage() {
183
  const didLoadRef = useRef(false);
184
  const [accounts, setAccounts] = useState<Account[]>([]);
185
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
@@ -843,3 +844,17 @@ export default function AccountsPage() {
843
  </>
844
  );
845
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  type AccountStatus,
50
  type AccountType,
51
  } from "@/lib/api";
52
+ import { useAuthGuard } from "@/lib/use-auth-guard";
53
  import { cn } from "@/lib/utils";
54
 
55
  import { AccountImportDialog } from "./components/account-import-dialog";
 
180
  }));
181
  }
182
 
183
+ function AccountsPageContent() {
184
  const didLoadRef = useRef(false);
185
  const [accounts, setAccounts] = useState<Account[]>([]);
186
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
 
844
  </>
845
  );
846
  }
847
+
848
+ export default function AccountsPage() {
849
+ const { isCheckingAuth, session } = useAuthGuard(["admin"]);
850
+
851
+ if (isCheckingAuth || !session || session.role !== "admin") {
852
+ return (
853
+ <div className="flex min-h-[40vh] items-center justify-center">
854
+ <LoaderCircle className="size-5 animate-spin text-stone-400" />
855
+ </div>
856
+ );
857
+ }
858
+
859
+ return <AccountsPageContent />;
860
+ }
web/src/app/image/page.tsx CHANGED
@@ -1,7 +1,7 @@
1
  "use client";
2
 
3
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
- import { History, Plus, Trash2 } from "lucide-react";
5
  import { toast } from "sonner";
6
 
7
  import { ImageComposer } from "@/app/image/components/image-composer";
@@ -16,6 +16,7 @@ import {
16
  } from "@/components/ui/dialog";
17
  import { Button } from "@/components/ui/button";
18
  import { editImage, fetchAccounts, generateImage, type Account } from "@/lib/api";
 
19
  import {
20
  clearImageConversations,
21
  deleteImageConversation,
@@ -170,7 +171,7 @@ async function recoverConversationHistory(items: ImageConversation[]) {
170
  return normalized;
171
  }
172
 
173
- export default function ImagePage() {
174
  const didLoadQuotaRef = useRef(false);
175
  const conversationsRef = useRef<ImageConversation[]>([]);
176
  const resultsViewportRef = useRef<HTMLDivElement>(null);
@@ -250,13 +251,17 @@ export default function ImagePage() {
250
  }, []);
251
 
252
  const loadQuota = useCallback(async () => {
 
 
 
 
253
  try {
254
  const data = await fetchAccounts();
255
  setAvailableQuota(formatAvailableQuota(data.items));
256
  } catch {
257
  setAvailableQuota((prev) => (prev === "加载中..." ? "--" : prev));
258
  }
259
- }, []);
260
 
261
  useEffect(() => {
262
  if (didLoadQuotaRef.current) {
@@ -273,7 +278,7 @@ export default function ImagePage() {
273
  return () => {
274
  window.removeEventListener("focus", handleFocus);
275
  };
276
- }, [loadQuota]);
277
 
278
  useEffect(() => {
279
  if (!selectedConversation) {
@@ -484,6 +489,7 @@ export default function ImagePage() {
484
  setLightboxOpen(true);
485
  }, []);
486
 
 
487
  const runConversationQueue = useCallback(
488
  async (conversationId: string) => {
489
  if (activeConversationQueueIds.has(conversationId)) {
@@ -680,6 +686,7 @@ export default function ImagePage() {
680
  },
681
  [loadQuota, updateConversation],
682
  );
 
683
 
684
  useEffect(() => {
685
  for (const conversation of conversations) {
@@ -873,3 +880,17 @@ export default function ImagePage() {
873
  </>
874
  );
875
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  "use client";
2
 
3
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
+ import { History, LoaderCircle, Plus, Trash2 } from "lucide-react";
5
  import { toast } from "sonner";
6
 
7
  import { ImageComposer } from "@/app/image/components/image-composer";
 
16
  } from "@/components/ui/dialog";
17
  import { Button } from "@/components/ui/button";
18
  import { editImage, fetchAccounts, generateImage, type Account } from "@/lib/api";
19
+ import { useAuthGuard } from "@/lib/use-auth-guard";
20
  import {
21
  clearImageConversations,
22
  deleteImageConversation,
 
171
  return normalized;
172
  }
173
 
174
+ function ImagePageContent({ isAdmin }: { isAdmin: boolean }) {
175
  const didLoadQuotaRef = useRef(false);
176
  const conversationsRef = useRef<ImageConversation[]>([]);
177
  const resultsViewportRef = useRef<HTMLDivElement>(null);
 
251
  }, []);
252
 
253
  const loadQuota = useCallback(async () => {
254
+ if (!isAdmin) {
255
+ setAvailableQuota("--");
256
+ return;
257
+ }
258
  try {
259
  const data = await fetchAccounts();
260
  setAvailableQuota(formatAvailableQuota(data.items));
261
  } catch {
262
  setAvailableQuota((prev) => (prev === "加载中..." ? "--" : prev));
263
  }
264
+ }, [isAdmin]);
265
 
266
  useEffect(() => {
267
  if (didLoadQuotaRef.current) {
 
278
  return () => {
279
  window.removeEventListener("focus", handleFocus);
280
  };
281
+ }, [isAdmin, loadQuota]);
282
 
283
  useEffect(() => {
284
  if (!selectedConversation) {
 
489
  setLightboxOpen(true);
490
  }, []);
491
 
492
+ /* eslint-disable react-hooks/preserve-manual-memoization */
493
  const runConversationQueue = useCallback(
494
  async (conversationId: string) => {
495
  if (activeConversationQueueIds.has(conversationId)) {
 
686
  },
687
  [loadQuota, updateConversation],
688
  );
689
+ /* eslint-enable react-hooks/preserve-manual-memoization */
690
 
691
  useEffect(() => {
692
  for (const conversation of conversations) {
 
880
  </>
881
  );
882
  }
883
+
884
+ export default function ImagePage() {
885
+ const { isCheckingAuth, session } = useAuthGuard();
886
+
887
+ if (isCheckingAuth || !session) {
888
+ return (
889
+ <div className="flex min-h-[40vh] items-center justify-center">
890
+ <LoaderCircle className="size-5 animate-spin text-stone-400" />
891
+ </div>
892
+ );
893
+ }
894
+
895
+ return <ImagePageContent isAdmin={session.role === "admin"} />;
896
+ }
web/src/app/login/page.tsx CHANGED
@@ -9,12 +9,14 @@ import { Button } from "@/components/ui/button";
9
  import { Card, CardContent } from "@/components/ui/card";
10
  import { Input } from "@/components/ui/input";
11
  import { login } from "@/lib/api";
12
- import { setStoredAuthKey } from "@/store/auth";
 
13
 
14
  export default function LoginPage() {
15
  const router = useRouter();
16
  const [authKey, setAuthKey] = useState("");
17
  const [isSubmitting, setIsSubmitting] = useState(false);
 
18
 
19
  const handleLogin = async () => {
20
  const normalizedAuthKey = authKey.trim();
@@ -25,9 +27,14 @@ export default function LoginPage() {
25
 
26
  setIsSubmitting(true);
27
  try {
28
- await login(normalizedAuthKey);
29
- await setStoredAuthKey(normalizedAuthKey);
30
- router.replace("/accounts");
 
 
 
 
 
31
  } catch (error) {
32
  const message = error instanceof Error ? error.message : "登录失败";
33
  toast.error(message);
@@ -36,6 +43,14 @@ export default function LoginPage() {
36
  }
37
  };
38
 
 
 
 
 
 
 
 
 
39
  return (
40
  <div className="grid min-h-[calc(100vh-1rem)] w-full place-items-center px-4 py-6">
41
  <Card className="w-full max-w-[505px] rounded-[30px] border-white/80 bg-white/95 shadow-[0_28px_90px_rgba(28,25,23,0.10)]">
 
9
  import { Card, CardContent } from "@/components/ui/card";
10
  import { Input } from "@/components/ui/input";
11
  import { login } from "@/lib/api";
12
+ import { useRedirectIfAuthenticated } from "@/lib/use-auth-guard";
13
+ import { getDefaultRouteForRole, setStoredAuthSession } from "@/store/auth";
14
 
15
  export default function LoginPage() {
16
  const router = useRouter();
17
  const [authKey, setAuthKey] = useState("");
18
  const [isSubmitting, setIsSubmitting] = useState(false);
19
+ const { isCheckingAuth } = useRedirectIfAuthenticated();
20
 
21
  const handleLogin = async () => {
22
  const normalizedAuthKey = authKey.trim();
 
27
 
28
  setIsSubmitting(true);
29
  try {
30
+ const data = await login(normalizedAuthKey);
31
+ await setStoredAuthSession({
32
+ key: normalizedAuthKey,
33
+ role: data.role,
34
+ subjectId: data.subject_id,
35
+ name: data.name,
36
+ });
37
+ router.replace(getDefaultRouteForRole(data.role));
38
  } catch (error) {
39
  const message = error instanceof Error ? error.message : "登录失败";
40
  toast.error(message);
 
43
  }
44
  };
45
 
46
+ if (isCheckingAuth) {
47
+ return (
48
+ <div className="grid min-h-[calc(100vh-1rem)] w-full place-items-center px-4 py-6">
49
+ <LoaderCircle className="size-5 animate-spin text-stone-400" />
50
+ </div>
51
+ );
52
+ }
53
+
54
  return (
55
  <div className="grid min-h-[calc(100vh-1rem)] w-full place-items-center px-4 py-6">
56
  <Card className="w-full max-w-[505px] rounded-[30px] border-white/80 bg-white/95 shadow-[0_28px_90px_rgba(28,25,23,0.10)]">
web/src/app/page.tsx CHANGED
@@ -3,11 +3,26 @@
3
  import { useEffect } from "react";
4
  import { useRouter } from "next/navigation";
5
 
 
 
6
  export default function HomePage() {
7
  const router = useRouter();
8
 
9
  useEffect(() => {
10
- router.replace("/accounts");
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  }, [router]);
12
 
13
  return null;
 
3
  import { useEffect } from "react";
4
  import { useRouter } from "next/navigation";
5
 
6
+ import { getDefaultRouteForRole, getStoredAuthSession } from "@/store/auth";
7
+
8
  export default function HomePage() {
9
  const router = useRouter();
10
 
11
  useEffect(() => {
12
+ let active = true;
13
+
14
+ const redirect = async () => {
15
+ const session = await getStoredAuthSession();
16
+ if (!active) {
17
+ return;
18
+ }
19
+ router.replace(session ? getDefaultRouteForRole(session.role) : "/login");
20
+ };
21
+
22
+ void redirect();
23
+ return () => {
24
+ active = false;
25
+ };
26
  }, [router]);
27
 
28
  return null;
web/src/app/settings/components/config-card.tsx CHANGED
@@ -17,7 +17,6 @@ export function ConfigCard() {
17
  const config = useSettingsStore((state) => state.config);
18
  const isLoadingConfig = useSettingsStore((state) => state.isLoadingConfig);
19
  const isSavingConfig = useSettingsStore((state) => state.isSavingConfig);
20
- const setAuthKey = useSettingsStore((state) => state.setAuthKey);
21
  const setRefreshAccountIntervalMinute = useSettingsStore((state) => state.setRefreshAccountIntervalMinute);
22
  const setProxy = useSettingsStore((state) => state.setProxy);
23
  const setBaseUrl = useSettingsStore((state) => state.setBaseUrl);
@@ -59,17 +58,10 @@ export function ConfigCard() {
59
  return (
60
  <Card className="rounded-2xl border-white/80 bg-white/90 shadow-sm">
61
  <CardContent className="space-y-4 p-6">
 
 
 
62
  <div className="grid gap-4 md:grid-cols-2">
63
- <div className="space-y-2">
64
- <label className="text-sm text-stone-700">登录密钥</label>
65
- <Input
66
- value={String(config?.["auth-key"] || "")}
67
- onChange={(event) => setAuthKey(event.target.value)}
68
- placeholder="auth-key"
69
- className="h-10 rounded-xl border-stone-200 bg-white"
70
- />
71
- <p className="text-xs text-stone-500">用于后台登录验证。</p>
72
- </div>
73
  <div className="space-y-2">
74
  <label className="text-sm text-stone-700">账号刷新间隔</label>
75
  <Input
 
17
  const config = useSettingsStore((state) => state.config);
18
  const isLoadingConfig = useSettingsStore((state) => state.isLoadingConfig);
19
  const isSavingConfig = useSettingsStore((state) => state.isSavingConfig);
 
20
  const setRefreshAccountIntervalMinute = useSettingsStore((state) => state.setRefreshAccountIntervalMinute);
21
  const setProxy = useSettingsStore((state) => state.setProxy);
22
  const setBaseUrl = useSettingsStore((state) => state.setBaseUrl);
 
58
  return (
59
  <Card className="rounded-2xl border-white/80 bg-white/90 shadow-sm">
60
  <CardContent className="space-y-4 p-6">
61
+ <div className="rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 text-sm leading-6 text-stone-600">
62
+ 管理员登录密钥继续从部署配置读取,不再在此页面展示;如需分发给其他人,请在下方创建普通用户密钥。
63
+ </div>
64
  <div className="grid gap-4 md:grid-cols-2">
 
 
 
 
 
 
 
 
 
 
65
  <div className="space-y-2">
66
  <label className="text-sm text-stone-700">账号刷新间隔</label>
67
  <Input
web/src/app/settings/components/user-keys-card.tsx ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useEffect, useRef, useState } from "react";
4
+ import { Ban, CheckCircle2, Copy, KeyRound, LoaderCircle, Plus, Trash2 } from "lucide-react";
5
+ import { toast } from "sonner";
6
+
7
+ import { Badge } from "@/components/ui/badge";
8
+ import { Button } from "@/components/ui/button";
9
+ import { Card, CardContent } from "@/components/ui/card";
10
+ import {
11
+ Dialog,
12
+ DialogContent,
13
+ DialogDescription,
14
+ DialogFooter,
15
+ DialogHeader,
16
+ DialogTitle,
17
+ } from "@/components/ui/dialog";
18
+ import { Input } from "@/components/ui/input";
19
+ import { createUserKey, deleteUserKey, fetchUserKeys, updateUserKey, type UserKey } from "@/lib/api";
20
+
21
+ function formatDateTime(value?: string | null) {
22
+ if (!value) {
23
+ return "—";
24
+ }
25
+ const date = new Date(value);
26
+ if (Number.isNaN(date.getTime())) {
27
+ return value;
28
+ }
29
+ return new Intl.DateTimeFormat("zh-CN", {
30
+ year: "numeric",
31
+ month: "2-digit",
32
+ day: "2-digit",
33
+ hour: "2-digit",
34
+ minute: "2-digit",
35
+ }).format(date);
36
+ }
37
+
38
+ export function UserKeysCard() {
39
+ const didLoadRef = useRef(false);
40
+ const [items, setItems] = useState<UserKey[]>([]);
41
+ const [isLoading, setIsLoading] = useState(true);
42
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
43
+ const [name, setName] = useState("");
44
+ const [isCreating, setIsCreating] = useState(false);
45
+ const [pendingId, setPendingId] = useState<string | null>(null);
46
+ const [revealedKey, setRevealedKey] = useState("");
47
+
48
+ const load = async () => {
49
+ setIsLoading(true);
50
+ try {
51
+ const data = await fetchUserKeys();
52
+ setItems(data.items);
53
+ } catch (error) {
54
+ toast.error(error instanceof Error ? error.message : "加载用户密钥失败");
55
+ } finally {
56
+ setIsLoading(false);
57
+ }
58
+ };
59
+
60
+ useEffect(() => {
61
+ if (didLoadRef.current) {
62
+ return;
63
+ }
64
+ didLoadRef.current = true;
65
+ void load();
66
+ }, []);
67
+
68
+ const handleCreate = async () => {
69
+ setIsCreating(true);
70
+ try {
71
+ const data = await createUserKey(name.trim());
72
+ setItems(data.items);
73
+ setRevealedKey(data.key);
74
+ setName("");
75
+ setIsDialogOpen(false);
76
+ toast.success("用户密钥已创建");
77
+ } catch (error) {
78
+ toast.error(error instanceof Error ? error.message : "创建用户密钥失败");
79
+ } finally {
80
+ setIsCreating(false);
81
+ }
82
+ };
83
+
84
+ const handleToggle = async (item: UserKey) => {
85
+ setPendingId(item.id);
86
+ try {
87
+ const data = await updateUserKey(item.id, { enabled: !item.enabled });
88
+ setItems(data.items);
89
+ toast.success(item.enabled ? "用户密钥已禁用" : "用户密钥已启用");
90
+ } catch (error) {
91
+ toast.error(error instanceof Error ? error.message : "更新用户密钥失败");
92
+ } finally {
93
+ setPendingId(null);
94
+ }
95
+ };
96
+
97
+ const handleDelete = async (item: UserKey) => {
98
+ if (!window.confirm(`确认删除用户密钥「${item.name}」吗?`)) {
99
+ return;
100
+ }
101
+ setPendingId(item.id);
102
+ try {
103
+ const data = await deleteUserKey(item.id);
104
+ setItems(data.items);
105
+ toast.success("用户密钥已删除");
106
+ } catch (error) {
107
+ toast.error(error instanceof Error ? error.message : "删除用户密钥失败");
108
+ } finally {
109
+ setPendingId(null);
110
+ }
111
+ };
112
+
113
+ const handleCopy = async (value: string) => {
114
+ try {
115
+ await navigator.clipboard.writeText(value);
116
+ toast.success("已复制到剪贴板");
117
+ } catch {
118
+ toast.error("复制失败,请手动复制");
119
+ }
120
+ };
121
+
122
+ return (
123
+ <>
124
+ <Card className="rounded-2xl border-white/80 bg-white/90 shadow-sm">
125
+ <CardContent className="space-y-6 p-6">
126
+ <div className="flex items-start justify-between gap-4">
127
+ <div className="flex items-center gap-3">
128
+ <div className="flex size-10 items-center justify-center rounded-xl bg-stone-100">
129
+ <KeyRound className="size-5 text-stone-600" />
130
+ </div>
131
+ <div>
132
+ <h2 className="text-lg font-semibold tracking-tight">用户密钥管理</h2>
133
+ <p className="text-sm text-stone-500">为普通用户创建专用密钥;普通用户只能进入画图页,不能查看设置和号池。</p>
134
+ </div>
135
+ </div>
136
+ <Button className="h-9 rounded-xl bg-stone-950 px-4 text-white hover:bg-stone-800" onClick={() => setIsDialogOpen(true)}>
137
+ <Plus className="size-4" />
138
+ 创建用户密钥
139
+ </Button>
140
+ </div>
141
+
142
+ {revealedKey ? (
143
+ <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-4 text-sm text-emerald-900">
144
+ <div className="font-medium">新密钥仅展示一次,请立即保存:</div>
145
+ <div className="mt-3 flex flex-col gap-3 rounded-lg border border-emerald-200 bg-white/80 p-3 md:flex-row md:items-center md:justify-between">
146
+ <code className="break-all font-mono text-[13px]">{revealedKey}</code>
147
+ <Button
148
+ type="button"
149
+ variant="outline"
150
+ className="h-9 rounded-xl border-emerald-200 bg-white px-4 text-emerald-700"
151
+ onClick={() => void handleCopy(revealedKey)}
152
+ >
153
+ <Copy className="size-4" />
154
+ 复制
155
+ </Button>
156
+ </div>
157
+ </div>
158
+ ) : null}
159
+
160
+ {isLoading ? (
161
+ <div className="flex items-center justify-center py-10">
162
+ <LoaderCircle className="size-5 animate-spin text-stone-400" />
163
+ </div>
164
+ ) : items.length === 0 ? (
165
+ <div className="rounded-xl bg-stone-50 px-6 py-10 text-center text-sm text-stone-500">
166
+ 暂无普通用户密钥。点击右上角按钮后即可创建并分发给其他人。
167
+ </div>
168
+ ) : (
169
+ <div className="space-y-3">
170
+ {items.map((item) => {
171
+ const isPending = pendingId === item.id;
172
+ return (
173
+ <div key={item.id} className="flex flex-col gap-3 rounded-xl border border-stone-200 bg-white px-4 py-4 md:flex-row md:items-center md:justify-between">
174
+ <div className="min-w-0 space-y-2">
175
+ <div className="flex flex-wrap items-center gap-2">
176
+ <div className="truncate text-sm font-medium text-stone-800">{item.name}</div>
177
+ <Badge variant={item.enabled ? "success" : "secondary"} className="rounded-md">
178
+ {item.enabled ? "已启用" : "已禁用"}
179
+ </Badge>
180
+ </div>
181
+ <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-stone-500">
182
+ <span>创建时间 {formatDateTime(item.created_at)}</span>
183
+ <span>最近使用 {formatDateTime(item.last_used_at)}</span>
184
+ </div>
185
+ </div>
186
+
187
+ <div className="flex items-center gap-2">
188
+ <Button
189
+ type="button"
190
+ variant="outline"
191
+ className="h-9 rounded-xl border-stone-200 bg-white px-4 text-stone-700"
192
+ onClick={() => void handleToggle(item)}
193
+ disabled={isPending}
194
+ >
195
+ {isPending ? (
196
+ <LoaderCircle className="size-4 animate-spin" />
197
+ ) : item.enabled ? (
198
+ <Ban className="size-4" />
199
+ ) : (
200
+ <CheckCircle2 className="size-4" />
201
+ )}
202
+ {item.enabled ? "禁用" : "启用"}
203
+ </Button>
204
+ <Button
205
+ type="button"
206
+ variant="outline"
207
+ className="h-9 rounded-xl border-rose-200 bg-white px-4 text-rose-600 hover:bg-rose-50 hover:text-rose-700"
208
+ onClick={() => void handleDelete(item)}
209
+ disabled={isPending}
210
+ >
211
+ {isPending ? <LoaderCircle className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
212
+ 删除
213
+ </Button>
214
+ </div>
215
+ </div>
216
+ );
217
+ })}
218
+ </div>
219
+ )}
220
+ </CardContent>
221
+ </Card>
222
+
223
+ <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
224
+ <DialogContent className="rounded-2xl p-6">
225
+ <DialogHeader className="gap-2">
226
+ <DialogTitle>创建用户密钥</DialogTitle>
227
+ <DialogDescription className="text-sm leading-6">
228
+ 可选填写一个备注名称,方便区分不同使用者;创建后会生成一条只能查看一次的原始密钥。
229
+ </DialogDescription>
230
+ </DialogHeader>
231
+ <div className="space-y-2">
232
+ <label className="text-sm font-medium text-stone-700">名称(可选)</label>
233
+ <Input
234
+ value={name}
235
+ onChange={(event) => setName(event.target.value)}
236
+ placeholder="例如:设计同学 A、运营临时账号"
237
+ className="h-11 rounded-xl border-stone-200 bg-white"
238
+ />
239
+ </div>
240
+ <DialogFooter>
241
+ <Button
242
+ type="button"
243
+ variant="secondary"
244
+ className="h-10 rounded-xl bg-stone-100 px-5 text-stone-700 hover:bg-stone-200"
245
+ onClick={() => setIsDialogOpen(false)}
246
+ disabled={isCreating}
247
+ >
248
+ 取消
249
+ </Button>
250
+ <Button
251
+ type="button"
252
+ className="h-10 rounded-xl bg-stone-950 px-5 text-white hover:bg-stone-800"
253
+ onClick={() => void handleCreate()}
254
+ disabled={isCreating}
255
+ >
256
+ {isCreating ? <LoaderCircle className="size-4 animate-spin" /> : <Plus className="size-4" />}
257
+ 创建
258
+ </Button>
259
+ </DialogFooter>
260
+ </DialogContent>
261
+ </Dialog>
262
+ </>
263
+ );
264
+ }
web/src/app/settings/page.tsx CHANGED
@@ -1,6 +1,9 @@
1
  "use client";
2
 
3
  import { useEffect, useRef } from "react";
 
 
 
4
 
5
  import { ConfigCard } from "./components/config-card";
6
  import { CPAPoolDialog } from "./components/cpa-pool-dialog";
@@ -8,6 +11,7 @@ import { CPAPoolsCard } from "./components/cpa-pools-card";
8
  import { ImportBrowserDialog } from "./components/import-browser-dialog";
9
  import { SettingsHeader } from "./components/settings-header";
10
  import { Sub2APIConnections } from "./components/sub2api-connections";
 
11
  import { useSettingsStore } from "./store";
12
 
13
  function SettingsDataController() {
@@ -42,13 +46,14 @@ function SettingsDataController() {
42
  return null;
43
  }
44
 
45
- export default function SettingsPage() {
46
  return (
47
  <>
48
  <SettingsDataController />
49
  <SettingsHeader />
50
  <section className="space-y-6">
51
  <ConfigCard />
 
52
  <CPAPoolsCard />
53
  <Sub2APIConnections />
54
  </section>
@@ -57,3 +62,17 @@ export default function SettingsPage() {
57
  </>
58
  );
59
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  "use client";
2
 
3
  import { useEffect, useRef } from "react";
4
+ import { LoaderCircle } from "lucide-react";
5
+
6
+ import { useAuthGuard } from "@/lib/use-auth-guard";
7
 
8
  import { ConfigCard } from "./components/config-card";
9
  import { CPAPoolDialog } from "./components/cpa-pool-dialog";
 
11
  import { ImportBrowserDialog } from "./components/import-browser-dialog";
12
  import { SettingsHeader } from "./components/settings-header";
13
  import { Sub2APIConnections } from "./components/sub2api-connections";
14
+ import { UserKeysCard } from "./components/user-keys-card";
15
  import { useSettingsStore } from "./store";
16
 
17
  function SettingsDataController() {
 
46
  return null;
47
  }
48
 
49
+ function SettingsPageContent() {
50
  return (
51
  <>
52
  <SettingsDataController />
53
  <SettingsHeader />
54
  <section className="space-y-6">
55
  <ConfigCard />
56
+ <UserKeysCard />
57
  <CPAPoolsCard />
58
  <Sub2APIConnections />
59
  </section>
 
62
  </>
63
  );
64
  }
65
+
66
+ export default function SettingsPage() {
67
+ const { isCheckingAuth, session } = useAuthGuard(["admin"]);
68
+
69
+ if (isCheckingAuth || !session || session.role !== "admin") {
70
+ return (
71
+ <div className="flex min-h-[40vh] items-center justify-center">
72
+ <LoaderCircle className="size-5 animate-spin text-stone-400" />
73
+ </div>
74
+ );
75
+ }
76
+
77
+ return <SettingsPageContent />;
78
+ }
web/src/app/settings/store.ts CHANGED
@@ -24,7 +24,6 @@ export type PageSizeOption = (typeof PAGE_SIZE_OPTIONS)[number];
24
  function normalizeConfig(config: SettingsConfig): SettingsConfig {
25
  return {
26
  ...config,
27
- "auth-key": typeof config["auth-key"] === "string" ? config["auth-key"] : "",
28
  refresh_account_interval_minute: Number(config.refresh_account_interval_minute || 5),
29
  proxy: typeof config.proxy === "string" ? config.proxy : "",
30
  base_url: typeof config.base_url === "string" ? config.base_url : "",
@@ -78,7 +77,6 @@ type SettingsStore = {
78
  initialize: () => Promise<void>;
79
  loadConfig: () => Promise<void>;
80
  saveConfig: () => Promise<void>;
81
- setAuthKey: (value: string) => void;
82
  setRefreshAccountIntervalMinute: (value: string) => void;
83
  setProxy: (value: string) => void;
84
  setBaseUrl: (value: string) => void;
@@ -159,7 +157,6 @@ export const useSettingsStore = create<SettingsStore>((set, get) => ({
159
  try {
160
  const data = await updateSettingsConfig({
161
  ...config,
162
- "auth-key": String(config["auth-key"] || "").trim(),
163
  refresh_account_interval_minute: Math.max(1, Number(config.refresh_account_interval_minute) || 1),
164
  proxy: config.proxy.trim(),
165
  base_url: String(config.base_url || "").trim(),
@@ -175,20 +172,6 @@ export const useSettingsStore = create<SettingsStore>((set, get) => ({
175
  }
176
  },
177
 
178
- setAuthKey: (value) => {
179
- set((state) => {
180
- if (!state.config) {
181
- return {};
182
- }
183
- return {
184
- config: {
185
- ...state.config,
186
- "auth-key": value,
187
- },
188
- };
189
- });
190
- },
191
-
192
  setRefreshAccountIntervalMinute: (value) => {
193
  set((state) => {
194
  if (!state.config) {
 
24
  function normalizeConfig(config: SettingsConfig): SettingsConfig {
25
  return {
26
  ...config,
 
27
  refresh_account_interval_minute: Number(config.refresh_account_interval_minute || 5),
28
  proxy: typeof config.proxy === "string" ? config.proxy : "",
29
  base_url: typeof config.base_url === "string" ? config.base_url : "",
 
77
  initialize: () => Promise<void>;
78
  loadConfig: () => Promise<void>;
79
  saveConfig: () => Promise<void>;
 
80
  setRefreshAccountIntervalMinute: (value: string) => void;
81
  setProxy: (value: string) => void;
82
  setBaseUrl: (value: string) => void;
 
157
  try {
158
  const data = await updateSettingsConfig({
159
  ...config,
 
160
  refresh_account_interval_minute: Math.max(1, Number(config.refresh_account_interval_minute) || 1),
161
  proxy: config.proxy.trim(),
162
  base_url: String(config.base_url || "").trim(),
 
172
  }
173
  },
174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  setRefreshAccountIntervalMinute: (value) => {
176
  set((state) => {
177
  if (!state.config) {
web/src/components/top-nav.tsx CHANGED
@@ -1,32 +1,64 @@
1
  "use client";
2
 
3
  import Link from "next/link";
 
4
  import { Github } from "lucide-react";
5
  import { usePathname, useRouter } from "next/navigation";
6
 
7
  import webConfig from "@/constants/common-env";
8
- import { clearStoredAuthKey } from "@/store/auth";
9
  import { cn } from "@/lib/utils";
10
 
11
- const navItems = [
12
  { href: "/image", label: "画图" },
13
  { href: "/accounts", label: "号池管理" },
14
  { href: "/settings", label: "设置" },
15
  ];
16
 
 
 
17
  export function TopNav() {
18
  const pathname = usePathname();
19
  const router = useRouter();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  const handleLogout = async () => {
22
- await clearStoredAuthKey();
23
  router.replace("/login");
24
  };
25
 
26
- if (pathname === "/login") {
27
  return null;
28
  }
29
 
 
 
 
30
  return (
31
  <header className="border-b border-stone-100/50">
32
  <div className="flex h-12 items-center justify-between px-3 sm:px-6">
@@ -67,6 +99,9 @@ export function TopNav() {
67
  })}
68
  </div>
69
  <div className="flex items-center justify-end gap-2 sm:gap-3">
 
 
 
70
  <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]">
71
  v{webConfig.appVersion}
72
  </span>
 
1
  "use client";
2
 
3
  import Link from "next/link";
4
+ import { useEffect, useState } from "react";
5
  import { Github } from "lucide-react";
6
  import { usePathname, useRouter } from "next/navigation";
7
 
8
  import webConfig from "@/constants/common-env";
9
+ import { clearStoredAuthSession, getStoredAuthSession, type StoredAuthSession } from "@/store/auth";
10
  import { cn } from "@/lib/utils";
11
 
12
+ const adminNavItems = [
13
  { href: "/image", label: "画图" },
14
  { href: "/accounts", label: "号池管理" },
15
  { href: "/settings", label: "设置" },
16
  ];
17
 
18
+ const userNavItems = [{ href: "/image", label: "画图" }];
19
+
20
  export function TopNav() {
21
  const pathname = usePathname();
22
  const router = useRouter();
23
+ const [session, setSession] = useState<StoredAuthSession | null | undefined>(undefined);
24
+
25
+ useEffect(() => {
26
+ let active = true;
27
+
28
+ const load = async () => {
29
+ if (pathname === "/login") {
30
+ if (!active) {
31
+ return;
32
+ }
33
+ setSession(null);
34
+ return;
35
+ }
36
+
37
+ const storedSession = await getStoredAuthSession();
38
+ if (!active) {
39
+ return;
40
+ }
41
+ setSession(storedSession);
42
+ };
43
+
44
+ void load();
45
+ return () => {
46
+ active = false;
47
+ };
48
+ }, [pathname]);
49
 
50
  const handleLogout = async () => {
51
+ await clearStoredAuthSession();
52
  router.replace("/login");
53
  };
54
 
55
+ if (pathname === "/login" || session === undefined || !session) {
56
  return null;
57
  }
58
 
59
+ const navItems = session.role === "admin" ? adminNavItems : userNavItems;
60
+ const roleLabel = session.role === "admin" ? "管理员" : "普通用户";
61
+
62
  return (
63
  <header className="border-b border-stone-100/50">
64
  <div className="flex h-12 items-center justify-between px-3 sm:px-6">
 
99
  })}
100
  </div>
101
  <div className="flex items-center justify-end gap-2 sm:gap-3">
102
+ <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]">
103
+ {roleLabel}
104
+ </span>
105
  <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]">
106
  v{webConfig.appVersion}
107
  </span>
web/src/components/ui/dia-text-reveal.tsx CHANGED
@@ -1,6 +1,6 @@
1
  "use client"
2
 
3
- import { useEffect, useRef, useState } from "react"
4
  import {
5
  animate,
6
  motion,
@@ -138,7 +138,8 @@ export function DiaTextReveal({
138
  fixedWidth = false,
139
  ...props
140
  }: DiaTextRevealProps) {
141
- const texts = Array.isArray(text) ? text : [text]
 
142
  const isMulti = texts.length > 1
143
  const prefersReducedMotion = useReducedMotion()
144
 
@@ -152,15 +153,6 @@ export function DiaTextReveal({
152
  repeatDelay,
153
  texts,
154
  })
155
- optsRef.current = {
156
- colors,
157
- textColor,
158
- duration,
159
- delay,
160
- repeat,
161
- repeatDelay,
162
- texts,
163
- }
164
 
165
  const indexRef = useRef(0)
166
  const hasPlayedRef = useRef(false)
@@ -179,34 +171,48 @@ export function DiaTextReveal({
179
 
180
  const isInView = useInView(spanRef, { once, amount: 0.1 })
181
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  useEffect(() => {
183
  const el = spanRef.current
184
  if (!el || !isMulti) return
185
  setMeasuredWidths(measureWidths(el, texts))
186
- }, [Array.isArray(text) ? text.join("\0") : text])
187
 
188
- playRef.current = () => {
189
- const { duration, delay, repeat, repeatDelay, texts } = optsRef.current
 
190
 
191
- sweepPos.set(SWEEP_START)
192
 
193
- const controls = animate(sweepPos, SWEEP_END, {
194
- duration,
195
- delay,
196
- ease: sweepEase,
197
- onComplete() {
198
- if (!repeat) return
199
- timerRef.current = setTimeout(() => {
200
- const next = (indexRef.current + 1) % texts.length
201
- indexRef.current = next
202
- setActiveIndex(next)
203
- playRef.current()
204
- }, repeatDelay * 1000)
205
- },
206
- })
207
 
208
- stopRef.current = () => controls.stop()
209
- }
 
210
 
211
  useEffect(() => {
212
  if (prefersReducedMotion) {
 
1
  "use client"
2
 
3
+ import { useEffect, useMemo, useRef, useState } from "react"
4
  import {
5
  animate,
6
  motion,
 
138
  fixedWidth = false,
139
  ...props
140
  }: DiaTextRevealProps) {
141
+ const texts = useMemo(() => (Array.isArray(text) ? text : [text]), [text])
142
+ const textKey = texts.join("\0")
143
  const isMulti = texts.length > 1
144
  const prefersReducedMotion = useReducedMotion()
145
 
 
153
  repeatDelay,
154
  texts,
155
  })
 
 
 
 
 
 
 
 
 
156
 
157
  const indexRef = useRef(0)
158
  const hasPlayedRef = useRef(false)
 
171
 
172
  const isInView = useInView(spanRef, { once, amount: 0.1 })
173
 
174
+ useEffect(() => {
175
+ optsRef.current = {
176
+ colors,
177
+ textColor,
178
+ duration,
179
+ delay,
180
+ repeat,
181
+ repeatDelay,
182
+ texts,
183
+ }
184
+ }, [colors, delay, duration, repeat, repeatDelay, textColor, textKey, texts])
185
+
186
  useEffect(() => {
187
  const el = spanRef.current
188
  if (!el || !isMulti) return
189
  setMeasuredWidths(measureWidths(el, texts))
190
+ }, [isMulti, textKey, texts])
191
 
192
+ useEffect(() => {
193
+ playRef.current = () => {
194
+ const { duration, delay, repeat, repeatDelay, texts } = optsRef.current
195
 
196
+ sweepPos.set(SWEEP_START)
197
 
198
+ const controls = animate(sweepPos, SWEEP_END, {
199
+ duration,
200
+ delay,
201
+ ease: sweepEase,
202
+ onComplete() {
203
+ if (!repeat) return
204
+ timerRef.current = setTimeout(() => {
205
+ const next = (indexRef.current + 1) % texts.length
206
+ indexRef.current = next
207
+ setActiveIndex(next)
208
+ playRef.current()
209
+ }, repeatDelay * 1000)
210
+ },
211
+ })
212
 
213
+ stopRef.current = () => controls.stop()
214
+ }
215
+ }, [sweepPos])
216
 
217
  useEffect(() => {
218
  if (prefersReducedMotion) {
web/src/lib/api.ts CHANGED
@@ -3,6 +3,7 @@ import { httpRequest } from "@/lib/request";
3
  export type AccountType = "Free" | "Plus" | "ProLite" | "Pro" | "Team";
4
  export type AccountStatus = "正常" | "限流" | "异常" | "禁用";
5
  export type ImageModel = "auto" | "gpt-image-1" | "gpt-image-2";
 
6
 
7
  export type Account = {
8
  id: string;
@@ -52,14 +53,30 @@ type AccountUpdateResponse = {
52
  export type SettingsConfig = {
53
  proxy: string;
54
  base_url?: string;
55
- "auth-key"?: string;
56
  refresh_account_interval_minute?: number | string;
57
  [key: string]: unknown;
58
  };
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  export async function login(authKey: string) {
61
  const normalizedAuthKey = String(authKey || "").trim();
62
- return httpRequest<{ ok: boolean }>("/auth/login", {
63
  method: "POST",
64
  body: {},
65
  headers: {
@@ -163,6 +180,30 @@ export async function updateSettingsConfig(settings: SettingsConfig) {
163
  });
164
  }
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  // ── CPA (CLIProxyAPI) ──────────────────────────────────────────────
167
 
168
  export type CPAPool = {
 
3
  export type AccountType = "Free" | "Plus" | "ProLite" | "Pro" | "Team";
4
  export type AccountStatus = "正常" | "限流" | "异常" | "禁用";
5
  export type ImageModel = "auto" | "gpt-image-1" | "gpt-image-2";
6
+ export type AuthRole = "admin" | "user";
7
 
8
  export type Account = {
9
  id: string;
 
53
  export type SettingsConfig = {
54
  proxy: string;
55
  base_url?: string;
 
56
  refresh_account_interval_minute?: number | string;
57
  [key: string]: unknown;
58
  };
59
 
60
+ export type LoginResponse = {
61
+ ok: boolean;
62
+ version: string;
63
+ role: AuthRole;
64
+ subject_id: string;
65
+ name: string;
66
+ };
67
+
68
+ export type UserKey = {
69
+ id: string;
70
+ name: string;
71
+ role: "user";
72
+ enabled: boolean;
73
+ created_at: string | null;
74
+ last_used_at: string | null;
75
+ };
76
+
77
  export async function login(authKey: string) {
78
  const normalizedAuthKey = String(authKey || "").trim();
79
+ return httpRequest<LoginResponse>("/auth/login", {
80
  method: "POST",
81
  body: {},
82
  headers: {
 
180
  });
181
  }
182
 
183
+ export async function fetchUserKeys() {
184
+ return httpRequest<{ items: UserKey[] }>("/api/auth/users");
185
+ }
186
+
187
+ export async function createUserKey(name: string) {
188
+ return httpRequest<{ item: UserKey; key: string; items: UserKey[] }>("/api/auth/users", {
189
+ method: "POST",
190
+ body: { name },
191
+ });
192
+ }
193
+
194
+ export async function updateUserKey(keyId: string, updates: { enabled?: boolean; name?: string }) {
195
+ return httpRequest<{ item: UserKey; items: UserKey[] }>(`/api/auth/users/${keyId}`, {
196
+ method: "POST",
197
+ body: updates,
198
+ });
199
+ }
200
+
201
+ export async function deleteUserKey(keyId: string) {
202
+ return httpRequest<{ items: UserKey[] }>(`/api/auth/users/${keyId}`, {
203
+ method: "DELETE",
204
+ });
205
+ }
206
+
207
  // ── CPA (CLIProxyAPI) ──────────────────────────────────────────────
208
 
209
  export type CPAPool = {
web/src/lib/request.ts CHANGED
@@ -1,7 +1,7 @@
1
  import axios, {AxiosError, type AxiosRequestConfig} from "axios";
2
 
3
  import webConfig from "@/constants/common-env";
4
- import {clearStoredAuthKey, getStoredAuthKey} from "@/store/auth";
5
 
6
  type RequestConfig = AxiosRequestConfig & {
7
  redirectOnUnauthorized?: boolean;
@@ -32,7 +32,7 @@ request.interceptors.response.use(
32
  if (status === 401 && shouldRedirect && typeof window !== "undefined") {
33
  // Avoid redirect loop — only redirect if not already on /login
34
  if (!window.location.pathname.startsWith("/login")) {
35
- await clearStoredAuthKey();
36
  window.location.replace("/login");
37
  // Return a never-resolving promise to prevent further error handling
38
  // while the browser navigates away
 
1
  import axios, {AxiosError, type AxiosRequestConfig} from "axios";
2
 
3
  import webConfig from "@/constants/common-env";
4
+ import {clearStoredAuthSession, getStoredAuthKey} from "@/store/auth";
5
 
6
  type RequestConfig = AxiosRequestConfig & {
7
  redirectOnUnauthorized?: boolean;
 
32
  if (status === 401 && shouldRedirect && typeof window !== "undefined") {
33
  // Avoid redirect loop — only redirect if not already on /login
34
  if (!window.location.pathname.startsWith("/login")) {
35
+ await clearStoredAuthSession();
36
  window.location.replace("/login");
37
  // Return a never-resolving promise to prevent further error handling
38
  // while the browser navigates away
web/src/lib/use-auth-guard.ts ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useEffect, useState } from "react";
4
+ import { useRouter } from "next/navigation";
5
+
6
+ import {
7
+ getDefaultRouteForRole,
8
+ getStoredAuthSession,
9
+ type AuthRole,
10
+ type StoredAuthSession,
11
+ } from "@/store/auth";
12
+
13
+ type UseAuthGuardResult = {
14
+ isCheckingAuth: boolean;
15
+ session: StoredAuthSession | null;
16
+ };
17
+
18
+ export function useAuthGuard(allowedRoles?: AuthRole[]): UseAuthGuardResult {
19
+ const router = useRouter();
20
+ const [session, setSession] = useState<StoredAuthSession | null>(null);
21
+ const [isCheckingAuth, setIsCheckingAuth] = useState(true);
22
+ const allowedRolesKey = (allowedRoles || []).join(",");
23
+
24
+ useEffect(() => {
25
+ let active = true;
26
+
27
+ const load = async () => {
28
+ const roleList = allowedRolesKey ? (allowedRolesKey.split(",") as AuthRole[]) : [];
29
+ const storedSession = await getStoredAuthSession();
30
+ if (!active) {
31
+ return;
32
+ }
33
+
34
+ if (!storedSession) {
35
+ setSession(null);
36
+ setIsCheckingAuth(false);
37
+ router.replace("/login");
38
+ return;
39
+ }
40
+
41
+ if (roleList.length > 0 && !roleList.includes(storedSession.role)) {
42
+ setSession(storedSession);
43
+ setIsCheckingAuth(false);
44
+ router.replace(getDefaultRouteForRole(storedSession.role));
45
+ return;
46
+ }
47
+
48
+ setSession(storedSession);
49
+ setIsCheckingAuth(false);
50
+ };
51
+
52
+ void load();
53
+ return () => {
54
+ active = false;
55
+ };
56
+ }, [allowedRolesKey, router]);
57
+
58
+ return { isCheckingAuth, session };
59
+ }
60
+
61
+ export function useRedirectIfAuthenticated() {
62
+ const router = useRouter();
63
+ const [isCheckingAuth, setIsCheckingAuth] = useState(true);
64
+
65
+ useEffect(() => {
66
+ let active = true;
67
+
68
+ const load = async () => {
69
+ const storedSession = await getStoredAuthSession();
70
+ if (!active) {
71
+ return;
72
+ }
73
+
74
+ if (storedSession) {
75
+ router.replace(getDefaultRouteForRole(storedSession.role));
76
+ return;
77
+ }
78
+
79
+ setIsCheckingAuth(false);
80
+ };
81
+
82
+ void load();
83
+ return () => {
84
+ active = false;
85
+ };
86
+ }, [router]);
87
+
88
+ return { isCheckingAuth };
89
+ }
web/src/store/auth.ts CHANGED
@@ -2,13 +2,47 @@
2
 
3
  import localforage from "localforage";
4
 
 
 
 
 
 
 
 
 
 
5
  export const AUTH_KEY_STORAGE_KEY = "chatgpt2api_auth_key";
 
6
 
7
  const authStorage = localforage.createInstance({
8
  name: "chatgpt2api",
9
  storeName: "auth",
10
  });
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  export async function getStoredAuthKey() {
13
  if (typeof window === "undefined") {
14
  return "";
@@ -17,18 +51,62 @@ export async function getStoredAuthKey() {
17
  return String(value || "").trim();
18
  }
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  export async function setStoredAuthKey(authKey: string) {
21
  const normalizedAuthKey = String(authKey || "").trim();
22
  if (!normalizedAuthKey) {
23
- await clearStoredAuthKey();
24
  return;
25
  }
26
  await authStorage.setItem(AUTH_KEY_STORAGE_KEY, normalizedAuthKey);
27
  }
28
 
29
- export async function clearStoredAuthKey() {
30
  if (typeof window === "undefined") {
31
  return;
32
  }
33
- await authStorage.removeItem(AUTH_KEY_STORAGE_KEY);
 
 
 
 
 
 
 
34
  }
 
2
 
3
  import localforage from "localforage";
4
 
5
+ export type AuthRole = "admin" | "user";
6
+
7
+ export type StoredAuthSession = {
8
+ key: string;
9
+ role: AuthRole;
10
+ subjectId: string;
11
+ name: string;
12
+ };
13
+
14
  export const AUTH_KEY_STORAGE_KEY = "chatgpt2api_auth_key";
15
+ export const AUTH_SESSION_STORAGE_KEY = "chatgpt2api_auth_session";
16
 
17
  const authStorage = localforage.createInstance({
18
  name: "chatgpt2api",
19
  storeName: "auth",
20
  });
21
 
22
+ function normalizeSession(value: unknown, fallbackKey = ""): StoredAuthSession | null {
23
+ if (!value || typeof value !== "object") {
24
+ return null;
25
+ }
26
+
27
+ const candidate = value as Partial<StoredAuthSession>;
28
+ const key = String(candidate.key || fallbackKey || "").trim();
29
+ const role = candidate.role === "admin" || candidate.role === "user" ? candidate.role : null;
30
+ if (!key || !role) {
31
+ return null;
32
+ }
33
+
34
+ return {
35
+ key,
36
+ role,
37
+ subjectId: String(candidate.subjectId || "").trim(),
38
+ name: String(candidate.name || "").trim(),
39
+ };
40
+ }
41
+
42
+ export function getDefaultRouteForRole(role: AuthRole) {
43
+ return role === "admin" ? "/accounts" : "/image";
44
+ }
45
+
46
  export async function getStoredAuthKey() {
47
  if (typeof window === "undefined") {
48
  return "";
 
51
  return String(value || "").trim();
52
  }
53
 
54
+ export async function getStoredAuthSession() {
55
+ if (typeof window === "undefined") {
56
+ return null;
57
+ }
58
+
59
+ const [storedKey, storedSession] = await Promise.all([
60
+ authStorage.getItem<string>(AUTH_KEY_STORAGE_KEY),
61
+ authStorage.getItem<StoredAuthSession>(AUTH_SESSION_STORAGE_KEY),
62
+ ]);
63
+
64
+ const normalizedSession = normalizeSession(storedSession, String(storedKey || ""));
65
+ if (normalizedSession) {
66
+ if (normalizedSession.key !== String(storedKey || "").trim()) {
67
+ await authStorage.setItem(AUTH_KEY_STORAGE_KEY, normalizedSession.key);
68
+ }
69
+ return normalizedSession;
70
+ }
71
+
72
+ if (String(storedKey || "").trim()) {
73
+ await clearStoredAuthSession();
74
+ }
75
+ return null;
76
+ }
77
+
78
+ export async function setStoredAuthSession(session: StoredAuthSession) {
79
+ const normalizedSession = normalizeSession(session);
80
+ if (!normalizedSession) {
81
+ await clearStoredAuthSession();
82
+ return;
83
+ }
84
+
85
+ await Promise.all([
86
+ authStorage.setItem(AUTH_KEY_STORAGE_KEY, normalizedSession.key),
87
+ authStorage.setItem(AUTH_SESSION_STORAGE_KEY, normalizedSession),
88
+ ]);
89
+ }
90
+
91
  export async function setStoredAuthKey(authKey: string) {
92
  const normalizedAuthKey = String(authKey || "").trim();
93
  if (!normalizedAuthKey) {
94
+ await clearStoredAuthSession();
95
  return;
96
  }
97
  await authStorage.setItem(AUTH_KEY_STORAGE_KEY, normalizedAuthKey);
98
  }
99
 
100
+ export async function clearStoredAuthSession() {
101
  if (typeof window === "undefined") {
102
  return;
103
  }
104
+ await Promise.all([
105
+ authStorage.removeItem(AUTH_KEY_STORAGE_KEY),
106
+ authStorage.removeItem(AUTH_SESSION_STORAGE_KEY),
107
+ ]);
108
+ }
109
+
110
+ export async function clearStoredAuthKey() {
111
+ await clearStoredAuthSession();
112
  }