Add Yaohuo verification-based self-service signup
This commit is contained in:
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import json
|
||||
import logging
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from functools import wraps
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, render_template, request, session
|
||||
@@ -10,7 +11,7 @@ from sqlalchemy import func, update
|
||||
|
||||
from . import db
|
||||
from .models import AuditEvent, RedemptionCode, utc_now
|
||||
from .services import Office365Service, ServiceConfigurationError, ServiceOperationError
|
||||
from .services import Office365Service, ServiceConfigurationError, ServiceOperationError, YaohuoVerificationService
|
||||
|
||||
|
||||
bp_admin = Blueprint("admin", __name__, url_prefix="/admin")
|
||||
@@ -20,6 +21,7 @@ logger = logging.getLogger("office365_self_service.routes")
|
||||
STATUS_AVAILABLE = "available"
|
||||
STATUS_PROCESSING = "processing"
|
||||
STATUS_USED = "used"
|
||||
YAOHUO_SESSION_KEY = "yaohuo_verification"
|
||||
|
||||
|
||||
def _settings():
|
||||
@@ -30,6 +32,10 @@ def _service() -> Office365Service:
|
||||
return current_app.extensions["office365_service"]
|
||||
|
||||
|
||||
def _yaohuo_service() -> YaohuoVerificationService:
|
||||
return current_app.extensions["yaohuo_verification_service"]
|
||||
|
||||
|
||||
def _success(data=None, message: str = "ok", status: int = 200):
|
||||
return jsonify({"success": True, "message": message, "data": data}), status
|
||||
|
||||
@@ -73,6 +79,42 @@ def _json_payload() -> dict:
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
|
||||
def _session_verification_state() -> dict:
|
||||
payload = session.get(YAOHUO_SESSION_KEY)
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
|
||||
|
||||
def _clear_yaohuo_verification() -> None:
|
||||
session.pop(YAOHUO_SESSION_KEY, None)
|
||||
|
||||
|
||||
def _verification_expired(expires_at: str | None) -> bool:
|
||||
if not expires_at:
|
||||
return True
|
||||
try:
|
||||
return datetime.fromisoformat(expires_at) <= datetime.now(timezone.utc)
|
||||
except ValueError:
|
||||
return True
|
||||
|
||||
|
||||
def _store_yaohuo_verification(target_user_id: str, code: str, expires_at: str) -> None:
|
||||
session[YAOHUO_SESSION_KEY] = {
|
||||
"targetUserId": target_user_id,
|
||||
"code": code,
|
||||
"expiresAt": expires_at,
|
||||
"verified": False,
|
||||
}
|
||||
|
||||
|
||||
def _mark_yaohuo_verified() -> None:
|
||||
state = _session_verification_state()
|
||||
if not state:
|
||||
return
|
||||
state["verified"] = True
|
||||
state.pop("code", None)
|
||||
session[YAOHUO_SESSION_KEY] = state
|
||||
|
||||
|
||||
def _code_match(code: str):
|
||||
return func.lower(RedemptionCode.code) == code.lower()
|
||||
|
||||
@@ -82,6 +124,7 @@ def _health_payload() -> dict:
|
||||
return {
|
||||
"platform": settings.to_public_dict(),
|
||||
"authenticated": _authenticated(),
|
||||
"yaohuoVerified": bool(_session_verification_state().get("verified")),
|
||||
}
|
||||
|
||||
|
||||
@@ -112,6 +155,68 @@ def _build_audit_event(
|
||||
)
|
||||
|
||||
|
||||
def _provision_account(username: str):
|
||||
actor = _current_actor("public")
|
||||
try:
|
||||
user_result = _service().create_user(username=username)
|
||||
except ServiceConfigurationError as exc:
|
||||
_record_audit_events(
|
||||
_build_audit_event(
|
||||
"account_provisioned",
|
||||
status="failed",
|
||||
actor=actor,
|
||||
username=username,
|
||||
details={"message": str(exc)},
|
||||
)
|
||||
)
|
||||
return _error(str(exc), status=503)
|
||||
except ServiceOperationError as exc:
|
||||
_record_audit_events(
|
||||
_build_audit_event(
|
||||
"account_provisioned",
|
||||
status="failed",
|
||||
actor=actor,
|
||||
username=username,
|
||||
principal_name=(exc.details or {}).get("userPrincipalName") if isinstance(exc.details, dict) else None,
|
||||
details={"message": exc.message, "serviceDetails": exc.details},
|
||||
)
|
||||
)
|
||||
return _error(exc.message, status=exc.status_code, details=exc.details)
|
||||
except Exception as exc:
|
||||
logger.exception("妖火验证建号时发生未预期错误")
|
||||
_record_audit_events(
|
||||
_build_audit_event(
|
||||
"account_provisioned",
|
||||
status="failed",
|
||||
actor=actor,
|
||||
username=username,
|
||||
details={"message": f"创建账号失败: {exc}"},
|
||||
)
|
||||
)
|
||||
return _error(f"创建账号失败: {exc}", status=500)
|
||||
|
||||
_record_audit_events(
|
||||
_build_audit_event(
|
||||
"account_provisioned",
|
||||
status="success",
|
||||
actor=actor,
|
||||
username=username,
|
||||
principal_name=user_result.get("userPrincipalName"),
|
||||
details={
|
||||
"licenseAssigned": user_result.get("licenseAssigned"),
|
||||
"licenseMessage": user_result.get("licenseMessage"),
|
||||
"source": "yaohuo_verification",
|
||||
},
|
||||
)
|
||||
)
|
||||
return _success({
|
||||
"userPrincipalName": user_result.get("userPrincipalName"),
|
||||
"temporaryPassword": user_result.get("temporaryPassword"),
|
||||
"licenseAssigned": user_result.get("licenseAssigned"),
|
||||
"licenseMessage": user_result.get("licenseMessage"),
|
||||
}, "账号开通成功!", status=201)
|
||||
|
||||
|
||||
def _record_audit_events(*events: AuditEvent) -> None:
|
||||
pending = [event for event in events if event is not None]
|
||||
if not pending:
|
||||
@@ -501,6 +606,98 @@ def redeem():
|
||||
}, "账号开通成功!", status=201)
|
||||
|
||||
|
||||
@bp_user.post("/api/yaohuo/send-code")
|
||||
def yaohuo_send_code():
|
||||
payload = _json_payload()
|
||||
target_user_id = str(payload.get("targetUserId", "")).strip()
|
||||
actor = _current_actor("public")
|
||||
|
||||
try:
|
||||
code = _yaohuo_service().generate_code()
|
||||
expires_at = _yaohuo_service().expires_at().isoformat()
|
||||
_yaohuo_service().send_verification_code(target_user_id, code)
|
||||
_store_yaohuo_verification(target_user_id, code, expires_at)
|
||||
except ServiceConfigurationError as exc:
|
||||
return _error(str(exc), status=503)
|
||||
except ServiceOperationError as exc:
|
||||
_record_audit_events(
|
||||
_build_audit_event(
|
||||
"yaohuo_verification_requested",
|
||||
status="failed",
|
||||
actor=actor,
|
||||
details={"targetUserId": target_user_id, "message": exc.message},
|
||||
)
|
||||
)
|
||||
return _error(exc.message, status=exc.status_code, details=exc.details)
|
||||
except ValueError as exc:
|
||||
return _error(str(exc), status=400)
|
||||
|
||||
_record_audit_events(
|
||||
_build_audit_event(
|
||||
"yaohuo_verification_requested",
|
||||
actor=actor,
|
||||
details={"targetUserId": target_user_id},
|
||||
)
|
||||
)
|
||||
return _success({"expiresAt": expires_at}, "验证码已发送到指定妖火 ID 的私信。")
|
||||
|
||||
|
||||
@bp_user.post("/api/yaohuo/verify")
|
||||
def yaohuo_verify():
|
||||
payload = _json_payload()
|
||||
submitted_code = str(payload.get("code", "")).strip()
|
||||
state = _session_verification_state()
|
||||
actor = _current_actor("public")
|
||||
|
||||
if not state:
|
||||
return _error("请先发送验证码。", status=400)
|
||||
if _verification_expired(state.get("expiresAt")):
|
||||
_clear_yaohuo_verification()
|
||||
return _error("验证码已过期,请重新发送。", status=410)
|
||||
if not submitted_code:
|
||||
return _error("请输入验证码。", status=400)
|
||||
if submitted_code != str(state.get("code", "")):
|
||||
_record_audit_events(
|
||||
_build_audit_event(
|
||||
"yaohuo_verified",
|
||||
status="failed",
|
||||
actor=actor,
|
||||
details={"targetUserId": state.get("targetUserId"), "message": "验证码错误。"},
|
||||
)
|
||||
)
|
||||
return _error("验证码错误。", status=400)
|
||||
|
||||
_mark_yaohuo_verified()
|
||||
_record_audit_events(
|
||||
_build_audit_event(
|
||||
"yaohuo_verified",
|
||||
actor=actor,
|
||||
details={"targetUserId": state.get("targetUserId")},
|
||||
)
|
||||
)
|
||||
return _success({"verified": True}, "妖火论坛验证成功。")
|
||||
|
||||
|
||||
@bp_user.post("/api/yaohuo/provision")
|
||||
def yaohuo_provision():
|
||||
payload = _json_payload()
|
||||
username = str(payload.get("username", "")).strip().lower()
|
||||
state = _session_verification_state()
|
||||
|
||||
if not username:
|
||||
return _error("请输入用户名。", status=400)
|
||||
if not state or not state.get("verified"):
|
||||
return _error("请先完成妖火论坛验证。", status=403)
|
||||
if _verification_expired(state.get("expiresAt")):
|
||||
_clear_yaohuo_verification()
|
||||
return _error("验证状态已过期,请重新验证。", status=410)
|
||||
|
||||
result = _provision_account(username)
|
||||
if result[1] < 400:
|
||||
_clear_yaohuo_verification()
|
||||
return result
|
||||
|
||||
|
||||
@bp_user.get("/api/config")
|
||||
def config():
|
||||
return _success(_settings().to_public_dict())
|
||||
|
||||
Reference in New Issue
Block a user