feat: 优化登录功能 - 服务端认证 + Cookie + 新UI
主要改进: 1. 添加服务端认证中间件,未登录用户自动重定向到登录页 2. 使用 HTTPOnly Cookie 存储 token(比 localStorage 更安全) 3. 添加"记住我"功能(勾选:30天,不勾选:1天) 4. 添加登出 API (/api/auth/logout) 5. 登录/注册页面采用 Neumorphism 设计风格 - 健康主题配色(青色 + 绿色) - Lora + Raleway 字体组合 - 新拟态阴影效果 6. 支持登录后重定向到原页面 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,7 +11,8 @@ import jwt
|
||||
# JWT 配置
|
||||
JWT_SECRET = os.environ.get("JWT_SECRET", "vitals-dev-secret-key-change-in-production")
|
||||
JWT_ALGORITHM = "HS256"
|
||||
JWT_EXPIRE_DAYS = 7
|
||||
JWT_EXPIRE_DAYS = 1 # 默认 1 天
|
||||
JWT_EXPIRE_DAYS_REMEMBER = 30 # 记住我:30 天
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
@@ -25,18 +26,32 @@ def verify_password(password: str, password_hash: str) -> bool:
|
||||
return bcrypt.checkpw(password.encode("utf-8"), password_hash.encode("utf-8"))
|
||||
|
||||
|
||||
def create_token(user_id: int, username: str, is_admin: bool = False) -> str:
|
||||
"""创建 JWT Token"""
|
||||
def create_token(user_id: int, username: str, is_admin: bool = False, remember_me: bool = False) -> str:
|
||||
"""创建 JWT Token
|
||||
|
||||
Args:
|
||||
user_id: 用户 ID
|
||||
username: 用户名
|
||||
is_admin: 是否管理员
|
||||
remember_me: 是否记住登录状态(True: 30天, False: 1天)
|
||||
"""
|
||||
expire_days = JWT_EXPIRE_DAYS_REMEMBER if remember_me else JWT_EXPIRE_DAYS
|
||||
payload = {
|
||||
"user_id": user_id,
|
||||
"username": username,
|
||||
"is_admin": is_admin,
|
||||
"exp": datetime.utcnow() + timedelta(days=JWT_EXPIRE_DAYS),
|
||||
"exp": datetime.utcnow() + timedelta(days=expire_days),
|
||||
"iat": datetime.utcnow(),
|
||||
}
|
||||
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
|
||||
|
||||
|
||||
def get_token_expire_seconds(remember_me: bool = False) -> int:
|
||||
"""获取 token 过期时间(秒)"""
|
||||
days = JWT_EXPIRE_DAYS_REMEMBER if remember_me else JWT_EXPIRE_DAYS
|
||||
return days * 24 * 60 * 60
|
||||
|
||||
|
||||
def decode_token(token: str) -> Optional[dict]:
|
||||
"""解码 JWT Token,返回 payload 或 None(如果无效/过期)"""
|
||||
try:
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user