- 后端:LX94 量价背离扫描(85 品种×4 周期)、JPush 推送分发、 账号/激活码体系、阿里云短信、管理台、28 项验收脚本 - 客户端:36 页 UI(漆器朱金主题)、自绘三窗格龙虾 K 线、 离线缓存、WorkManager 兜底轮询
148 lines
4.5 KiB
Python
148 lines
4.5 KiB
Python
"""安全基建:密码哈希、JWT(jti 吊销 + token_invalid_before)、激活码、图形验证码、限流。"""
|
||
from __future__ import annotations
|
||
|
||
import base64
|
||
import hashlib
|
||
import random
|
||
import secrets
|
||
import string
|
||
import threading
|
||
import time
|
||
from datetime import datetime, timedelta, timezone
|
||
|
||
from jose import JWTError, jwt
|
||
import bcrypt
|
||
|
||
from .config import settings
|
||
|
||
ALGORITHM = "HS256"
|
||
BJ = timezone(timedelta(hours=8))
|
||
|
||
# 激活码字符集:去除易混淆 0/O/1/I
|
||
CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
||
|
||
|
||
def hash_password(plain: str) -> str:
|
||
return bcrypt.hashpw(plain.encode("utf-8"), bcrypt.gensalt()).decode()
|
||
|
||
|
||
def verify_password(plain: str, hashed: str) -> bool:
|
||
try:
|
||
return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8"))
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
FAKE_HASH = hash_password("timing-safe-dummy") # 登录侧信道防护用恒定时延校验
|
||
|
||
|
||
def sha256(s: str) -> str:
|
||
return hashlib.sha256(s.encode("utf-8")).hexdigest()
|
||
|
||
|
||
def now_s() -> str:
|
||
return datetime.now(BJ).strftime("%Y-%m-%d %H:%M:%S")
|
||
|
||
|
||
def now_dt() -> datetime:
|
||
return datetime.now(BJ)
|
||
|
||
|
||
def gen_activation_code() -> str:
|
||
body = "".join(secrets.choice(CODE_ALPHABET) for _ in range(16))
|
||
return "-".join(body[i : i + 4] for i in (0, 4, 8, 12))
|
||
|
||
|
||
def gen_sms_code() -> str:
|
||
return f"{secrets.randbelow(1000000):06d}"
|
||
|
||
|
||
def gen_captcha_text() -> str:
|
||
return "".join(secrets.choice(CODE_ALPHABET) for _ in range(4))
|
||
|
||
|
||
def captcha_png(text: str) -> bytes:
|
||
"""Pillow 生成 PNG 验证码(Flutter Image.memory 可直接解码)。"""
|
||
import io
|
||
|
||
from PIL import Image, ImageDraw, ImageFont
|
||
|
||
W, H = 120, 40
|
||
img = Image.new("RGB", (W, H), (36, 24, 22)) # 暗漆
|
||
draw = ImageDraw.Draw(img)
|
||
# 干扰线
|
||
for _ in range(6):
|
||
x1, y1 = random.randint(0, W), random.randint(0, H)
|
||
draw.line((x1, y1, x1 + random.randint(-14, 14), y1 + random.randint(-10, 10)),
|
||
fill=(58, 42, 34), width=1)
|
||
# 噪点
|
||
for _ in range(80):
|
||
draw.point((random.randint(0, W - 1), random.randint(0, H - 1)), fill=(58, 42, 34))
|
||
# 字符(逐个贴到透明小图再旋转)
|
||
colors = [(201, 162, 39), (239, 227, 206), (168, 144, 120)]
|
||
font = None
|
||
for cand in ("/System/Library/Fonts/Menlo.ttc", "/System/Library/Fonts/Monaco.ttf",
|
||
"/System/Library/Fonts/Helvetica.ttc"):
|
||
try:
|
||
font = ImageFont.truetype(cand, 24)
|
||
break
|
||
except Exception:
|
||
continue
|
||
if font is None:
|
||
font = ImageFont.load_default()
|
||
for i, ch in enumerate(text):
|
||
tile = Image.new("RGBA", (34, 34), (0, 0, 0, 0))
|
||
d2 = ImageDraw.Draw(tile)
|
||
d2.text((6, 2), ch, font=font, fill=random.choice(colors))
|
||
tile = tile.rotate(random.randint(-18, 18), expand=True, resample=Image.BICUBIC)
|
||
img.paste(tile, (6 + i * 26, 3), tile)
|
||
buf = io.BytesIO()
|
||
img.save(buf, format="PNG")
|
||
return buf.getvalue()
|
||
|
||
|
||
def captcha_b64(text: str) -> str:
|
||
return base64.b64encode(captcha_png(text)).decode()
|
||
|
||
|
||
# ---- JWT ---------------------------------------------------------------------
|
||
|
||
def create_jwt(user_id: int, days: int | None = None, scope: str = "app") -> tuple[str, str, str]:
|
||
"""返回 (token, jti, expires_at_str)。"""
|
||
days = days or settings.jwt_days
|
||
now = datetime.now(BJ)
|
||
exp = now + timedelta(days=days)
|
||
jti = secrets.token_hex(16)
|
||
payload = {"sub": str(user_id), "jti": jti, "iat": int(now.timestamp()), "exp": int(exp.timestamp()), "scope": scope}
|
||
token = jwt.encode(payload, settings.jwt_secret, algorithm=ALGORITHM)
|
||
return token, jti, exp.strftime("%Y-%m-%d %H:%M:%S")
|
||
|
||
|
||
def decode_jwt(token: str) -> dict | None:
|
||
try:
|
||
return jwt.decode(token, settings.jwt_secret, algorithms=[ALGORITHM])
|
||
except JWTError:
|
||
return None
|
||
|
||
|
||
# ---- 简单限流(内存,重启即清,仅防突发) -------------------------------------
|
||
|
||
class RateLimiter:
|
||
def __init__(self) -> None:
|
||
self._hits: dict[str, list[float]] = {}
|
||
self._lock = threading.Lock()
|
||
|
||
def allow(self, key: str, limit: int, window_s: int) -> bool:
|
||
now = time.monotonic()
|
||
with self._lock:
|
||
hits = [t for t in self._hits.get(key, []) if now - t < window_s]
|
||
if len(hits) >= limit:
|
||
self._hits[key] = hits
|
||
return False
|
||
hits.append(now)
|
||
self._hits[key] = hits
|
||
return True
|
||
|
||
|
||
rate_limiter = RateLimiter()
|