fix: 解决本地分支不能登录

This commit is contained in:
sophie committed 2026-10-07 17:42:58 +08:00
1 parent fe5191b38a
commit abde3de71d
3 files changed
+129 -1

No files matched your search

+42 -1
View File
@@ -4,6 +4,7 @@ backend/app/services/auth/casdoor/client.py
用途:封装 Casdoor OAuth/OIDC HTTP 通信,供 HXOPS 与平级服务复制复用。
依赖:requests、CasdoorConfig、Casdoor 错误映射。
逻辑:所有 grant 和 userinfo 请求集中在此;模块不依赖 HXOPS User、数据库或业务权限。
discovery 仍可能广告 HTTPS 域名,服务端换票和 userinfo 会改写到 CASDOOR_BASE_URL。
"""
from __future__ import annotations
@@ -40,6 +41,15 @@ class CasdoorTokenResult:
return dict(self.raw)
# 仅改写后端自己调用的端点。authorization_endpoint 留给浏览器,避免把用户重定向到内网地址。
_SERVER_ENDPOINT_KEYS = (
'token_endpoint',
'userinfo_endpoint',
'jwks_uri',
'introspection_endpoint',
)
class CasdoorClient:
"""无业务模型依赖的 Casdoor OAuth/OIDC 客户端。"""
@@ -58,7 +68,13 @@ class CasdoorClient:
self._metadata_lock = Lock()
def oidc_metadata(self) -> dict[str, Any]:
"""读取并缓存 OIDC discovery 文档 10 分钟。"""
"""
读取并缓存 OIDC discovery 文档 10 分钟。
核心逻辑:先请求 CASDOOR_BASE_URL 上的 discovery。若换票、userinfo、JWKS
仍指向 AUTH_JWT_ISSUER 的 HTTPS 源,改写到 CASDOOR_BASE_URL,避开过期证书。
浏览器使用的 authorization_endpoint 保持 discovery 原值。
"""
now = datetime.now(timezone.utc)
if self._metadata and self._metadata_expires_at and self._metadata_expires_at > now:
return dict(self._metadata)
@@ -74,10 +90,35 @@ class CasdoorClient:
data = response.json() or {}
if not isinstance(data, dict):
raise RuntimeError('Casdoor OIDC metadata is invalid')
# [STEP 1] 公网证书过期时,Casdoor 仍在 discovery 里广告 HTTPS 域名。
# 后端改走已配置的 HTTP 入口,令牌 iss 仍按 AUTH_JWT_ISSUER 校验。
data = self._rewrite_server_endpoints(data)
self._metadata = data
self._metadata_expires_at = now + timedelta(minutes=10)
return dict(data)
def _rewrite_server_endpoints(self, data: dict[str, Any]) -> dict[str, Any]:
"""
把 discovery 中指向签发方源站的服务端地址改写到 CASDOOR_BASE_URL。
Args:
data: Casdoor openid-configuration JSON。
Returns:
改写 token、userinfo、jwks 后的文档。签发方与 base URL 相同时原样返回。
"""
issuer = self.config.issuer.rstrip('/')
base_url = self.config.base_url.rstrip('/')
if not issuer or not base_url or issuer == base_url:
return data
prefix = f'{issuer}/'
rewritten = dict(data)
for key in _SERVER_ENDPOINT_KEYS:
value = str(rewritten.get(key) or '').strip()
if value == issuer or value.startswith(prefix):
rewritten[key] = f'{base_url}{value[len(issuer):]}'
return rewritten
def _token_endpoint(self) -> str:
"""从 discovery 文档读取 token endpoint,缺失时安全失败。"""
endpoint = str(self.oidc_metadata().get('token_endpoint') or '').strip()
+27
View File
@@ -135,6 +135,33 @@ def test_casdoor_config_repr_does_not_expose_secret(app):
assert 'top-secret-value' not in repr(config)
def test_casdoor_server_endpoints_follow_base_url_when_issuer_uses_expired_https():
"""公网 HTTPS 证书不可用时,换票和 userinfo 改走 CASDOOR_BASE_URL,浏览器授权地址保持原域名。"""
http = FakeHttp()
http.get = lambda url, **kwargs: FakeResponse({
'issuer': 'https://auth.example.com',
'authorization_endpoint': 'https://auth.example.com/login/oauth/authorize',
'token_endpoint': 'https://auth.example.com/api/login/oauth/access_token',
'userinfo_endpoint': 'https://auth.example.com/api/userinfo',
'jwks_uri': 'https://auth.example.com/.well-known/jwks',
}) if url.endswith('/.well-known/openid-configuration') else FakeResponse({})
client = CasdoorClient(CasdoorConfig(
base_url='http://192.168.100.230:8870',
client_id='peer-client',
client_secret='peer-secret',
issuer='https://auth.example.com',
), http_session=http)
metadata = client.oidc_metadata()
# 后端换票不能再访问过期证书上的 HTTPS 域名。
assert metadata['token_endpoint'] == 'http://192.168.100.230:8870/api/login/oauth/access_token'
assert metadata['userinfo_endpoint'] == 'http://192.168.100.230:8870/api/userinfo'
assert metadata['jwks_uri'] == 'http://192.168.100.230:8870/.well-known/jwks'
# 浏览器授权仍使用 discovery 原地址。
assert metadata['authorization_endpoint'] == 'https://auth.example.com/login/oauth/authorize'
client.password_login('alice', 'user-password')
assert http.posts[0][0] == 'http://192.168.100.230:8870/api/login/oauth/access_token'
def test_casdoor_password_client_request_is_framework_independent():
"""公共客户端按配置发送 password grant,不依赖 HXOPS User 或数据库。"""
http = FakeHttp()
@@ -0,0 +1,60 @@
/**
* features/contract-payment/utils/paymentStatus.test.ts
* 用途:锁定台账阶段格子的逾期与缺日期判定,避免验收款有过期日期却不显示已逾期。
* 依赖:paymentStatus.classifyLedgerStageCell。
* 逻辑:用固定业务日覆盖验收款已逾期、质保款未到期,以及零金额阶段显示为空格。
*/
import { describe, expect, it } from 'vitest';
import { classifyLedgerStageCell } from './paymentStatus';
const TODAY = '2026-10-07';
describe('classifyLedgerStageCell', () => {
it('marks an acceptance cell overdue when its date is before today', () => {
// 验收款没有付款回写,仍要按日期依据标已逾期,和预付款、出货款同一套比较。
expect(classifyLedgerStageCell({
status: 'active',
percentage: '30',
amount: '6600.00',
due_date: '2026-09-30',
anchor_date: '2026-09-30',
}, 'acceptance', TODAY)).toBe('overdue');
});
it('marks a future warranty date as not yet due', () => {
expect(classifyLedgerStageCell({
status: 'active',
percentage: '10',
amount: '2200.00',
due_date: '2027-09-25',
anchor_date: '2026-09-30',
}, 'warranty', TODAY)).toBe('active');
});
it('asks for a stage-specific missing-date label when acceptance has no archive date', () => {
expect(classifyLedgerStageCell({
status: 'active',
percentage: '35',
amount: '52500.00',
due_date: null,
anchor_date: null,
}, 'acceptance', TODAY)).toBe('missing_date');
});
it('keeps paid prepayment as paid and a zero stage as an empty cell', () => {
expect(classifyLedgerStageCell({
status: 'paid',
percentage: '30',
amount: '6600.00',
due_date: '2026-08-12',
anchor_date: '2026-08-12',
}, 'prepayment', TODAY)).toBe('paid');
expect(classifyLedgerStageCell({
status: 'active',
percentage: '0',
amount: '0',
due_date: null,
anchor_date: null,
}, 'acceptance', TODAY)).toBe('absent');
});
});