chore: initialize GSREA website project
This commit is contained in:
commit
d3c5461de5
1842 files changed
+246140
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,56 @@
|
||||
from functools import lru_cache
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||
|
||||
app_name: str = "甘肃省房地产价格评估行业协会"
|
||||
cors_origins: str = (
|
||||
"http://127.0.0.1:13000,http://localhost:13000,"
|
||||
"http://127.0.0.1:13006,http://localhost:13006"
|
||||
)
|
||||
jwt_secret: str = ""
|
||||
jwt_expire_minutes: int = 120
|
||||
# 门户会员令牌(专家答疑等),默认 7 天;工作人员仍用 jwt_expire_minutes。
|
||||
jwt_member_expire_minutes: int = 10080
|
||||
api_payload_encrypt: bool = False
|
||||
api_payload_aes_key: str = ""
|
||||
api_ip_blacklist: str = ""
|
||||
database_url: str = ""
|
||||
redis_host: str = "127.0.0.1"
|
||||
redis_port: int = 6379
|
||||
redis_db: int = 0
|
||||
redis_password: str = ""
|
||||
redis_timeout_sec: int = 30
|
||||
redis_ssl_enabled: bool = False
|
||||
minio_endpoint: str = ""
|
||||
minio_access_key: str = ""
|
||||
minio_secret_key: str = ""
|
||||
minio_bucket_public: str = "gsfdc-public"
|
||||
minio_bucket_private: str = "gsfdc-private"
|
||||
minio_secure: bool = False
|
||||
minio_base_url: str = ""
|
||||
field_aes_key: str = ""
|
||||
gaode_key: str = ""
|
||||
gaode_security_js_code: str = ""
|
||||
smtp_host: str = ""
|
||||
smtp_port: int = 465
|
||||
smtp_user: str = ""
|
||||
smtp_password: str = ""
|
||||
smtp_sender: str = ""
|
||||
smtp_use_ssl: bool = True
|
||||
|
||||
@property
|
||||
def cors_origin_list(self) -> list[str]:
|
||||
return [item.strip() for item in self.cors_origins.split(",") if item.strip()]
|
||||
|
||||
@property
|
||||
def blocked_ips(self) -> set[str]:
|
||||
return {item.strip() for item in self.api_ip_blacklist.split(",") if item.strip()}
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
@@ -0,0 +1,43 @@
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from app.core.config import get_settings
|
||||
|
||||
|
||||
def _key() -> bytes:
|
||||
settings = get_settings()
|
||||
raw = settings.api_payload_aes_key.strip()
|
||||
if not raw:
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="接口加密未配置")
|
||||
try:
|
||||
key = base64.b64decode(raw)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="接口加密未配置")
|
||||
if len(key) not in {16, 24, 32}:
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="接口加密未配置")
|
||||
return key
|
||||
|
||||
|
||||
def encrypt_json(payload: dict | list) -> dict:
|
||||
nonce = os.urandom(12)
|
||||
plain = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode()
|
||||
ciphertext = AESGCM(_key()).encrypt(nonce, plain, None)
|
||||
return {"data": base64.b64encode(nonce + ciphertext).decode()}
|
||||
|
||||
|
||||
def decrypt_json(envelope: dict) -> dict | list:
|
||||
token = envelope.get("data")
|
||||
if not isinstance(token, str):
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="加密报文格式不正确")
|
||||
try:
|
||||
raw = base64.b64decode(token)
|
||||
plain = AESGCM(_key()).decrypt(raw[:12], raw[12:], None)
|
||||
return json.loads(plain)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="加密报文无法解密")
|
||||
@@ -0,0 +1,26 @@
|
||||
from fastapi import Depends
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
from app.core.security import decode_access_token
|
||||
|
||||
bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
async def require_staff(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(bearer),
|
||||
) -> dict:
|
||||
if credentials is None:
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="请先登录")
|
||||
return decode_access_token(credentials.credentials, "staff")
|
||||
|
||||
|
||||
async def require_member(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(bearer),
|
||||
) -> dict:
|
||||
if credentials is None:
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="请先登录")
|
||||
return decode_access_token(credentials.credentials, "member")
|
||||
@@ -0,0 +1,50 @@
|
||||
# 数据库字段加密(AES-256-GCM)。与 app.core.crypto 的接口报文加密相互独立。
|
||||
import base64
|
||||
import os
|
||||
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from app.core.config import get_settings
|
||||
|
||||
_DETAIL = "字段加密未配置"
|
||||
|
||||
|
||||
def _fail() -> None:
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=_DETAIL)
|
||||
|
||||
|
||||
def _key() -> bytes:
|
||||
raw = "".join(get_settings().field_aes_key.split())
|
||||
if not raw:
|
||||
_fail()
|
||||
try:
|
||||
key = base64.b64decode(raw, validate=True)
|
||||
except Exception:
|
||||
_fail()
|
||||
if len(key) != 32:
|
||||
_fail()
|
||||
return key
|
||||
|
||||
|
||||
def encrypt_text(plain: str) -> str:
|
||||
if plain == "":
|
||||
return ""
|
||||
nonce = os.urandom(12)
|
||||
ciphertext = AESGCM(_key()).encrypt(nonce, plain.encode("utf-8"), None)
|
||||
return base64.b64encode(nonce + ciphertext).decode("ascii")
|
||||
|
||||
|
||||
def decrypt_text(token: str) -> str:
|
||||
if token == "":
|
||||
return ""
|
||||
try:
|
||||
raw = base64.b64decode(token, validate=True)
|
||||
if len(raw) < 13:
|
||||
raise ValueError("short")
|
||||
plain = AESGCM(_key()).decrypt(raw[:12], raw[12:], None)
|
||||
return plain.decode("utf-8")
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="字段密文无法解密") from None
|
||||
@@ -0,0 +1,23 @@
|
||||
def mask_mobile(value: str | None) -> str:
|
||||
if not value:
|
||||
return ""
|
||||
if len(value) < 7:
|
||||
return "***"
|
||||
return f"{value[:3]}****{value[-4:]}"
|
||||
|
||||
|
||||
def mask_email(value: str | None) -> str:
|
||||
if not value or "@" not in value:
|
||||
return ""
|
||||
name, _, domain = value.partition("@")
|
||||
if not name or not domain:
|
||||
return ""
|
||||
return f"{name[:1]}***@{domain}"
|
||||
|
||||
|
||||
def mask_id_card(value: str | None) -> str:
|
||||
if not value:
|
||||
return ""
|
||||
if len(value) < 8:
|
||||
return "***"
|
||||
return f"{value[:4]}**********{value[-4:]}"
|
||||
@@ -0,0 +1,108 @@
|
||||
import json
|
||||
import logging
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.core.config import get_settings
|
||||
from app.core.crypto import decrypt_json, encrypt_json
|
||||
|
||||
logger = logging.getLogger("gsfdc.access")
|
||||
|
||||
_SKIP_ENCRYPT_PREFIXES = ("/docs", "/redoc", "/openapi.json")
|
||||
|
||||
|
||||
def _skip_encrypt(path: str, content_type: str) -> bool:
|
||||
if path.startswith(_SKIP_ENCRYPT_PREFIXES):
|
||||
return True
|
||||
if "multipart/form-data" in content_type:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class AccessGuardMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
client = request.client.host if request.client else ""
|
||||
if _ip_blocked(client):
|
||||
return JSONResponse(status_code=403, content={"detail": "访问被拒绝"})
|
||||
|
||||
if get_settings().api_payload_encrypt and not _skip_encrypt(
|
||||
request.url.path, request.headers.get("content-type", "")
|
||||
):
|
||||
request = await _decrypt_request(request)
|
||||
|
||||
response = await call_next(request)
|
||||
logger.info("%s %s %s", request.method, request.url.path, response.status_code)
|
||||
_record_admin_call(request, response.status_code)
|
||||
|
||||
if get_settings().api_payload_encrypt and not _skip_encrypt(
|
||||
request.url.path, response.headers.get("content-type", "")
|
||||
):
|
||||
return await _encrypt_response(response)
|
||||
return response
|
||||
|
||||
|
||||
async def _decrypt_request(request: Request) -> Request:
|
||||
body = await request.body()
|
||||
raw = body
|
||||
if body:
|
||||
try:
|
||||
envelope = json.loads(body)
|
||||
except json.JSONDecodeError:
|
||||
envelope = None
|
||||
if isinstance(envelope, dict) and "data" in envelope:
|
||||
plain = decrypt_json(envelope)
|
||||
raw = json.dumps(plain, ensure_ascii=False).encode()
|
||||
|
||||
async def receive():
|
||||
return {"type": "http.request", "body": raw, "more_body": False}
|
||||
|
||||
return Request(request.scope, receive)
|
||||
|
||||
|
||||
async def _encrypt_response(response: Response) -> Response:
|
||||
body = b""
|
||||
async for chunk in response.body_iterator:
|
||||
body += chunk
|
||||
if not body:
|
||||
return response
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
except json.JSONDecodeError:
|
||||
return Response(content=body, status_code=response.status_code, headers=dict(response.headers))
|
||||
encrypted = encrypt_json(payload if isinstance(payload, (dict, list)) else {"data": payload})
|
||||
return JSONResponse(status_code=response.status_code, content=encrypted)
|
||||
|
||||
|
||||
def _ip_blocked(ip: str) -> bool:
|
||||
if not ip:
|
||||
return False
|
||||
try:
|
||||
from app.services.ip_guard import is_ip_blocked
|
||||
|
||||
return is_ip_blocked(ip)
|
||||
except Exception:
|
||||
return ip in get_settings().blocked_ips
|
||||
|
||||
|
||||
def _record_admin_call(request: Request, status_code: int) -> None:
|
||||
try:
|
||||
from app.services.audit import record_admin_call
|
||||
|
||||
record_admin_call(request, status_code)
|
||||
except Exception:
|
||||
logger.warning("admin audit hook failed")
|
||||
|
||||
|
||||
def install_middleware(app: FastAPI) -> None:
|
||||
settings = get_settings()
|
||||
app.add_middleware(AccessGuardMiddleware)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.cors_origin_list,
|
||||
allow_credentials=False,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
@@ -0,0 +1,42 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Literal
|
||||
|
||||
import jwt
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from app.core.config import get_settings
|
||||
|
||||
TokenType = Literal["staff", "member"]
|
||||
|
||||
|
||||
def create_access_token(subject: str, token_type: TokenType) -> str:
|
||||
settings = get_settings()
|
||||
if len(settings.jwt_secret) < 32:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="鉴权未配置",
|
||||
)
|
||||
minutes = (
|
||||
settings.jwt_member_expire_minutes
|
||||
if token_type == "member"
|
||||
else settings.jwt_expire_minutes
|
||||
)
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=minutes)
|
||||
payload = {"sub": subject, "typ": token_type, "exp": expire}
|
||||
return jwt.encode(payload, settings.jwt_secret, algorithm="HS256")
|
||||
|
||||
|
||||
def decode_access_token(token: str, expected_type: TokenType) -> dict:
|
||||
settings = get_settings()
|
||||
if len(settings.jwt_secret) < 32:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="鉴权未配置",
|
||||
)
|
||||
try:
|
||||
payload = jwt.decode(token, settings.jwt_secret, algorithms=["HS256"])
|
||||
except jwt.PyJWTError:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效")
|
||||
if payload.get("typ") != expected_type or not payload.get("sub"):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="无权访问该接口")
|
||||
return payload
|
||||
Reference in new issue
Block a user