Repository navigation
Expand file tree
/
Copy pathuser_auth_server.py
More file actions
589 lines (478 loc) · 16.1 KB
/
Copy pathuser_auth_server.py
File metadata and controls
589 lines (478 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
"""
用户管理 API 服务器
提供用户注册、登录、JWT 认证等功能
"""
import os
import sys
import uuid
import hashlib
import secrets
import threading
from datetime import datetime, timedelta
from typing import Optional
from pathlib import Path
import json
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Depends, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, EmailStr, Field
import uvicorn
try:
import jwt
except ImportError:
raise RuntimeError("缺少依赖 PyJWT,请先执行 `pip install PyJWT` 或安装 requirements.txt")
# 项目根目录
BASE_DIR = Path(__file__).parent.absolute()
DB_FILE = BASE_DIR / "user_db.json"
load_dotenv(BASE_DIR / ".env", override=True)
def get_cors_origins() -> list[str]:
raw = os.getenv("CORS_ALLOW_ORIGINS", "http://localhost:3000,http://localhost:3001")
origins = [origin.strip() for origin in raw.split(",") if origin.strip()]
return origins or ["http://localhost:3000", "http://localhost:3001"]
# JWT 配置
JWT_SECRET = os.getenv("JWT_SECRET_KEY", "samtree-default-jwt-secret-key-2026")
JWT_ALGORITHM = "HS256"
JWT_EXPIRATION_HOURS = 24 * 7 # 7 天
# --- 数据模型 ---
class User(BaseModel):
id: str
username: str
email: Optional[str] = None
password_hash: str
salt: str
created_at: str
updated_at: str
profile: dict = {}
class UserCreate(BaseModel):
username: str = Field(..., min_length=3, max_length=50)
password: str = Field(..., min_length=6)
email: Optional[str] = None
class UserLogin(BaseModel):
username: str
password: str
class Token(BaseModel):
access_token: str
token_type: str = "bearer"
expires_in: int
user_info: dict
class Message(BaseModel):
id: str
role: str # user or assistant
content: str
timestamp: str
tag: Optional[str] = None
class ConversationSession(BaseModel):
id: str
user_id: str
title: str
category: str
messages: list[Message] = []
created_at: str
updated_at: str
is_active: bool = True
# --- 密码加密工具 ---
def hash_password(password: str, salt: str) -> str:
"""使用 SHA-256 + salt 哈希密码"""
return hashlib.sha256((password + salt).encode()).hexdigest()
def generate_salt() -> str:
"""生成随机盐值"""
return secrets.token_hex(16)
# --- JWT 工具 ---
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
"""创建 JWT token"""
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(hours=JWT_EXPIRATION_HOURS)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, JWT_SECRET, algorithm=JWT_ALGORITHM)
return encoded_jwt
def verify_token(token: str) -> Optional[dict]:
"""验证 JWT token"""
try:
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
return payload
except jwt.ExpiredSignatureError:
return None
except jwt.InvalidTokenError:
return None
# --- 数据库类 ---
class UserDB:
def __init__(self, db_file: Path):
self.db_file = db_file
self._lock = threading.RLock()
self.data = {
"users": [],
"sessions": [],
"conversations": []
}
self._load()
def _load(self):
with self._lock:
if self.db_file.exists():
try:
with open(self.db_file, 'r', encoding='utf-8') as f:
self.data = json.load(f)
except (OSError, json.JSONDecodeError):
pass
def _save(self):
with self._lock:
with open(self.db_file, 'w', encoding='utf-8') as f:
json.dump(self.data, f, ensure_ascii=False, indent=2)
# 用户管理
def get_user_by_username(self, username: str) -> Optional[User]:
with self._lock:
for u in self.data["users"]:
if u["username"] == username:
return User(**u)
return None
def get_user_by_id(self, user_id: str) -> Optional[User]:
with self._lock:
for u in self.data["users"]:
if u["id"] == user_id:
return User(**u)
return None
def create_user(self, user: User) -> bool:
with self._lock:
if self.get_user_by_username(user.username):
return False
self.data["users"].append(user.model_dump())
self._save()
return True
def update_user(self, user_id: str, updates: dict) -> bool:
with self._lock:
for i, u in enumerate(self.data["users"]):
if u["id"] == user_id:
u.update(updates)
u["updated_at"] = datetime.now().isoformat()
self.data["users"][i] = u
self._save()
return True
return False
# 会话管理
def create_session(self, session: ConversationSession) -> str:
with self._lock:
self.data["sessions"].append(session.model_dump())
self._save()
return session.id
def get_user_sessions(self, user_id: str, limit: int = 20) -> list[ConversationSession]:
with self._lock:
sessions = [
ConversationSession(**s)
for s in self.data["sessions"]
if s["user_id"] == user_id
]
# 按更新时间排序
sessions.sort(key=lambda x: x.updated_at, reverse=True)
return sessions[:limit]
def get_session(self, session_id: str) -> Optional[ConversationSession]:
with self._lock:
for s in self.data["sessions"]:
if s["id"] == session_id:
return ConversationSession(**s)
return None
def add_message_to_session(self, session_id: str, message: Message) -> bool:
with self._lock:
for i, s in enumerate(self.data["sessions"]):
if s["id"] == session_id:
s["messages"].append(message.model_dump())
s["updated_at"] = datetime.now().isoformat()
self.data["sessions"][i] = s
self._save()
return True
return False
def update_session_title(self, session_id: str, title: str) -> bool:
with self._lock:
for i, s in enumerate(self.data["sessions"]):
if s["id"] == session_id:
s["title"] = title
s["updated_at"] = datetime.now().isoformat()
self.data["sessions"][i] = s
self._save()
return True
return False
def delete_session(self, session_id: str) -> bool:
with self._lock:
self.data["sessions"] = [s for s in self.data["sessions"] if s["id"] != session_id]
self._save()
return True
# 初始化数据库
db = UserDB(DB_FILE)
# --- FastAPI 应用 ---
app = FastAPI(
title="用户管理 API",
description="用户认证和会话管理系统",
version="1.0.0"
)
app.add_middleware(
CORSMiddleware,
allow_origins=get_cors_origins(),
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Security
security = HTTPBearer(auto_error=False)
# 依赖注入:获取当前用户
async def get_current_user(
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)
) -> User:
if not credentials:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="未授权访问",
headers={"WWW-Authenticate": "Bearer"},
)
token = credentials.credentials
payload = verify_token(token)
if not payload:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token 无效或已过期",
headers={"WWW-Authenticate": "Bearer"},
)
user_id = payload.get("sub")
if not user_id:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token 无效",
headers={"WWW-Authenticate": "Bearer"},
)
user = db.get_user_by_id(user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="用户不存在",
headers={"WWW-Authenticate": "Bearer"},
)
return user
# --- API 端点 ---
@app.get("/")
async def root():
return {
"name": "用户管理 API",
"version": "1.0.0",
"status": "running",
"users_count": len(db.data["users"]),
"sessions_count": len(db.data["sessions"])
}
@app.get("/health")
async def health_check():
return {"status": "healthy", "timestamp": datetime.now().isoformat()}
# ===== 用户认证 =====
@app.post("/api/auth/register", response_model=dict)
async def register(user_data: UserCreate):
"""用户注册"""
# 检查用户名是否已存在
if db.get_user_by_username(user_data.username):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="用户名已存在"
)
# 生成盐值和哈希密码
salt = generate_salt()
password_hash = hash_password(user_data.password, salt)
# 创建用户
new_user = User(
id=str(uuid.uuid4()),
username=user_data.username,
email=user_data.email,
password_hash=password_hash,
salt=salt,
created_at=datetime.now().isoformat(),
updated_at=datetime.now().isoformat(),
profile={
"display_name": user_data.username,
"avatar": None,
"bio": ""
}
)
if not db.create_user(new_user):
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="创建用户失败"
)
# 生成 token
access_token = create_access_token(
data={"sub": new_user.id, "username": new_user.username}
)
return {
"message": "注册成功",
"user": {
"id": new_user.id,
"username": new_user.username,
"email": new_user.email
},
"access_token": access_token,
"token_type": "bearer"
}
@app.post("/api/auth/login", response_model=Token)
async def login(credentials: UserLogin):
"""用户登录"""
user = db.get_user_by_username(credentials.username)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="用户名或密码错误"
)
# 验证密码
password_hash = hash_password(credentials.password, user.salt)
if password_hash != user.password_hash:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="用户名或密码错误"
)
# 生成 token
access_token = create_access_token(
data={"sub": user.id, "username": user.username}
)
return Token(
access_token=access_token,
token_type="bearer",
expires_in=JWT_EXPIRATION_HOURS * 3600,
user_info={
"id": user.id,
"username": user.username,
"email": user.email,
"profile": user.profile
}
)
@app.get("/api/auth/me", response_model=dict)
async def get_current_user_info(current_user: User = Depends(get_current_user)):
"""获取当前用户信息"""
return {
"id": current_user.id,
"username": current_user.username,
"email": current_user.email,
"profile": current_user.profile,
"created_at": current_user.created_at
}
@app.put("/api/auth/profile")
async def update_profile(
profile_data: dict,
current_user: User = Depends(get_current_user)
):
"""更新用户资料"""
allowed_fields = ["display_name", "avatar", "bio"]
updates = {k: v for k, v in profile_data.items() if k in allowed_fields}
if not updates:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="没有有效的更新内容"
)
if not db.update_user(current_user.id, {"profile": updates}):
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="更新失败"
)
return {"message": "更新成功"}
# ===== 会话管理 =====
@app.get("/api/sessions", response_model=list[ConversationSession])
async def get_user_sessions(
limit: int = 20,
current_user: User = Depends(get_current_user)
):
"""获取用户的会话列表"""
return db.get_user_sessions(current_user.id, limit)
@app.post("/api/sessions", response_model=dict)
async def create_session(
session_data: dict,
current_user: User = Depends(get_current_user)
):
"""创建新会话"""
new_session = ConversationSession(
id=str(uuid.uuid4()),
user_id=current_user.id,
title=session_data.get("title", "新对话"),
category=session_data.get("category", "general"),
messages=[],
created_at=datetime.now().isoformat(),
updated_at=datetime.now().isoformat(),
is_active=True
)
session_id = db.create_session(new_session)
return {
"message": "会话创建成功",
"session_id": session_id
}
@app.get("/api/sessions/{session_id}", response_model=ConversationSession)
async def get_session(
session_id: str,
current_user: User = Depends(get_current_user)
):
"""获取会话详情"""
session = db.get_session(session_id)
if not session:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="会话不存在"
)
# 验证会话所有权
if session.user_id != current_user.id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="无权访问此会话"
)
return session
@app.post("/api/sessions/{session_id}/messages")
async def add_message(
session_id: str,
message_data: dict,
current_user: User = Depends(get_current_user)
):
"""添加消息到会话"""
session = db.get_session(session_id)
if not session:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="会话不存在"
)
if session.user_id != current_user.id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="无权访问此会话"
)
message = Message(
id=str(uuid.uuid4()),
role=message_data["role"],
content=message_data["content"],
timestamp=datetime.now().isoformat(),
tag=message_data.get("tag")
)
if not db.add_message_to_session(session_id, message):
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="添加消息失败"
)
return {
"message": "消息已添加",
"message_id": message.id
}
@app.delete("/api/sessions/{session_id}")
async def delete_session(
session_id: str,
current_user: User = Depends(get_current_user)
):
"""删除会话"""
session = db.get_session(session_id)
if not session:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="会话不存在"
)
if session.user_id != current_user.id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="无权删除此会话"
)
db.delete_session(session_id)
return {"message": "会话已删除"}
if __name__ == "__main__":
print("=" * 60)
print("用户管理 API 服务器启动中...")
print(f"数据库文件:{DB_FILE}")
print(f"JWT Secret: {JWT_SECRET[:10]}...")
print("=" * 60)
uvicorn.run(app, host="0.0.0.0", port=8082, log_level="info")