fix(auth): 修改密码当新密码与旧密码相同时弹出错误,不再退出登录

This commit is contained in:
sophie committed 2026-09-08 13:32:39 +08:00
1 parent 9570197378
commit 0f8b318458
18 files changed
+247 -18

No files matched your search

+7 -1
View File
@@ -101,7 +101,7 @@ def login():
@auth_bp.post('/change-password', endpoint='change_password')
def change_password():
"""校验当前身份并同步更新本地与 Casdoor 密码。"""
"""校验当前身份并同步更新本地与 Casdoor 密码;新密码与原密码相同直接 400。"""
user = _compat._get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
@@ -110,6 +110,12 @@ def change_password():
new_password = data.get('new_password')
if not current_password or not new_password:
raise ValidationError('Current and new password are required')
if current_password == new_password:
raise AppError(
code='AUTH.PASSWORD_UNCHANGED',
message='New password must differ from the current password',
http_status=400,
)
try:
_compat._verify_current_password_for_change(user, current_password)
_compat._sync_casdoor_password(user.username, current_password, new_password)
+3
View File
@@ -324,12 +324,15 @@ def _verify_current_password_for_change(user, current_password: str):
raise
def _sync_casdoor_password(username: str, current_password: str, new_password: str):
"""将用户自助改密同步到 Casdoor;新密码未变化原样抛出,原密码错误转为 403。"""
if not _is_casdoor_configured():
return
user_owner = _casdoor_user_owner()
try:
_casdoor_set_password(user_owner, username, current_password, new_password)
except AppError as first_error:
if first_error.code == 'AUTH.PASSWORD_UNCHANGED':
raise
if first_error.code in ('CASDOOR_INVALID_CREDENTIALS', 'AUTH.INCORRECT_CURRENT_PASSWORD'):
_raise_incorrect_current_password()
raise
@@ -235,6 +235,22 @@ def create_user(data: dict[str, Any]) -> dict:
def update_user(user_id: int, data: dict[str, Any]) -> dict:
"""
更新管理端用户资料,可选同步 Casdoor 改密。
核心逻辑:先写入本地字段;新密码与当前哈希相同则直接拒绝,避免 Casdoor 返回含 old password 的文案被误判成 401。
Args:
user_id: 目标用户主键。
data: 管理端提交的字段,password 为空表示不改密。
Returns:
{'status': 'ok'}。
Raises:
NotFoundError: 用户不存在。
AppError: 邮箱非法、新密码未变化或 Casdoor 同步失败。
"""
user = db.session.get(User, user_id)
if not user:
raise NotFoundError('User not found')
@@ -259,6 +275,12 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
if 'feature_permissions' in data or 'role' in data:
permissions_payload = data.get('feature_permissions', user.feature_permissions)
user.set_feature_permissions(permissions_payload)
if new_password and user.check_password(new_password):
raise AppError(
code='AUTH.PASSWORD_UNCHANGED',
message='New password must differ from the current password',
http_status=400,
)
if new_password:
user.set_password(new_password)
if 'agent_ids' in data:
@@ -3,7 +3,7 @@ backend/app/services/auth/hxops/casdoor_user_sync.py
用途:集中实现 HXOPS 用户创建和改密到 Casdoor 的管理端同步。
依赖:Flask 配置、requests、HXOPS User 模型、公共 Casdoor 错误解析。
逻辑:管理端事务调用本模块;HTTP 失败映射为稳定 AppError,由上层决定回滚。
逻辑:管理端事务调用本模块;set-password 失败映射为稳定业务码(相同密码/原密码错误不用 401)。
"""
from __future__ import annotations
@@ -111,13 +111,57 @@ def raise_update_user_error(source) -> None:
)
def is_same_password_error(message: str) -> bool:
"""判断 Casdoor 是否因新密码与当前密码相同而拒绝改密。"""
text = message or ''
lowered = text.lower()
if any(
token in lowered
for token in (
'cannot be the same',
'must be different',
'same as the old',
'same as old password',
'identical to the old',
'identical to old',
'password unchanged',
'new password is the same',
)
):
return True
if 'new password' in lowered and 'old password' in lowered and 'same' in lowered:
return True
return '新密码' in text and '旧密码' in text and ('相同' in text or '一样' in text)
def raise_password_unchanged(source=None) -> None:
"""新密码与当前密码相同按业务校验失败返回,禁止使用 401 以免前端清会话。"""
data = extract_error_payload(source) if source is not None else {}
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
raise AppError(
code='AUTH.PASSWORD_UNCHANGED',
message='New password must differ from the current password',
http_status=400,
details={'technical': msg_text[:300]} if msg_text else {},
)
def raise_set_password_error(source) -> None:
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
"""将 Casdoor set-password 失败映射为稳定业务错误码,改密业务失败不使用会话 401。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
raw_text = msg_text or str(source or '')
lowered = raw_text.lower()
# [STEP 1] 先识别“新密码与旧密码相同”。Casdoor 文案含 old password,若后判会被误成原密码错误 401。
if is_same_password_error(raw_text):
raise_password_unchanged(source)
# [STEP 2] 原密码错误:业务 400。401 会被前端全局 fetch 包装当成登录失效并踢回登录页。
if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
raise AppError(
code='AUTH.INCORRECT_CURRENT_PASSWORD',
message='Incorrect current password',
http_status=400,
)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
if is_user_missing_error(lowered):
@@ -247,6 +247,35 @@ def test_admin_update_user_rolls_back_when_casdoor_password_fails(client, admin_
assert user.check_password('old-password')
def test_admin_update_user_rejects_unchanged_password(client, admin_headers, monkeypatch):
"""管理员提交与当前相同的密码应 400 AUTH.PASSWORD_UNCHANGED,且不调用 Casdoor。"""
user = _create_local_user('same_pw_user', 'same_pw_user@example.com')
client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test'
client.application.config['CASDOOR_CLIENT_ID'] = 'client-id'
client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret'
client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX'
casdoor_calls = {'set_password': 0}
def fake_set_password(_owner, _name, _old, _new):
casdoor_calls['set_password'] += 1
monkeypatch.setattr(casdoor_service, 'casdoor_set_password', fake_set_password)
res = client.put(
f'/api/admin/users/{user.id}',
json={'password': 'old-password'},
headers=admin_headers,
)
# 断言:相同密码按业务校验失败,不刷新 token / 不清会话。
assert res.status_code == 400
payload = res.get_json() or {}
error = payload.get('error') or {}
assert error.get('code') == 'AUTH.PASSWORD_UNCHANGED'
assert casdoor_calls['set_password'] == 0
db.session.refresh(user)
assert user.check_password('old-password')
def test_admin_update_user_provisions_missing_casdoor_user_with_password(client, admin_headers, monkeypatch):
"""
IdP 无账号且管理员改密时,应 set-password 失败后 fallback 至 add-user,不调用 update-user。
+27
View File
@@ -1,3 +1,10 @@
"""
tests/test_casdoor_errors.py
用途:校验 Casdoor 登录/改密错误文本到稳定 AppError 的映射。
依赖:app.api.user 兼容入口中的 _raise_casdoor_* 辅助函数。
逻辑:覆盖 OAuth 错误、set-password 策略/缺失用户/相同密码/原密码错误。
"""
import pytest
from app.api import user as user_api
@@ -34,6 +41,26 @@ def test_raise_casdoor_set_password_error_maps_policy(app):
assert exc.value.code == 'CASDOOR_PASSWORD_POLICY'
def test_raise_casdoor_set_password_error_maps_same_password(app):
"""Casdoor “新密码不能与旧密码相同”不得映射为 401,以免前端清会话。"""
with app.app_context():
with pytest.raises(user_api.AppError) as exc:
user_api._raise_casdoor_set_password_error(
{'status': 'error', 'msg': 'The new password cannot be the same as the old password'}
)
assert exc.value.code == 'AUTH.PASSWORD_UNCHANGED'
assert exc.value.http_status == 400
def test_raise_casdoor_set_password_error_maps_incorrect_current_as_business(app):
"""原密码错误走业务码 400,禁止 CASDOOR_INVALID_CREDENTIALS 401。"""
with app.app_context():
with pytest.raises(user_api.AppError) as exc:
user_api._raise_casdoor_set_password_error({'status': 'error', 'msg': 'incorrect current password'})
assert exc.value.code == 'AUTH.INCORRECT_CURRENT_PASSWORD'
assert exc.value.http_status == 400
def test_raise_casdoor_add_user_error_maps_policy(app):
with app.app_context():
with pytest.raises(user_api.AppError) as exc:
+28
View File
@@ -92,6 +92,34 @@ def test_change_password_local_mode(client):
def test_change_password_rejects_unchanged_password(client):
"""新密码与原密码相同时应 400,且不改哈希。"""
headers = _auth_headers(client)
res = client.post(
'/api/user/change-password',
headers=headers,
json={'current_password': 'old-password', 'new_password': 'old-password'},
)
assert res.status_code == 400
assert (res.get_json() or {}).get('error', {}).get('code') == 'AUTH.PASSWORD_UNCHANGED'
user = db.session.query(User).filter_by(username='testuser').first()
assert user.check_password('old-password')
def test_change_password_local_mode_syncs_casdoor(client, monkeypatch):
client.application.config['CASDOOR_BASE_URL'] = 'http://casdoor.test'
+1
View File
@@ -51,6 +51,7 @@
"passwordPolicy": "New password does not meet security requirements",
"setPasswordFailed": "Failed to change password. Please try again or contact the administrator.",
"incorrectCurrentPassword": "Original: current password is incorrect. New: the password you entered is incorrect; please try again.",
"passwordUnchanged": "The new password must be different from the current password.",
"userNotInIdp": "Your account has not been registered in the authentication system. Please contact the administrator to sync your account before changing your password."
},
"casdoorDialogTitles": {
+1
View File
@@ -119,6 +119,7 @@
"SHIPPING_CUSTOMER_MERGE_CONFIRMATION_INVALID": "The source customer short code for merge confirmation is incorrect.",
"AUTH_INCORRECT_PASSWORD": "Incorrect password",
"AUTH_INCORRECT_CURRENT_PASSWORD": "The current password you entered is incorrect. Please try again.",
"AUTH_PASSWORD_UNCHANGED": "The new password must be different from the current password.",
"AUTH_USER_NOT_FOUND": "User not found",
"AUTH_ACCOUNT_DISABLED": "Account is disabled",
"AUTH_CASDOOR_IDENTITY_INVALID": "Casdoor did not return a stable user identity. Check the OIDC configuration.",
+1
View File
@@ -41,6 +41,7 @@
"passwordPolicy": "รหัสผ่านใหม่ไม่ตรงตามข้อกำหนดด้านความปลอดภัย",
"setPasswordFailed": "เปลี่ยนรหัสผ่านไม่สำเร็จ กรุณาลองใหม่หรือติดต่อผู้ดูแลระบบ",
"incorrectCurrentPassword": "เดิม: รหัสผ่านปัจจุบันไม่ถูกต้อง ใหม่: รหัสผ่านที่คุณป้อนไม่ถูกต้อง โปรดลองอีกครั้ง",
"passwordUnchanged": "รหัสผ่านใหม่ต้องแตกต่างจากรหัสผ่านปัจจุบัน",
"userNotInIdp": "บัญชีของคุณยังไม่ได้ลงทะเบียนในระบบยืนยันตัวตน กรุณาติดต่อผู้ดูแลระบบเพื่อซิงค์บัญชีก่อนเปลี่ยนรหัสผ่าน"
},
"casdoorDialogTitles": {
+1
View File
@@ -119,6 +119,7 @@
"SHIPPING_CUSTOMER_MERGE_CONFIRMATION_INVALID": "รหัสย่อลูกค้าต้นทางที่ใช้ยืนยันการรวมไม่ถูกต้อง",
"AUTH_INCORRECT_PASSWORD": "รหัสผ่านไม่ถูกต้อง",
"AUTH_INCORRECT_CURRENT_PASSWORD": "รหัสผ่านเดิมที่คุณป้อนไม่ถูกต้อง โปรดลองอีกครั้ง",
"AUTH_PASSWORD_UNCHANGED": "รหัสผ่านใหม่ต้องแตกต่างจากรหัสผ่านปัจจุบัน",
"AUTH_USER_NOT_FOUND": "ไม่พบผู้ใช้",
"AUTH_ACCOUNT_DISABLED": "บัญชีถูกปิดใช้งาน",
"AUTH_CASDOOR_IDENTITY_INVALID": "Casdoor ไม่ได้ส่งคืนข้อมูลระบุตัวผู้ใช้ที่คงที่ โปรดตรวจสอบการตั้งค่า OIDC",
+1
View File
@@ -51,6 +51,7 @@
"passwordPolicy": "新密码不符合安全要求",
"setPasswordFailed": "修改密码失败,请稍后重试或联系管理员",
"incorrectCurrentPassword": "原:当前密码不正确,新:您输入的原密码有误,请重新输入",
"passwordUnchanged": "新密码不能与当前密码相同",
"userNotInIdp": "您的账号尚未在统一认证系统中开通,请联系管理员同步账号后再修改密码。"
},
"casdoorDialogTitles": {
+1
View File
@@ -119,6 +119,7 @@
"SHIPPING_CUSTOMER_MERGE_CONFIRMATION_INVALID": "合并确认的源客户简码不正确。",
"AUTH_INCORRECT_PASSWORD": "密码错误",
"AUTH_INCORRECT_CURRENT_PASSWORD": "您输入的原密码有误,请重新输入",
"AUTH_PASSWORD_UNCHANGED": "新密码不能与当前密码相同",
"AUTH_USER_NOT_FOUND": "用户不存在",
"AUTH_ACCOUNT_DISABLED": "账号已禁用",
"AUTH_CASDOOR_IDENTITY_INVALID": "Casdoor 未返回稳定用户身份,请联系管理员检查 OIDC 配置。",
+1
View File
@@ -41,6 +41,7 @@
"passwordPolicy": "新密碼不符合安全要求",
"setPasswordFailed": "修改密碼失敗,請稍後重試或聯繫管理員",
"incorrectCurrentPassword": "原:當前密碼不正確,新:您輸入的原密碼有誤,請重新輸入",
"passwordUnchanged": "新密碼不能與目前密碼相同",
"userNotInIdp": "您的賬號尚未在統一認證系統中開通,請聯繫管理員同步賬號後再修改密碼。"
},
"casdoorDialogTitles": {
+1
View File
@@ -119,6 +119,7 @@
"SHIPPING_CUSTOMER_MERGE_CONFIRMATION_INVALID": "合併確認的來源客戶簡碼不正確。",
"AUTH_INCORRECT_PASSWORD": "密碼錯誤",
"AUTH_INCORRECT_CURRENT_PASSWORD": "您輸入的原密碼有誤,請重新輸入",
"AUTH_PASSWORD_UNCHANGED": "新密碼不能與目前密碼相同",
"AUTH_USER_NOT_FOUND": "用戶不存在",
"AUTH_ACCOUNT_DISABLED": "帳號已禁用",
"AUTH_CASDOOR_IDENTITY_INVALID": "Casdoor 未返回穩定用戶身份,請聯絡管理員檢查 OIDC 設定。",
+30 -9
View File
@@ -2,7 +2,7 @@
* main.ts
* 用途:Vue 应用启动入口(pinia / router / i18n / 401 fetch 包装)。
* 依赖:App.vue、router、i18n、config、auth sync、agentTabs。
* 逻辑:挂载前设置 document.title;包装 fetch 以刷新 token 并派发未授权事件。
* 逻辑:挂载前设置 document.title;包装 fetch 以刷新 token;仅会话类 401 才派发未授权事件。
*/
import { createApp } from 'vue';
import './style.css';
@@ -12,13 +12,28 @@ import i18n from './i18n';
import { config } from './config';
import { pinia } from './app/plugins/pinia';
import { bindAuthStoreSync } from './features/auth/stores/auth.store';
import { refreshAccessToken, getAuthToken, initAuthSync } from '@/shared/utils/auth';
import { refreshAccessToken, getAuthToken, initAuthSync, isSessionUnauthorizedError } from '@/shared/utils/auth';
import { initAgentTabSync } from '@/shared/utils/agentTabs';
initAuthSync();
initAgentTabSync();
document.title = String(i18n.global.t(config.appTitleKey));
/**
* 从 401 响应 envelope 读取 error.code,供会话失效判断使用。
* 核心逻辑:clone 后再 json,避免消耗原 Response body。
* @param res - fetch 原始响应
* @returns 错误码;无法解析时为空字符串
*/
async function readApiErrorCode(res: Response): Promise<string> {
try {
const body = await res.clone().json();
return String(body?.error?.code || body?.code || '').trim();
} catch {
return '';
}
}
const _rawFetch = window.fetch.bind(window);
window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
const runFetch = (nextInit?: RequestInit) => _rawFetch(input, nextInit);
@@ -34,16 +49,22 @@ window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Res
url.includes('/api/user/casdoor/login');
const isOptionalSsoCatalogApi = /\/api\/sso\/apps(?:\?|$)/.test(url);
if (res.status === 401 && isApi && !isRefreshApi) {
const refreshed = await refreshAccessToken();
if (refreshed) {
const mergedHeaders = new Headers((reqInit && reqInit.headers) || {});
mergedHeaders.set('Authorization', `Bearer ${getAuthToken()}`);
reqInit = { ...(reqInit || {}), headers: mergedHeaders };
res = await runFetch(reqInit);
const errorCode = await readApiErrorCode(res);
if (isSessionUnauthorizedError(errorCode)) {
const refreshed = await refreshAccessToken();
if (refreshed) {
const mergedHeaders = new Headers((reqInit && reqInit.headers) || {});
mergedHeaders.set('Authorization', `Bearer ${getAuthToken()}`);
reqInit = { ...(reqInit || {}), headers: mergedHeaders };
res = await runFetch(reqInit);
}
}
}
if (res.status === 401 && isApi && !isLoginApi && !isOptionalSsoCatalogApi) {
window.dispatchEvent(new CustomEvent('hxops:unauthorized', { detail: { url, status: res.status } }));
const errorCode = await readApiErrorCode(res);
if (isSessionUnauthorizedError(errorCode)) {
window.dispatchEvent(new CustomEvent('hxops:unauthorized', { detail: { url, status: res.status } }));
}
}
} catch {
// no-op
+21 -2
View File
@@ -1,8 +1,8 @@
/**
* shared/utils/auth.ts
* 用途:统一封装登录态、记住我偏好、登录页账号密码自动回填、跨标签登出同步等认证相关本地存储能力。
* 用途:统一封装登录态、记住我偏好、登录页账号密码自动回填、跨标签登出同步,以及 401 是否表示会话失效的判断。
* 依赖:浏览器 localStorage/sessionStorage、Casdoor refresh 接口。
* 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理,既支持 30 天免登录,也支持按业务确认方案回填账号密码;首页刷新可通过 patchStoredAuthUser 就地更新功能权限。
* 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理;改密等业务 401 不得触发全局登出。
*/
export type FeaturePermissions = {
training_hr_manage?: boolean;
@@ -330,6 +330,25 @@ export const initAuthSync = (): void => {
}
};
const BUSINESS_UNAUTHORIZED_CODES = new Set([
'CASDOOR_INVALID_CREDENTIALS',
'AUTH_INCORRECT_CURRENT_PASSWORD',
'AUTH_INCORRECT_PASSWORD',
'AUTH_PASSWORD_UNCHANGED',
]);
/**
* 判断 API 401 是否表示登录会话失效,从而需要清 token 并跳转登录页。
* 核心逻辑:空错误码按会话失效处理;改密/凭据类业务码即使历史接口返回 401 也不清会话。
* @param code - 后端 envelope error.code
* @returns true 时由全局 fetch 包装派发 hxops:unauthorized
*/
export function isSessionUnauthorizedError(code?: string | null): boolean {
const raw = String(code || '').trim();
if (!raw) return true;
return !BUSINESS_UNAUTHORIZED_CODES.has(raw.replace(/\./g, '_').toUpperCase());
}
let _refreshing: Promise<string | null> | null = null;
export const refreshAccessToken = async (): Promise<string | null> => {
+24 -2
View File
@@ -1,6 +1,8 @@
/**
* shared/utils/casdoor.ts
* Casdoor OAuth 错误文案解析。
* 用途:把 Casdoor / 改密相关 BusinessError 映射为登录与个人中心可读文案。
* 依赖:BusinessError、vue-i18n t()。
* 逻辑:优先用稳定 error.code;个人中心改密与管理端用户编辑共用同一套码。
*/
import type { BusinessError } from '@/shared/api/client';
@@ -10,9 +12,20 @@ function cleanText(value: unknown): string {
return typeof value === 'string' ? value.trim() : String(value ?? '').trim();
}
/**
* 从 BusinessError 取出可映射的 Casdoor / 改密错误码。
* 核心逻辑:优先稳定 code,其次 details.error_code,最后从英文原文兜底。
* @param err - requestJson 抛出的业务错误
* @returns 用于文案映射的错误码
*/
export function pickCasdoorErrorCode(err: BusinessError): string {
const code = cleanText(err.code);
if (code.startsWith('CASDOOR_') || code === 'ACCOUNT_DISABLED' || code === 'AUTH.INCORRECT_CURRENT_PASSWORD') {
if (
code.startsWith('CASDOOR_')
|| code === 'ACCOUNT_DISABLED'
|| code === 'AUTH.INCORRECT_CURRENT_PASSWORD'
|| code === 'AUTH.PASSWORD_UNCHANGED'
) {
return code;
}
const detailsCode = cleanText(err.details?.error_code);
@@ -24,6 +37,13 @@ export function pickCasdoorErrorCode(err: BusinessError): string {
return code;
}
/**
* 将 Casdoor / 改密错误转为当前语言用户可见文案。
* 核心逻辑:按 pickCasdoorErrorCode 查 i18n;未知码回退原始 message。
* @param err - 业务错误
* @param t - vue-i18n t 函数
* @returns 用户可见错误文案
*/
export function resolveCasdoorErrorMessage(err: BusinessError, t: TranslateFn): string {
const errorCode = pickCasdoorErrorCode(err);
const keyMap: Record<string, string> = {
@@ -39,6 +59,7 @@ export function resolveCasdoorErrorMessage(err: BusinessError, t: TranslateFn):
CASDOOR_SET_PASSWORD_FAILED: 'login.casdoorErrors.setPasswordFailed',
CASDOOR_USER_NOT_IN_IDP: 'login.casdoorErrors.userNotInIdp',
'AUTH.INCORRECT_CURRENT_PASSWORD': 'login.casdoorErrors.incorrectCurrentPassword',
'AUTH.PASSWORD_UNCHANGED': 'login.casdoorErrors.passwordUnchanged',
'VALIDATION.INVALID_PARAM': 'login.casdoorErrors.stateExpired',
};
const key = keyMap[errorCode];
@@ -46,6 +67,7 @@ export function resolveCasdoorErrorMessage(err: BusinessError, t: TranslateFn):
const raw = cleanText(err.message);
if (raw === 'Incorrect username or password') return t('login.casdoorErrors.invalidCredentials');
if (raw === 'Incorrect current password') return t('login.casdoorErrors.incorrectCurrentPassword');
if (raw === 'New password must differ from the current password') return t('login.casdoorErrors.passwordUnchanged');
if (raw === 'Invalid or expired Casdoor state') return t('login.casdoorErrors.stateExpired');
return raw || t('login.casdoorErrors.authFailed');
}