766 lines
37 KiB
Python
766 lines
37 KiB
Python
"""登录、令牌、免登与"我"的信息。"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
from datetime import datetime, timedelta
|
||
from typing import Any
|
||
|
||
from fastapi import APIRouter, Query, Request, Response
|
||
from fastapi.responses import RedirectResponse
|
||
from pydantic import BaseModel, Field
|
||
from sqlalchemy import select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from ..config import settings
|
||
from ..deps import CurrentUser, DbSession, PrincipalOf, client_ip
|
||
from ..envelope import ApiError, ok
|
||
from ..models import (Account, AccountIdentity, AccountSource, LoginLog, OperationLog,
|
||
OrgUnit, Status)
|
||
from ..security import (
|
||
TokenError,
|
||
decode_token,
|
||
hash_password,
|
||
issue_tokens,
|
||
password_policy_error,
|
||
verify_password,
|
||
)
|
||
from ..service import hub_api, org_sync, permissions, sso_handoff, sso_state
|
||
|
||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||
|
||
|
||
class LoginBody(BaseModel):
|
||
account: str = Field(min_length=1, max_length=190)
|
||
password: str = Field(min_length=1, max_length=200)
|
||
#: Hub 开着且它要验证码时才有值;没要就留空,别把空串当"验证码错误"送过去。
|
||
captchaId: str = ""
|
||
captchaAnswer: str = ""
|
||
|
||
|
||
class RefreshBody(BaseModel):
|
||
refreshToken: str
|
||
|
||
|
||
class PasswordBody(BaseModel):
|
||
oldPassword: str = ""
|
||
newPassword: str = Field(min_length=1, max_length=200)
|
||
|
||
|
||
@router.post("/login")
|
||
def login(body: LoginBody, request: Request, db: DbSession) -> dict[str, Any]:
|
||
"""账号口令登录。界面上只有一个账号口令框,归谁验由 ``[hub].login_mode`` 决定。
|
||
|
||
统一身份开着的时候,这个框收的就是 Hub 账号:口令由 Hub 判定,本系统只把结果换成
|
||
自己的会话,口令明文既不落库也不写日志。返回值里的 ``via`` 说清这次是走哪条路进来
|
||
的(``hub`` / ``local``),登录日志与前端提示都照着它讲。
|
||
"""
|
||
account, via, detail = _authenticate(db, body, request)
|
||
# 审计里的 mode 与返回给前端的 via 同源:都回答"口令归谁判的"
|
||
judged = "hub" if via == "hub" else "password"
|
||
if not Status.is_active(account.status):
|
||
_log(db, account.id, account.account, False, Status.label(account.status), request,
|
||
mode=judged)
|
||
db.commit()
|
||
raise ApiError("disabled", f"账号已{Status.label(account.status)},请联系管理员", http_status=403)
|
||
|
||
return ok({**_issue_session(db, request, account, detail=detail, mode=judged), "via": via})
|
||
|
||
|
||
def _authenticate(db: Session, body: LoginBody,
|
||
request: Request) -> tuple[Account, str, str]:
|
||
"""返回 ``(本地账号, 认证方式, 登录日志说明)``。
|
||
|
||
判定顺序照 unisoa 那套口径来,两条不能让步的:
|
||
|
||
* **应急账号先走本地**。内置超管永远在 ``local_only_accounts`` 里,Hub 密钥配错、
|
||
目录同步没跑、Hub 整个停机的时候还得进得去门改配置,否则就只能改库了。
|
||
* **Hub 说"不对"就是不对**。被拒之后绝不拿库里那个旧哈希再兜一层——那样 Hub 上的
|
||
停用、离职下线、改口令会在故障期集体失效。只有"压根没问到"(连不上、超时)才谈
|
||
得上 ``login_mode = "hybrid"`` 那条回落。
|
||
"""
|
||
hub = settings.hub
|
||
name = body.account.strip()
|
||
if hub.hub_password_login and name.lower() not in hub.local_only_account_set:
|
||
try:
|
||
principal = hub_api.login_with_password(name, body.password,
|
||
captcha_id=body.captchaId.strip(),
|
||
captcha_answer=body.captchaAnswer.strip())
|
||
except hub_api.HubRejected as exc:
|
||
# 故意不去动 login_failed_count:那是本地口令的锁定计数,让 Hub 的失败去
|
||
# 累加它,等于给外面开一条"把管理员锁在自己系统外面"的免费通道。
|
||
_log(db, None, name, False, f"统一身份拒绝:{exc.message}", request, mode="hub")
|
||
db.commit()
|
||
if exc.needs_captcha:
|
||
raise ApiError("captcha_required", exc.message or "验证码不正确或已失效",
|
||
http_status=401) from exc
|
||
raise ApiError("bad_credentials", exc.message or "账号或口令不正确",
|
||
http_status=401) from exc
|
||
except hub_api.HubError as exc:
|
||
if hub.mode != "hybrid":
|
||
raise ApiError("hub_unavailable",
|
||
f"{exc};本档口令只认统一身份,可改用统一门户免登",
|
||
http_status=503) from exc
|
||
logger.warning("统一身份不可用,退回本地口令校验 %s:%s", name, exc)
|
||
else:
|
||
account = _account_from_hub(db, principal, name, request)
|
||
sub = str(principal.get("sub") or "").strip()
|
||
return account, "hub", f"统一身份口令校验通过(sub={sub or '-'})"
|
||
|
||
return _local_login(db, name, body.password, request), "local", ""
|
||
|
||
|
||
def _local_login(db: Session, name: str, password: str, request: Request) -> Account:
|
||
"""本地口令那条路:查号、锁定、验哈希、记失败次数。"""
|
||
account = db.execute(
|
||
select(Account).where(Account.account == name, Account.is_deleted.is_(False))
|
||
).scalars().first()
|
||
|
||
if account is None:
|
||
_log(db, None, name, False, "账号不存在", request)
|
||
raise ApiError("bad_credentials", "账号或口令不正确", http_status=401)
|
||
if account.locked_until and account.locked_until > datetime.now():
|
||
minutes = max(1, int((account.locked_until - datetime.now()).total_seconds() // 60) + 1)
|
||
raise ApiError("locked", f"账号已锁定,请 {minutes} 分钟后再试", http_status=429)
|
||
|
||
if not _verify(db, account, password):
|
||
_fail(db, account, request)
|
||
raise ApiError("bad_credentials", "账号或口令不正确", http_status=401)
|
||
return account
|
||
|
||
|
||
def _issue_session(db: Session, request: Request, account: Account, *,
|
||
detail: str, mode: str = "password") -> dict[str, Any]:
|
||
"""登录成功后公共的那一段:记登录日志、落最近登录信息、发令牌、拼权限。
|
||
|
||
口令登录、免登票据、免登短码三条入口都必须走这里,否则很容易出现"免登进来的
|
||
人没记登录日志"或者"免登没清失败计数,被上一次口令输错连坐锁定"这类偏差。
|
||
"""
|
||
account.login_failed_count = 0
|
||
account.locked_until = None
|
||
account.last_login_at = datetime.now()
|
||
account.last_login_ip = _client_ip(request)
|
||
tokens = issue_tokens(account.id, account.account)
|
||
context = permissions.build_context(db, account)
|
||
_log(db, account.id, account.account, True, detail, request, mode=mode)
|
||
db.commit()
|
||
return {
|
||
**tokens,
|
||
"user": profile_payload(db, account),
|
||
"permissions": sorted(context.codes) or (["*"] if context.is_system_admin else []),
|
||
"roles": [{"id": role.id, "code": role.code, "name": role.name} for role in context.roles],
|
||
}
|
||
|
||
|
||
def _verify(db: Session, account: Account, password: str) -> bool:
|
||
"""本地口令校验:只管本系统自己存的那份哈希。
|
||
|
||
Hub 账号的口令不归这里管——那是 :func:`_authenticate` 拿去问统一身份的事,本系统
|
||
库里给 Hub 账号存的哈希(同步建的号甚至是空串)不构成任何凭据。所以这里没有任何
|
||
"Hub 连不上就当本地账号放行"的兜底:那样做等于让 Hub 的停用与离职下线在故障期间
|
||
集体失效,是最坏情况下最不该发生的事。
|
||
|
||
Hub 整体不可用时的逃生门是 ``[hub].break_glass_login``,它只放行 ``source=local``
|
||
的账号(内置超管),不给任何 Hub 账号开后门;想留更宽的退路请显式改
|
||
``[hub].login_mode = "hybrid"``。
|
||
"""
|
||
if account.source == AccountSource.HUB:
|
||
return False
|
||
# login_mode = "sso" 时口令这条路整个关掉,连逃生门也不留
|
||
if not settings.hub.local_password_login_allowed:
|
||
return False
|
||
if settings.hub.enabled and not settings.hub.break_glass_login:
|
||
return False
|
||
return verify_password(password, account.password_hash)
|
||
|
||
|
||
|
||
def _fail(db, account: Account, request: Request) -> None:
|
||
limit = settings.security.login_max_errors
|
||
account.login_failed_count = (account.login_failed_count or 0) + 1
|
||
if limit and account.login_failed_count >= limit:
|
||
account.locked_until = datetime.now() + timedelta(minutes=settings.security.login_lock_minutes)
|
||
account.login_failed_count = 0
|
||
_log(db, account.id, account.account, False, "口令不正确", request)
|
||
db.commit()
|
||
|
||
|
||
def _log(db, account_id: int | None, account: str, success: bool, reason: str, request: Request,
|
||
*, mode: str = "password") -> None:
|
||
"""记一条登录审计。
|
||
|
||
``mode`` 说的是"这次是谁判的":``password`` 本地口令、``hub`` 统一身份口令、
|
||
``sso`` 统一门户免登。排查时"这个人到底是怎么进来的"全靠这一列,不能都糊成默认值。
|
||
"""
|
||
db.add(LoginLog(
|
||
account=account, account_id=account_id, success=success, reason=reason,
|
||
ip=_client_ip(request), user_agent=request.headers.get("User-Agent", "")[:500],
|
||
mode=mode,
|
||
))
|
||
db.flush()
|
||
|
||
|
||
# 取访客 IP 的口径统一在 deps.client_ip,这里只留一个短别名
|
||
_client_ip = client_ip
|
||
|
||
|
||
@router.get("/captcha")
|
||
def login_captcha() -> dict[str, Any]:
|
||
"""登录页验证码:口令要拿去问 Hub 时才需要,Hub 那侧确实是算术题 SVG。
|
||
|
||
``required=false`` 有两种含义——本系统压根不问 Hub(``login_mode`` 是 local/sso 或
|
||
Hub 没开),以及问不到验证码(这一种带 ``warning``)。后者不挡登录:真需要验证码时
|
||
Hub 会当场拒,接口回 ``captcha_required``,前端那时再取一张并把框亮出来。
|
||
"""
|
||
if not settings.hub.hub_password_login:
|
||
return ok({"required": False, "captchaId": "", "image": "", "question": ""})
|
||
try:
|
||
payload = hub_api.fetch_captcha()
|
||
except hub_api.HubError as exc:
|
||
logger.warning("取登录验证码失败:%s", exc)
|
||
return ok({"required": False, "captchaId": "", "image": "", "question": "",
|
||
"warning": str(exc)})
|
||
return ok({"required": True, **payload})
|
||
|
||
|
||
@router.post("/refresh")
|
||
def refresh(body: RefreshBody, db: DbSession) -> dict[str, Any]:
|
||
try:
|
||
payload = decode_token(body.refreshToken, expect="refresh")
|
||
except TokenError as exc:
|
||
raise ApiError("invalid_token", str(exc), http_status=401) from exc
|
||
account = db.get(Account, int(payload.get("sub") or 0))
|
||
if account is None or account.is_deleted or not Status.is_active(account.status):
|
||
raise ApiError("invalid_token", "账号不可用,请重新登录", http_status=401)
|
||
if account.password_updated_at:
|
||
issued_at = payload.get("iat") or 0
|
||
if account.password_updated_at.timestamp() > float(issued_at):
|
||
raise ApiError("invalid_token", "口令已修改,请重新登录", http_status=401)
|
||
return ok(issue_tokens(account.id, account.account))
|
||
|
||
|
||
@router.get("/me")
|
||
def me(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
context = current.permission
|
||
return ok({
|
||
"user": profile_payload(db, current.account),
|
||
"permissions": ["*"] if context.is_system_admin else sorted(context.codes),
|
||
"roles": [{"id": role.id, "code": role.code, "name": role.name} for role in context.roles],
|
||
"menus": permissions.menu_tree(db, context),
|
||
"fieldMasks": context.field_masks,
|
||
})
|
||
|
||
|
||
@router.get("/menus")
|
||
def menus(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
return ok(permissions.menu_tree(db, current.permission))
|
||
|
||
|
||
@router.put("/password")
|
||
def change_password(body: PasswordBody, db: DbSession, account: CurrentUser) -> dict[str, Any]:
|
||
if account.source == "hub" and settings.hub.enabled:
|
||
raise ApiError("hub_account", "统一身份账号的口令请到统一身份平台修改")
|
||
if account.password_hash and not verify_password(body.oldPassword, account.password_hash):
|
||
raise ApiError("bad_password", "原口令不正确")
|
||
problem = password_policy_error(body.newPassword)
|
||
if problem:
|
||
raise ApiError("weak_password", problem)
|
||
account.password_hash = hash_password(body.newPassword)
|
||
account.password_updated_at = datetime.now()
|
||
db.add(OperationLog(account_id=account.id, account_name=account.display_name,
|
||
action="change_password", object_type="account", object_id=str(account.id)))
|
||
db.commit()
|
||
return ok({"changed": True})
|
||
|
||
|
||
@router.post("/logout")
|
||
def logout(account: CurrentUser) -> dict[str, Any]:
|
||
# 无状态令牌:前端删掉本地令牌即可。真正的即时吊销靠改口令/停用账号。
|
||
return ok({"loggedOut": True})
|
||
|
||
|
||
@router.get("/sso/status")
|
||
def sso_status(request: Request) -> dict[str, Any]:
|
||
"""前端据此决定登录页长什么样、"前往统一门户"该把人送去哪。
|
||
|
||
``localPasswordAllowed=false`` 时登录页要撤掉口令表单,只留"从统一门户进入":
|
||
跳转链接只能由门户签发(``POST /auth/apps/{code}/launch`` 要用户在 Hub 的登录态),
|
||
本系统自己造不出这张票,所以这里不给 authorizeUrl,只给状态与门户地址。
|
||
|
||
``callbackUrl`` 是管理员要去 Hub 后台登记的那一条,随请求地址现算,换部署不用改代码。
|
||
"""
|
||
return ok({
|
||
"enabled": settings.hub.sso_configured,
|
||
"hubEnabled": settings.hub.enabled,
|
||
"passwordLoginAllowed": settings.hub.password_login_allowed,
|
||
"hubPasswordLogin": settings.hub.hub_password_login,
|
||
"localPasswordAllowed": settings.hub.local_password_login_allowed,
|
||
"loginMode": settings.hub.mode,
|
||
"hubBaseUrl": settings.hub.base_url if settings.hub.enabled else "",
|
||
"portalUrl": settings.hub.portal_base_url if settings.hub.enabled else "",
|
||
"appCode": settings.hub.app_code,
|
||
"missing": _sso_missing(),
|
||
**sso_handoff.advertised_urls(request),
|
||
**sso_handoff.view(),
|
||
})
|
||
|
||
|
||
def _sso_missing() -> list[str]:
|
||
"""免登三件套缺哪几项,直接点名;对接文档说"配不齐就等于没开"。"""
|
||
missing: list[str] = []
|
||
if not settings.hub.enabled:
|
||
missing.append("hub.enabled")
|
||
if not settings.hub.base_url:
|
||
missing.append("hub.base_url")
|
||
if not settings.hub.app_code:
|
||
missing.append("hub.app_code")
|
||
if not settings.hub.integration_key:
|
||
missing.append("hub.integration_key")
|
||
return missing
|
||
|
||
|
||
@router.post("/sso/state")
|
||
def sso_begin(request: Request, response: Response) -> dict[str, Any]:
|
||
"""发起免登:写一条随机 ``state`` 到 HttpOnly Cookie,把 state 与门户地址给前端。
|
||
|
||
前端拿到 state 后把用户送回统一门户,用户在门户里点本系统卡片,Hub 带着 ``ticket``
|
||
(以及它收到的 ``state``)把浏览器跳回来。文档要求 state 由下游服务端生成并保管、
|
||
落地时精确比对,用来挡会话固定与票据注入——所以值放服务端下发的 HttpOnly Cookie,
|
||
不放 localStorage、不放地址栏,见 :mod:`app.service.sso_state`。
|
||
"""
|
||
missing = _sso_missing()
|
||
if missing:
|
||
raise ApiError("sso_disabled", f"统一门户免登未启用,缺少:{'、'.join(missing)}",
|
||
http_status=400)
|
||
value = sso_state.issue_state(response, secure=sso_state.is_https(request))
|
||
return ok({
|
||
"state": value,
|
||
"portalUrl": settings.hub.portal_base_url,
|
||
"appCode": settings.hub.app_code,
|
||
"ttlSeconds": sso_state.STATE_TTL_SECONDS,
|
||
})
|
||
|
||
|
||
class TicketBody(BaseModel):
|
||
ticket: str = ""
|
||
state: str = ""
|
||
|
||
|
||
class ExchangeBody(BaseModel):
|
||
code: str = ""
|
||
|
||
|
||
#: 免登失败的稳定原因码。回调 302 回落地页时只透传这一批,表外的一律收进
|
||
#: ``sso_failed``,免得后端的中文句子绕过前端语言包直接上界面。
|
||
LANDING_REASONS = frozenset({
|
||
"sso_disabled",
|
||
"ticket_missing",
|
||
"ticket_invalid",
|
||
"ticket_expired",
|
||
"ticket_audience_mismatch",
|
||
"user_inactive",
|
||
"sso_state_rejected",
|
||
"hub_key_rejected",
|
||
"hub_app_forbidden",
|
||
"hub_app_not_found",
|
||
"hub_no_subject",
|
||
"hub_unavailable",
|
||
"account_disabled",
|
||
"account_not_provisioned",
|
||
})
|
||
|
||
#: 落地地址上带着一性次短码,不能被浏览器或中间代理缓存了重复使用
|
||
_NO_STORE = {"Cache-Control": "no-store", "Pragma": "no-cache"}
|
||
|
||
logger = logging.getLogger("pms.hub")
|
||
|
||
|
||
@router.post("/sso/ticket")
|
||
def sso_ticket_login(body: TicketBody, request: Request, response: Response,
|
||
db: DbSession) -> dict[str, Any]:
|
||
"""免登落地换本地会话(前端落地页口径):``ticket`` -> Hub 校验 -> 发本地令牌。
|
||
|
||
票据由浏览器交给前端、再由前端 POST 回来,判定全在 :func:`_person_from_ticket`,
|
||
与后端回调 ``GET /auth/sso/callback`` 走的是同一套。Hub 上把 ``launch_url`` 填成
|
||
前端路由时才用这条路;填的是后端回调就该走 ``POST /auth/sso/exchange``。
|
||
"""
|
||
account, detail = _person_from_ticket(db, request, response,
|
||
ticket=body.ticket, state=body.state)
|
||
return ok({**_issue_session(db, request, account, detail=detail, mode="sso"), "via": "hub"})
|
||
|
||
|
||
@router.get("/sso/callback")
|
||
def sso_callback(
|
||
db: DbSession,
|
||
request: Request,
|
||
ticket: str = Query("", description="统一门户跳转带来的一次性票据"),
|
||
state: str = Query("", description="发起跳转时本系统发出、门户原样带回的 state"),
|
||
redirect: str = Query("", description="免登成功后要去的站内路径"),
|
||
) -> RedirectResponse:
|
||
"""免登回调(后端落地口径):Hub 把浏览器 302 到这里,本系统当场验票。
|
||
|
||
Hub 上 ``launch_url`` / ``redirect_uris`` 填本路径(或别名 ``/sso/hub``)时,票据只在
|
||
"浏览器 -> 本系统 -> Hub" 这一趟里出现,前端 JS、浏览历史、代理日志与 Referer 都拿不到
|
||
它。验完 302 到 ``/sso#code=…``,前端再调 ``POST /auth/sso/exchange`` 换会话。
|
||
"""
|
||
return _landing(db, request, ticket=ticket, state=state, redirect=redirect)
|
||
|
||
|
||
@router.post("/sso/exchange")
|
||
def sso_exchange(body: ExchangeBody, request: Request, response: Response,
|
||
db: DbSession) -> dict[str, Any]:
|
||
"""用回调发出的一次性短码换本地会话(配 ``GET /auth/sso/callback`` 使用)。
|
||
|
||
短码必须配着回调当场下发的那条 HttpOnly Cookie 一起交回来,两者缺一律按失效处理;
|
||
用掉即作废,第二次来就是"回门户重新点一次"。出参形状与 ``POST /auth/sso/ticket``
|
||
一致,多带一个 ``redirect``:回调时带进来的站内路径,前端据此决定进哪一页。
|
||
"""
|
||
account, row = sso_handoff.redeem(db, request, response, body.code)
|
||
if not Status.is_active(account.status):
|
||
# 回调与兑换之间只有几十秒,但停用确实可能发生在这里,不能拿旧身份换会话
|
||
raise ApiError("account_disabled",
|
||
f"账号已{Status.label(account.status)},请联系管理员", http_status=403)
|
||
session = _issue_session(db, request, account, detail=row.detail or "统一门户免登进入",
|
||
mode="sso")
|
||
return ok({**session, "via": "hub", "redirect": sso_handoff.redirect_target(row)})
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 回调地址的别名:Hub 上填 /sso/hub 也接得住
|
||
# ---------------------------------------------------------------------------
|
||
|
||
#: 不带 ``/api/v1`` 前缀的回调别名。对接地带里管理员最常照对接指南的举例把 ``launch_url``
|
||
#: 写成 ``https://<本系统>/sso/hub``,那一处如果没有后端路由就只剩一张空白页,
|
||
#: 还得让人回头改 Hub 上的配置。生产同域反代把这一条也转给后端即可。
|
||
sso_alias_router = APIRouter(tags=["auth"])
|
||
|
||
|
||
@sso_alias_router.get(sso_handoff.ALIAS_PATH, include_in_schema=False)
|
||
def sso_callback_alias(
|
||
db: DbSession,
|
||
request: Request,
|
||
ticket: str = Query("", description="统一门户跳转带来的一次性票据"),
|
||
state: str = Query("", description="发起跳转时本系统发出、门户原样带回的 state"),
|
||
redirect: str = Query("", description="免登成功后要去的站内路径"),
|
||
) -> RedirectResponse:
|
||
"""``/sso/hub`` 与 ``GET /api/v1/auth/sso/callback`` 是同一个入口的两种写法。"""
|
||
return _landing(db, request, ticket=ticket, state=state, redirect=redirect)
|
||
|
||
|
||
def _landing(db: Session, request: Request, *, ticket: str, state: str,
|
||
redirect: str) -> RedirectResponse:
|
||
"""统一门户 302 落到后端:验票认人,再用一条一次性短码把人送进前端。
|
||
|
||
这是浏览器整页跳转过来的入口,出错不能回 JSON(用户只会看到一屏
|
||
``{"ok": false, ...}``),一律 302 回落地页并带上稳定原因码,由前端翻成本地化文案。
|
||
票据原值既不进 302 地址,也不写日志;本地令牌同样不上地址栏,上来的是
|
||
:mod:`app.service.sso_handoff` 那条 60 秒即失效、只能用一次、还绑着 HttpOnly Cookie
|
||
的短码。
|
||
"""
|
||
scratch = Response()
|
||
try:
|
||
account, detail = _person_from_ticket(db, request, scratch,
|
||
ticket=ticket, state=state)
|
||
except ApiError as exc:
|
||
logger.warning("免登回调被拒(%s),来源 %s", exc.code, _client_ip(request))
|
||
return _redirect(sso_handoff.landing_url(error=_landing_reason(exc.code)), scratch)
|
||
code, bind = sso_handoff.issue(db, account=account, detail=detail,
|
||
redirect=sso_handoff.safe_path(redirect))
|
||
response = _redirect(sso_handoff.landing_url(code=code), scratch)
|
||
sso_handoff.attach_cookie(response, bind, secure=sso_state.is_https(request))
|
||
logger.info("统一门户免登回调落地:%s -> 一次性短码", account.account)
|
||
return response
|
||
|
||
|
||
def _landing_reason(reason: str) -> str:
|
||
"""回调失败时能写进 302 地址的原因码:表外的一律收进 ``sso_failed``。"""
|
||
return reason if reason in LANDING_REASONS else "sso_failed"
|
||
|
||
|
||
def _redirect(location: str, scratch: Response | None = None) -> RedirectResponse:
|
||
"""发一条不缓存的 302,顺带把校验 ``state`` 时用掉的那条 Cookie 一起带出去。"""
|
||
response = RedirectResponse(location, status_code=302, headers=_NO_STORE)
|
||
if scratch is not None:
|
||
sso_state.forward_cookies(scratch, response)
|
||
return response
|
||
|
||
|
||
def _person_from_ticket(db: Session, request: Request, response: Response, *,
|
||
ticket: str, state: str) -> tuple[Account, str]:
|
||
"""免登票据 -> 本地账号。前端落地页与后端回调两条路共用这一段判定。
|
||
|
||
成了给出 ``(本地账号, 登录日志说明)``,任何一环不对都抛 :class:`ApiError`,``code``
|
||
是给前端与日志用的稳定码。几条来自对接文档的硬规定,这里逐条对上:
|
||
|
||
* 票据只在这一次服务端调用里消费,**不重试**(超时也无法判断 Hub 是否已消费);
|
||
票据原值不写日志、不进异常文本;
|
||
* ``state`` 比两层:浏览器 Cookie 一层,票据校验响应回传的那层再比一次;
|
||
* 受众(``app_code``)与 ``expires_at`` 由 :mod:`app.service.hub_api` 二次校验;
|
||
* ``user_inactive`` 就把本地账号一并停用,绝不"回落到旧会话";
|
||
* 只按 ``sub`` 建映射,``account`` 只是展示与认领线索。
|
||
"""
|
||
missing = _sso_missing()
|
||
if missing:
|
||
raise ApiError("sso_disabled", "统一门户免登未启用,请联系管理员检查 Hub 站点地址、"
|
||
"应用编码与免登应用密钥", http_status=400)
|
||
value = (ticket or "").strip()
|
||
if not value:
|
||
raise ApiError("ticket_missing", "缺少免登票据,请回到统一门户重新点击本系统",
|
||
http_status=400)
|
||
|
||
check = sso_state.check_state(request, response, state)
|
||
allowed, why = check.verdict(settings.hub.sso_state_required)
|
||
if not allowed:
|
||
logger.warning("免登被拒:state 校验未通过(%s),来源 %s", why, _client_ip(request))
|
||
raise ApiError("sso_state_rejected", f"免登校验未通过:{why}", http_status=401)
|
||
|
||
try:
|
||
identity = hub_api.verify_ticket(value, app_code=settings.hub.app_code or None)
|
||
except hub_api.TicketRejected as exc:
|
||
# 登录日志只记 reason 与 Hub 的错误码,票据原值一个字都不落
|
||
_log(db, None, f"hub:{exc.reason}", False, exc.message, request, mode="sso")
|
||
db.commit()
|
||
if exc.reason == "user_inactive":
|
||
_retire_local_session(db, exc.data)
|
||
logger.warning("免登票据校验未通过(reason=%s code=%s),来源 %s",
|
||
exc.reason, exc.code or "-", _client_ip(request))
|
||
raise ApiError(exc.reason, exc.message,
|
||
http_status=403 if exc.reason == "user_inactive" else 401) from exc
|
||
|
||
# 票据回传的 state 必须与这一趟交回来的 state 是同一条:Cookie 那一层只证明
|
||
# "地址栏里的 state 是本系统发出去的",这一层才证明"Hub 签的这张票本来就是开给
|
||
# 这个 state 的"。少了它,别人就能拿自己的票据配我们的 state,把人登成他自己。
|
||
echoed = str(identity.get("state") or "").strip()
|
||
given = (state or "").strip()
|
||
if echoed != given and (echoed or settings.hub.sso_state_required):
|
||
logger.warning("免登被拒:票据回传的 state 与%s的 state 不一致,来源 %s",
|
||
"本系统发出" if given else "地址栏", _client_ip(request))
|
||
raise ApiError("sso_state_rejected",
|
||
"免登校验未通过:票据与本次跳转不是同一次发起,请回到统一门户重新点击",
|
||
http_status=401)
|
||
|
||
sub = str(identity.get("sub") or "").strip()
|
||
account = _account_by_sub(db, sub)
|
||
if account is None:
|
||
account = _bind_hub_principal(db, sub, identity)
|
||
|
||
if account is None:
|
||
_log(db, None, sub, False, "免登被拒:无法建立账号映射", request, mode="sso")
|
||
db.commit()
|
||
raise ApiError("account_not_provisioned", "这个统一身份账号在本系统里还没有映射,"
|
||
"请联系管理员或先做一次组织人员同步", http_status=403)
|
||
if not Status.is_active(account.status):
|
||
_log(db, account.id, account.account, False, "免登被拒:账号不可用", request, mode="sso")
|
||
db.commit()
|
||
raise ApiError("account_disabled",
|
||
f"账号已{Status.label(account.status)},请联系管理员", http_status=403)
|
||
|
||
logger.info("统一门户免登校验通过:%s(sub=%s)", account.account, sub)
|
||
return account, (
|
||
f"统一门户免登进入(app={identity.get('app_code') or settings.hub.app_code},sub={sub})"
|
||
)
|
||
|
||
|
||
def _account_from_hub(db: Session, principal: dict[str, Any], submitted: str,
|
||
request: Request) -> Account:
|
||
"""统一身份认了这个账号 -> 本地账号:先按 Hub 主键,其次按账号,都没有就当场建号。
|
||
|
||
与免登那条路共用 :func:`_bind_hub_principal` -> ``org_sync._sync_people`` 那套建号
|
||
规则,两条路各写一份"同名撞号怎么办"迟早对不上。多出来的一步是按账号认领:这条路
|
||
是本人亲自在本系统页面上报了账号名并过了 Hub 的口令校验,把还没绑过主键的同名本地
|
||
账号认下来是安全的;免登那条路不行,票据里只有 ``sub``,账号名只是 Hub 顺带下发的
|
||
展示值,拿它认人等于允许别人用票据把自己登成别人。
|
||
"""
|
||
sub = str(principal.get("sub") or "").strip()
|
||
if not sub and principal.get("access_token"):
|
||
# 极少数部署登录响应里不带用户主键,拿刚拿到的令牌问一次 /auth/me 补上;
|
||
# 问不到就退回账号名那条路,别把已经验过口令的人挡在门外。
|
||
sub = _sub_from_access_token(str(principal["access_token"]))
|
||
|
||
account = _account_by_sub(db, sub)
|
||
if account is None:
|
||
account, refused = _claim_hub_account_by_name(db, sub, principal, submitted)
|
||
if refused:
|
||
_log(db, None, submitted or sub, False, "统一身份校验通过,但账号主键与别人冲突", request,
|
||
mode="hub")
|
||
db.commit()
|
||
raise ApiError("account_identity_conflict",
|
||
"这个账号名在本系统里已经绑定了另一个统一身份主键,"
|
||
"请联系管理员核对后再登录", http_status=403)
|
||
if account is None:
|
||
account = _bind_hub_principal(db, sub, principal)
|
||
if account is None:
|
||
_log(db, None, submitted or sub, False, "统一身份校验通过,但无法建立账号映射", request,
|
||
mode="hub")
|
||
db.commit()
|
||
raise ApiError("account_not_provisioned",
|
||
"统一身份已经认了这个账号,但本系统还没有它的映射:"
|
||
"请先在「统一身份同步」跑一次人员同步,或联系管理员建号",
|
||
http_status=403)
|
||
|
||
_adopt_hub_identity(db, account, sub, principal)
|
||
return account
|
||
|
||
|
||
def _sub_from_access_token(token: str) -> str:
|
||
"""用登录拿到的令牌问一次 ``/auth/me``,只为把用户主键补全。"""
|
||
try:
|
||
me = hub_api.fetch_me(token)
|
||
except hub_api.HubError as exc:
|
||
logger.warning("统一身份登录响应没有主键,问 /auth/me 也没问到:%s", exc)
|
||
return ""
|
||
for key in ("user_id", "id", "sub"):
|
||
value = me.get(key)
|
||
if value not in (None, ""):
|
||
return str(value).strip()
|
||
return ""
|
||
|
||
|
||
def _claim_hub_account_by_name(db: Session, sub: str, principal: dict[str, Any],
|
||
submitted: str) -> tuple[Account | None, bool]:
|
||
"""按账号名认领本地已有账号,返回 ``(账号, 是否因主键冲突而拒)``。
|
||
|
||
主键只补空、不覆盖:把一个已经绑着别人主键的行改过来,等于把两个人的权限、待办、
|
||
流程历史并成一条,所以这里直接拒,也不再往下走建号那条路——悄悄建一条
|
||
``xxx_hubNNN`` 的影子账号放人进来,是更难被发现的一种并号。
|
||
"""
|
||
wanted = [name for name in (str(principal.get("account") or "").strip(), submitted) if name]
|
||
for name in dict.fromkeys(wanted):
|
||
account = db.execute(
|
||
select(Account).where(Account.account == name, Account.is_deleted.is_(False))
|
||
).scalars().first()
|
||
if account is None:
|
||
continue
|
||
if account.hub_user_id and sub.isdigit() and account.hub_user_id != int(sub):
|
||
logger.warning("账号 %s 本地绑的是 Hub 主键 %s,本次登录却是 %s,不认领",
|
||
account.account, account.hub_user_id, sub)
|
||
return None, True
|
||
logger.info("统一身份登录认领本地账号 %s(sub=%s)", account.account, sub or "-")
|
||
return account, False
|
||
return None, False
|
||
|
||
|
||
def _adopt_hub_identity(db: Session, account: Account, sub: str,
|
||
principal: dict[str, Any]) -> None:
|
||
"""本人刚在统一身份验过口令,这一行从这次登录起交给 Hub 口径。
|
||
|
||
只补空、不改名、不动状态:账号改名要连着审批岗位、共享名单一起搬,那是同步的活;
|
||
状态由同步与免登停用那条路管,这里把停用的人"救活"是最坏的一种体贴。
|
||
"""
|
||
changed = False
|
||
if sub.isdigit() and not account.hub_user_id:
|
||
account.hub_user_id = int(sub)
|
||
changed = True
|
||
elif sub.isdigit() and account.hub_user_id != int(sub):
|
||
logger.warning("账号 %s 本地绑的是 Hub 主键 %s,本次登录却是 %s,保持不动,请人工核对",
|
||
account.account, account.hub_user_id, sub)
|
||
if account.source != AccountSource.HUB:
|
||
account.source = AccountSource.HUB
|
||
changed = True
|
||
if changed:
|
||
db.flush()
|
||
|
||
|
||
def _account_by_sub(db: Session, sub: str) -> Account | None:
|
||
"""按 Hub 主键(票据里的 ``sub``)找本地账号——文档规定只以 ``sub`` 建映射。"""
|
||
if not sub.isdigit():
|
||
return None
|
||
return db.execute(
|
||
select(Account).where(Account.hub_user_id == int(sub), Account.is_deleted.is_(False))
|
||
).scalars().first()
|
||
|
||
|
||
def _retire_local_session(db: Session, data: dict[str, Any]) -> None:
|
||
"""Hub 说这个人停用了:本地账号就地停用,绝不"回落到旧会话"。
|
||
|
||
本系统的访问令牌是无状态 JWT,不存服务端会话,所以这里能做的是把账号停用——
|
||
``deps.current_account`` 每个请求都会重新查状态,停用即刻生效,旧令牌立刻没用。
|
||
"""
|
||
account = _account_by_sub(db, str((data or {}).get("sub") or "").strip())
|
||
if account is None or account.status == Status.DISABLED:
|
||
return
|
||
account.status = Status.DISABLED
|
||
db.commit()
|
||
logger.info("统一门户已停用 %s,本地账号同步置为停用", account.account)
|
||
|
||
|
||
def _bind_hub_principal(db: Session, sub: str, principal: dict[str, Any]) -> Account | None:
|
||
"""首次免登时按 ``sub`` 建账号。
|
||
|
||
文档写死"只以 sub 建立映射,禁止用 display_name 或 email 自动合并账号",所以这里
|
||
不看姓名、不看邮箱;本地已经占着同名账号的人也不抢,走 org_sync 那套加后缀新建的
|
||
规则,保持两条路径行为一致。
|
||
"""
|
||
from ..service.org_sync import SyncStats, _sync_people # 复用同一段建号规则
|
||
|
||
if not sub.isdigit():
|
||
return None
|
||
status = principal.get("status")
|
||
node = {
|
||
"user_id": int(sub),
|
||
"account": str(principal.get("account") or "").strip(),
|
||
"display_name": str(principal.get("display_name") or "").strip(),
|
||
"email": str(principal.get("email") or "").strip(),
|
||
# 对端没带状态就按启用建号(刚从统一身份验过口令的人当然是活的);带了就照它写,
|
||
# 免得顺带认领到一行时把一个停用的人在这里悄悄救活。
|
||
"status": 1 if status is None else Status.normalize(status),
|
||
}
|
||
if not node["account"]:
|
||
return None
|
||
_sync_people(db, [node], {}, SyncStats())
|
||
db.flush()
|
||
return db.execute(
|
||
select(Account).where(Account.hub_user_id == node["user_id"])
|
||
).scalars().first()
|
||
|
||
|
||
@router.get("/hub/status")
|
||
def hub_status(request: Request, db: DbSession) -> dict[str, Any]:
|
||
"""同步与免登的运行态。
|
||
|
||
``sso`` 这一段是给人抄进 Hub 后台的:缺哪几项、回调地址是哪一条、落地页在哪。
|
||
对接文档里"配不齐就等于没开"最坑人的地方就是它不报错,只是安静地不生效。
|
||
"""
|
||
payload = org_sync.status_payload(db)
|
||
payload["sso"] = {
|
||
"enabled": settings.hub.sso_configured,
|
||
"missing": _sso_missing(),
|
||
"appCode": settings.hub.app_code,
|
||
"portalUrl": settings.hub.portal_base_url,
|
||
"stateRequired": settings.hub.sso_state_required,
|
||
**sso_handoff.view(),
|
||
**sso_handoff.advertised_urls(request),
|
||
}
|
||
return ok(payload)
|
||
|
||
|
||
def profile_payload(db, account: Account) -> dict[str, Any]:
|
||
identity = db.execute(
|
||
select(AccountIdentity, OrgUnit.name)
|
||
.join(OrgUnit, OrgUnit.id == AccountIdentity.org_unit_id)
|
||
.where(AccountIdentity.account_id == account.id)
|
||
.order_by(AccountIdentity.is_default.desc())
|
||
.limit(1)
|
||
).first()
|
||
return {
|
||
"id": account.id,
|
||
"account": account.account,
|
||
"displayName": account.display_name or account.account,
|
||
"empCode": account.emp_code,
|
||
"email": account.email,
|
||
"telephone": account.telephone,
|
||
"avatarUrl": account.avatar_url,
|
||
"orgUnitId": account.org_unit_id,
|
||
"orgUnitName": account.org_unit_name,
|
||
"identityOrgName": identity[1] if identity else account.org_unit_name,
|
||
"positionId": account.position_id,
|
||
"positionName": account.position.name if account.position else "",
|
||
"isSystemAdmin": account.is_system_admin,
|
||
"source": account.source,
|
||
"sourceLabel": "统一身份" if account.source == "hub" else "本地",
|
||
"status": account.status,
|
||
"statusLabel": Status.label(account.status),
|
||
"lastLoginAt": account.last_login_at.isoformat(sep=" ", timespec="seconds") if account.last_login_at else "",
|
||
"workLocation": account.work_location,
|
||
}
|