优化验证

This commit is contained in:
咕谷酱
2025-09-24 02:08:13 +08:00
parent 8054281b15
commit 86c7bbb74e
13 changed files with 891 additions and 5 deletions

View File

@@ -317,13 +317,51 @@ def totp_redis_key(user: User) -> str:
return f"totp:setup:{user.email}"
def _generate_totp_account_label(user: User) -> str:
"""生成TOTP账户标签
根据配置选择使用用户名或邮箱,并添加服务器信息使标签更具描述性
"""
if settings.totp_use_username_in_label:
# 使用用户名作为主要标识
primary_identifier = user.username
else:
# 使用邮箱作为标识
primary_identifier = user.email
# 如果配置了服务名称,添加到标签中以便在认证器中区分
if settings.totp_service_name:
return f"{primary_identifier} ({settings.totp_service_name})"
else:
return primary_identifier
def _generate_totp_issuer_name() -> str:
"""生成TOTP发行者名称
优先使用自定义的totp_issuer否则使用服务名称
"""
if settings.totp_issuer:
return settings.totp_issuer
elif settings.totp_service_name:
return settings.totp_service_name
else:
# 回退到默认值
return "osu! Private Server"
async def start_create_totp_key(user: User, redis: Redis) -> StartCreateTotpKeyResp:
secret = pyotp.random_base32()
await redis.hset(totp_redis_key(user), mapping={"secret": secret, "fails": 0}) # pyright: ignore[reportGeneralTypeIssues]
await redis.expire(totp_redis_key(user), 300)
# 生成更完整的账户标签和issuer信息
account_label = _generate_totp_account_label(user)
issuer_name = _generate_totp_issuer_name()
return StartCreateTotpKeyResp(
secret=secret,
uri=pyotp.totp.TOTP(secret).provisioning_uri(name=user.email, issuer_name=settings.totp_issuer),
uri=pyotp.totp.TOTP(secret).provisioning_uri(name=account_label, issuer_name=issuer_name),
)