154 lines
5.1 KiB
Python
154 lines
5.1 KiB
Python
"""口令散列与登录令牌。
|
||
|
||
老系统用 ``MD5(密码 + salt)``(``DESCrypto`` / ``Utils`` 里那套),并且 salt 和口令
|
||
分开存两列。这里换 bcrypt,代价是每次校验几十毫秒,但对登录这种低频操作完全值得。
|
||
|
||
令牌用 JWT 而不是老系统那种"Redis 里存一个随机串":本系统要能在多实例下横向扩容,
|
||
也要让前端能离线判过期。撤销靠 ``accounts.password_updated_at`` 与刷新令牌表,
|
||
见 :func:`issue_tokens`。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import hmac
|
||
import secrets
|
||
from datetime import datetime, timedelta
|
||
from typing import Any
|
||
|
||
import bcrypt
|
||
from jose import JWTError, jwt
|
||
|
||
from .config import settings
|
||
|
||
_BCRYPT_MAX_BYTES = 72 # bcrypt 只看前 72 字节,超长口令先截断,避免"两种口令都能登"
|
||
|
||
|
||
def hash_password(password: str) -> str:
|
||
return bcrypt.hashpw(_encode(password), bcrypt.gensalt()).decode("utf-8")
|
||
|
||
|
||
def verify_password(password: str, password_hash: str) -> bool:
|
||
if not password_hash:
|
||
return False
|
||
try:
|
||
return bcrypt.checkpw(_encode(password), password_hash.encode("utf-8"))
|
||
except (ValueError, TypeError):
|
||
return False
|
||
|
||
|
||
def _encode(password: str) -> bytes:
|
||
return password.encode("utf-8")[:_BCRYPT_MAX_BYTES]
|
||
|
||
|
||
def random_password(length: int = 14) -> str:
|
||
return secrets.token_urlsafe(length)
|
||
|
||
|
||
class TokenError(Exception):
|
||
"""令牌无效、过期或已撤销。"""
|
||
|
||
|
||
def issue_tokens(
|
||
account_id: int,
|
||
account: str,
|
||
*,
|
||
identity_id: int | None = None,
|
||
extra: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""签发访问令牌 + 刷新令牌。"""
|
||
now = datetime.now()
|
||
access_payload: dict[str, Any] = {
|
||
"sub": str(account_id),
|
||
"account": account,
|
||
"typ": "access",
|
||
"iat": int(now.timestamp()),
|
||
"exp": int((now + timedelta(seconds=settings.security.access_token_ttl)).timestamp()),
|
||
}
|
||
if identity_id:
|
||
access_payload["identity"] = identity_id
|
||
if extra:
|
||
access_payload.update(extra)
|
||
|
||
refresh_payload = {
|
||
"sub": str(account_id),
|
||
"account": account,
|
||
"typ": "refresh",
|
||
"jti": secrets.token_hex(12),
|
||
"iat": int(now.timestamp()),
|
||
"exp": int((now + timedelta(seconds=settings.security.refresh_token_ttl)).timestamp()),
|
||
}
|
||
algorithm = settings.security.jwt_algorithm
|
||
# 出参用驼峰,和全站 wrapper 一致;这里的键名一旦改动,前端登录会静默失效
|
||
return {
|
||
"accessToken": jwt.encode(access_payload, _secret(), algorithm=algorithm),
|
||
"refreshToken": jwt.encode(refresh_payload, _secret(), algorithm=algorithm),
|
||
"tokenType": "bearer",
|
||
"expiresIn": settings.security.access_token_ttl,
|
||
}
|
||
|
||
|
||
def decode_token(token: str, *, expect: str = "access") -> dict[str, Any]:
|
||
try:
|
||
payload = jwt.decode(token, _secret(), algorithms=[settings.security.jwt_algorithm])
|
||
except JWTError as exc:
|
||
raise TokenError(f"令牌无效或已过期:{exc}") from exc
|
||
if payload.get("typ") != expect:
|
||
raise TokenError("令牌类型不正确")
|
||
return payload
|
||
|
||
|
||
def refresh_token_ttl() -> int:
|
||
return settings.security.refresh_token_ttl
|
||
|
||
|
||
def access_token_ttl() -> int:
|
||
return settings.security.access_token_ttl
|
||
|
||
|
||
def _secret() -> str:
|
||
secret = settings.security.jwt_secret
|
||
if not secret:
|
||
# 生产档漏配密钥时绝不能退化成"随便签一个能用的",直接拒绝签发
|
||
raise TokenError("服务端未配置 security.jwt_secret,无法签发登录令牌")
|
||
return secret
|
||
|
||
|
||
def signing_secret() -> str:
|
||
"""非 JWT 的东西(免登 state、一次性短码)也用这把密钥签/哈希。
|
||
|
||
集中在这里只有一个原因:密钥漏配时宁可抛错,也不能退化成"随便找个串签一下"——
|
||
那种情况下签出来的 state 谁都能造,免登的防注入就白做了。
|
||
"""
|
||
return _secret()
|
||
|
||
|
||
def hash_token(value: str) -> str:
|
||
"""令牌类字符串的哈希口径。库里只存这个,明文丢了也还原不出可用凭据。"""
|
||
return hashlib.sha256((value or "").encode("utf-8")).hexdigest()
|
||
|
||
|
||
def sign(value: str) -> str:
|
||
"""给短字符串签名(免登 state 的 Cookie 值用),常数时间比对靠 :func:`verify_signature`。"""
|
||
return hmac.new(signing_secret().encode("utf-8"), value.encode("utf-8"), hashlib.sha256).hexdigest()[:32]
|
||
|
||
|
||
def verify_signature(value: str, signature: str) -> bool:
|
||
return hmac.compare_digest(sign(value), (signature or "").strip())
|
||
|
||
|
||
def password_policy_error(password: str) -> str | None:
|
||
"""口令强度:长度 + 至少两类字符。返回 None 表示合格。"""
|
||
minimum = settings.security.password_min_length
|
||
if len(password) < minimum:
|
||
return f"口令长度不得少于 {minimum} 位"
|
||
kinds = sum([
|
||
any(char.islower() for char in password),
|
||
any(char.isupper() for char in password),
|
||
any(char.isdigit() for char in password),
|
||
any(not char.isalnum() for char in password),
|
||
])
|
||
if kinds < 2:
|
||
return "口令需包含小写字母、大写字母、数字、符号中的至少两类"
|
||
return None
|