feat: configure admin session lifetime (#484)

This commit is contained in:
Lan committed 2026-07-10 19:21:00 +08:00
1 parent 2c51384c80
commit 93ff291366
5 files changed
+108 -7

No files matched your search

+26 -3
View File
@@ -8,7 +8,12 @@ import base64
import hmac
import json
import time
from core.settings import settings
from core.settings import (
ADMIN_SESSION_EXPIRE_DEFAULT,
ADMIN_SESSION_EXPIRE_MAX,
ADMIN_SESSION_EXPIRE_MIN,
settings,
)
from apps.admin.services import FileService, ConfigService, LocalFileService
@@ -19,17 +24,35 @@ def _get_jwt_secret() -> bytes:
return secret.encode()
def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str:
def get_admin_session_expire_seconds() -> int:
try:
expires_in = int(
getattr(settings, "adminSessionExpire", ADMIN_SESSION_EXPIRE_DEFAULT)
)
except (TypeError, ValueError):
return ADMIN_SESSION_EXPIRE_DEFAULT
if (
not ADMIN_SESSION_EXPIRE_MIN <= expires_in <= ADMIN_SESSION_EXPIRE_MAX
or expires_in % ADMIN_SESSION_EXPIRE_MIN != 0
):
return ADMIN_SESSION_EXPIRE_DEFAULT
return expires_in
def create_token(data: dict, expires_in: int | None = None) -> str:
"""
创建JWT token
:param data: 数据负载
:param expires_in: 过期时间(秒)
"""
token_lifetime = (
get_admin_session_expire_seconds() if expires_in is None else expires_in
)
header = base64.b64encode(
json.dumps({"alg": "HS256", "typ": "JWT"}).encode()
).decode()
payload = base64.b64encode(
json.dumps({**data, "exp": int(time.time()) + expires_in}).encode()
json.dumps({**data, "exp": int(time.time()) + token_lifetime}).encode()
).decode()
signature = hmac.new(_get_jwt_secret(), f"{header}.{payload}".encode(), "sha256").digest()
+23 -1
View File
@@ -6,7 +6,11 @@ from typing import Any, Optional
from core.response import APIResponse
from core.storage import FileStorageInterface, storages
from core.settings import settings
from core.settings import (
ADMIN_SESSION_EXPIRE_MAX,
ADMIN_SESSION_EXPIRE_MIN,
settings,
)
from core.config import refresh_settings
from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret
from apps.base.models import FileCodes, KeyValue
@@ -1496,6 +1500,7 @@ class FileService:
class ConfigService:
INT_FIELDS = {
"adminSessionExpire",
"enableChunk",
"errorCount",
"errorMinute",
@@ -1554,6 +1559,23 @@ class ConfigService:
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail=f"{key} 配置值格式错误")
try:
session_expire = int(next_config.get("adminSessionExpire"))
except (TypeError, ValueError):
raise HTTPException(
status_code=400,
detail="adminSessionExpire 配置值格式错误",
)
if (
not ADMIN_SESSION_EXPIRE_MIN <= session_expire <= ADMIN_SESSION_EXPIRE_MAX
or session_expire % ADMIN_SESSION_EXPIRE_MIN != 0
):
raise HTTPException(
status_code=400,
detail="adminSessionExpire 必须是 1 到 365 个整天",
)
next_config["adminSessionExpire"] = session_expire
if admin_password_changed:
next_config["jwt_secret"] = generate_jwt_secret()
+17 -3
View File
@@ -31,7 +31,11 @@ from apps.admin.schemas import (
)
from core.response import APIResponse
from apps.base.models import FileCodes, KeyValue
from apps.admin.dependencies import create_token
from apps.admin.dependencies import (
create_token,
get_admin_session_expire_seconds,
verify_token,
)
from core.settings import settings
from core.utils import get_now, verify_password
@@ -53,8 +57,18 @@ async def login(data: LoginData):
if not verify_password(data.password, settings.admin_token):
raise HTTPException(status_code=401, detail="密码错误")
token = create_token({"is_admin": True})
return APIResponse(detail={"token": token, "token_type": "Bearer"})
expires_in = get_admin_session_expire_seconds()
token = create_token({"is_admin": True}, expires_in=expires_in)
return APIResponse(
detail={
"id": "admin",
"username": "admin",
"token": token,
"token_type": "Bearer",
"expires_at": verify_token(token)["exp"],
"expires_in": expires_in,
}
)
@admin_api.get("/verify")