"""Password hashing and JWT helpers.""" from __future__ import annotations import hashlib import secrets from datetime import datetime, timedelta, timezone from typing import Any import bcrypt from jose import JWTError, jwt from .config import settings # bcrypt reads at most 72 bytes of the password. _MAX_PASSWORD_BYTES = 72 def _encode(raw: str) -> bytes: return raw.encode("utf-8")[:_MAX_PASSWORD_BYTES] def hash_password(raw: str) -> str: return bcrypt.hashpw(_encode(raw), bcrypt.gensalt(rounds=10)).decode("utf-8") def verify_password(raw: str, hashed: str) -> bool: if not hashed: return False try: return bcrypt.checkpw(_encode(raw), hashed.encode("utf-8")) except ValueError: return False def session_idle_minutes() -> int: """空闲多久要求重新登录(分钟);0 或负数表示不启用。""" try: return max(0, int(settings.session_idle_minutes or 0)) except (TypeError, ValueError): return 0 def create_access_token(subject: str, extra: dict[str, Any] | None = None) -> tuple[str, int]: expires_in = settings.access_token_minutes * 60 # 开了空闲超时的话,访问令牌本身就不能活得比空闲窗口还久:访问令牌是自包含 JWT, # 在这期间内后端拦不住它,只靠刷新时检查等于没做(对接指南第 8 节)。 idle = session_idle_minutes() if idle: expires_in = min(expires_in, idle * 60) now = datetime.now(timezone.utc) payload: dict[str, Any] = { "sub": subject, "iat": int(now.timestamp()), "exp": int((now + timedelta(seconds=expires_in)).timestamp()), "type": "access", } if extra: payload.update(extra) token = jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm) return token, expires_in def create_refresh_token(subject: str) -> tuple[str, datetime]: """签发刷新令牌,顺带给出落库的过期时刻(**本机时钟**)。 JWT 里的 ``exp`` 是绝对时刻(epoch 秒),怎么算都不会错;库里 ``expires_at`` 那一列 却要和 ``create_time``、``last_used_at`` 放在一起比大小,而后两列用的是 :func:`app.models.localnow` 的本机时间。早先这里回的是 UTC-naive,+8 的部署每一行 都短八小时:按 ``expires_at`` 清理或排查时,会看到令牌"还没用过就已经过期"。 """ expires_at = datetime.now() + timedelta(days=settings.refresh_token_days) payload = { "sub": subject, "jti": secrets.token_hex(16), "exp": int(expires_at.timestamp()), "type": "refresh", } token = jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm) return token, expires_at def decode_token(token: str) -> dict[str, Any]: payload = jwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm]) if payload.get("type") not in {"access", "refresh"}: raise JWTError("unexpected token type") return payload def create_serial_ticket(process_id: str, serial: str, expires_in: int) -> str: """给一个刚占下的单号配一张短命凭条:凭条说得出"哪个流程、哪个号、到什么时候"。 「新建填单时就生成编号」这一档要在单子还不存在的时候就把号给人看,可那张号已经从 计数器里取走了。凭条不是把号送出去让人随便填回来——提交时后端只认这张签过名的短命 JWT,签名不对、流程不对、过期,一律当没这回事,改由发起那一刻正常排号。 """ now = datetime.now(timezone.utc) payload = { "sub": f"serial:{process_id}", "iat": int(now.timestamp()), "exp": int((now + timedelta(seconds=expires_in)).timestamp()), "type": "serial_reserve", "process": process_id, "serial": serial, } return jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm) def decode_serial_ticket(ticket: str) -> dict[str, Any] | None: """读出凭条上的流程与单号;签名不对、过期、类型不对一律回 None(不抛)。 这里不报错是有意的:凭条过期是这一档的正常代价(人填了半小时才提交), 那种情况下"当没预约过、发起时正常排号"比给人一句 400 客气得多。 """ if not ticket: return None try: payload = jwt.decode(ticket, settings.jwt_secret, algorithms=[settings.jwt_algorithm]) except JWTError: return None if payload.get("type") != "serial_reserve": return None process = str(payload.get("process") or "") serial = str(payload.get("serial") or "") if not process or not serial: return None return {"process": process, "serial": serial} def hash_token(token: str) -> str: return hashlib.sha256(token.encode("utf-8")).hexdigest()