fix(password): 优化修改密码相关bug
This commit is contained in:
1 parent
3837a8669e
commit
1de4b78181
5 files changed
+344
-38
No files matched your search
+102
-8
@@ -16,6 +16,7 @@ import hmac
|
|||||||
import base64
|
import base64
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
|
import ast
|
||||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||||
user_bp = Blueprint('user', __name__)
|
user_bp = Blueprint('user', __name__)
|
||||||
_WECOM_ACCESS_TOKEN_CACHE = {'token': None, 'expires_at': None}
|
_WECOM_ACCESS_TOKEN_CACHE = {'token': None, 'expires_at': None}
|
||||||
@@ -185,7 +186,7 @@ def _casdoor_exchange_code(code: str, redirect_uri: str):
|
|||||||
resp = requests.post(token_endpoint, data=payload, timeout=8)
|
resp = requests.post(token_endpoint, data=payload, timeout=8)
|
||||||
data = resp.json() or {}
|
data = resp.json() or {}
|
||||||
if not resp.ok or not data.get('access_token'):
|
if not resp.ok or not data.get('access_token'):
|
||||||
raise RuntimeError(f'Casdoor token exchange failed: {data}')
|
_raise_casdoor_auth_error(data, context='code')
|
||||||
return data
|
return data
|
||||||
|
|
||||||
def _casdoor_refresh_token(refresh_token: str):
|
def _casdoor_refresh_token(refresh_token: str):
|
||||||
@@ -195,7 +196,7 @@ def _casdoor_refresh_token(refresh_token: str):
|
|||||||
resp = requests.post(token_endpoint, data=payload, timeout=8)
|
resp = requests.post(token_endpoint, data=payload, timeout=8)
|
||||||
data = resp.json() or {}
|
data = resp.json() or {}
|
||||||
if not resp.ok or not data.get('access_token'):
|
if not resp.ok or not data.get('access_token'):
|
||||||
raise RuntimeError(f'Casdoor refresh failed: {data}')
|
_raise_casdoor_auth_error(data, context='refresh')
|
||||||
return data
|
return data
|
||||||
|
|
||||||
def _casdoor_userinfo(access_token: str):
|
def _casdoor_userinfo(access_token: str):
|
||||||
@@ -222,7 +223,7 @@ def _casdoor_password_login(username: str, password: str):
|
|||||||
resp = requests.post(token_endpoint, data=payload, timeout=8)
|
resp = requests.post(token_endpoint, data=payload, timeout=8)
|
||||||
data = resp.json() or {}
|
data = resp.json() or {}
|
||||||
if not resp.ok or not data.get('access_token'):
|
if not resp.ok or not data.get('access_token'):
|
||||||
raise RuntimeError(f'Casdoor password login failed: {data}')
|
_raise_casdoor_auth_error(data, context='password')
|
||||||
return data
|
return data
|
||||||
|
|
||||||
def _is_casdoor_login_mode() -> bool:
|
def _is_casdoor_login_mode() -> bool:
|
||||||
@@ -258,12 +259,90 @@ def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, ne
|
|||||||
except ValueError:
|
except ValueError:
|
||||||
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
|
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||||
if data.get('status') != 'ok':
|
if data.get('status') != 'ok':
|
||||||
raise RuntimeError(data.get('msg') or f'Casdoor set-password failed: {data}')
|
_raise_casdoor_set_password_error(data)
|
||||||
|
|
||||||
def _is_casdoor_password_error(message: str) -> bool:
|
def _is_casdoor_password_error(message: str) -> bool:
|
||||||
lowered = (message or '').lower()
|
lowered = (message or '').lower()
|
||||||
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
|
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
|
||||||
|
|
||||||
|
def _is_casdoor_user_missing_error(message: str) -> bool:
|
||||||
|
lowered = (message or '').lower()
|
||||||
|
return (
|
||||||
|
"doesn't exist" in lowered
|
||||||
|
or 'does not exist' in lowered
|
||||||
|
or 'user not found' in lowered
|
||||||
|
or 'no such user' in lowered
|
||||||
|
)
|
||||||
|
|
||||||
|
def _raise_casdoor_user_not_in_idp(source=None) -> None:
|
||||||
|
data = _extract_casdoor_error_payload(source)
|
||||||
|
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||||
|
raise AppError(
|
||||||
|
code='CASDOOR_USER_NOT_IN_IDP',
|
||||||
|
message='Your account has not been registered in the authentication system. Please contact the administrator.',
|
||||||
|
http_status=409,
|
||||||
|
details={'technical': msg_text or str(source or '')[:300]},
|
||||||
|
)
|
||||||
|
|
||||||
|
def _extract_casdoor_error_payload(source) -> dict:
|
||||||
|
if isinstance(source, dict):
|
||||||
|
return source
|
||||||
|
text = str(source or '')
|
||||||
|
match = re.search(r'\{.*\}', text, re.DOTALL)
|
||||||
|
if match:
|
||||||
|
try:
|
||||||
|
parsed = ast.literal_eval(match.group(0))
|
||||||
|
if isinstance(parsed, dict):
|
||||||
|
return parsed
|
||||||
|
except (SyntaxError, ValueError):
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
parsed = json.loads(text)
|
||||||
|
if isinstance(parsed, dict):
|
||||||
|
return parsed
|
||||||
|
except (json.JSONDecodeError, TypeError):
|
||||||
|
pass
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _raise_casdoor_auth_error(source, *, context: str, status_code: int = 401) -> None:
|
||||||
|
"""
|
||||||
|
Map Casdoor OAuth/API failures to stable business error codes for frontend i18n.
|
||||||
|
context: password | verify | code | refresh
|
||||||
|
"""
|
||||||
|
data = _extract_casdoor_error_payload(source)
|
||||||
|
raw = str(source or '')
|
||||||
|
oauth_error = _clean_str(data.get('error')).lower()
|
||||||
|
if not oauth_error and 'invalid_grant' in raw.lower():
|
||||||
|
oauth_error = 'invalid_grant'
|
||||||
|
if not oauth_error and 'invalid_client' in raw.lower():
|
||||||
|
oauth_error = 'invalid_client'
|
||||||
|
if oauth_error == 'invalid_grant' or _is_casdoor_password_error(raw):
|
||||||
|
if context in ('password', 'verify'):
|
||||||
|
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
|
||||||
|
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
|
||||||
|
if oauth_error in ('invalid_client', 'unauthorized_client'):
|
||||||
|
raise AppError(code='CASDOOR_CONFIG_ERROR', message='Authentication service is misconfigured. Please contact the administrator.', http_status=503, details={'casdoor_error': oauth_error})
|
||||||
|
if oauth_error == 'access_denied':
|
||||||
|
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
|
||||||
|
if 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower():
|
||||||
|
raise AppError(code='CASDOOR_CONFIG_ERROR', message='Authentication service is not configured. Please contact the administrator.', http_status=503)
|
||||||
|
if 'invalid or expired casdoor state' in raw.lower():
|
||||||
|
raise ValidationError('Invalid or expired Casdoor state')
|
||||||
|
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500])
|
||||||
|
raise AppError(code='CASDOOR_AUTH_FAILED', message='Authentication failed, please try again', http_status=status_code, details={'casdoor_error': oauth_error or None, 'technical': raw[:300]})
|
||||||
|
|
||||||
|
def _raise_casdoor_set_password_error(source) -> None:
|
||||||
|
data = _extract_casdoor_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()
|
||||||
|
if _is_casdoor_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
|
||||||
|
_raise_incorrect_current_password()
|
||||||
|
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_casdoor_user_missing_error(lowered):
|
||||||
|
_raise_casdoor_user_not_in_idp(source)
|
||||||
|
raise AppError(code='CASDOOR_SET_PASSWORD_FAILED', message='Failed to change password. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source)[:300]})
|
||||||
|
|
||||||
def _raise_incorrect_current_password():
|
def _raise_incorrect_current_password():
|
||||||
raise AppError(
|
raise AppError(
|
||||||
code='AUTH.INCORRECT_CURRENT_PASSWORD',
|
code='AUTH.INCORRECT_CURRENT_PASSWORD',
|
||||||
@@ -278,6 +357,10 @@ def _verify_current_password_for_change(user, current_password: str):
|
|||||||
_raise_incorrect_current_password()
|
_raise_incorrect_current_password()
|
||||||
try:
|
try:
|
||||||
_verify_casdoor_password(user.username, current_password)
|
_verify_casdoor_password(user.username, current_password)
|
||||||
|
except AppError as e:
|
||||||
|
if e.code == 'CASDOOR_INVALID_CREDENTIALS':
|
||||||
|
_raise_incorrect_current_password()
|
||||||
|
raise
|
||||||
except RuntimeError as e:
|
except RuntimeError as e:
|
||||||
if _is_casdoor_password_error(str(e)):
|
if _is_casdoor_password_error(str(e)):
|
||||||
_raise_incorrect_current_password()
|
_raise_incorrect_current_password()
|
||||||
@@ -289,7 +372,13 @@ def _sync_casdoor_password(username: str, current_password: str, new_password: s
|
|||||||
user_owner = _casdoor_user_owner()
|
user_owner = _casdoor_user_owner()
|
||||||
try:
|
try:
|
||||||
_casdoor_set_password(user_owner, username, current_password, new_password)
|
_casdoor_set_password(user_owner, username, current_password, new_password)
|
||||||
|
except AppError as first_error:
|
||||||
|
if first_error.code in ('CASDOOR_INVALID_CREDENTIALS', 'AUTH.INCORRECT_CURRENT_PASSWORD'):
|
||||||
|
_raise_incorrect_current_password()
|
||||||
|
raise
|
||||||
except RuntimeError as first_error:
|
except RuntimeError as first_error:
|
||||||
|
if _is_casdoor_user_missing_error(str(first_error)):
|
||||||
|
_raise_casdoor_user_not_in_idp(first_error)
|
||||||
if _is_casdoor_password_error(str(first_error)):
|
if _is_casdoor_password_error(str(first_error)):
|
||||||
_raise_incorrect_current_password()
|
_raise_incorrect_current_password()
|
||||||
try:
|
try:
|
||||||
@@ -775,9 +864,12 @@ def casdoor_password_login():
|
|||||||
except WeComLoginError:
|
except WeComLoginError:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
raise
|
raise
|
||||||
|
except AppError:
|
||||||
|
db.session.rollback()
|
||||||
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
raise UnauthorizedError(f'Casdoor password login failed: {str(e)}')
|
_raise_casdoor_auth_error(e, context='password')
|
||||||
|
|
||||||
@user_bp.route('/casdoor/authorize-url', methods=['GET'])
|
@user_bp.route('/casdoor/authorize-url', methods=['GET'])
|
||||||
def casdoor_authorize_url():
|
def casdoor_authorize_url():
|
||||||
@@ -903,10 +995,13 @@ def casdoor_login():
|
|||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
current_app.logger.warning('[casdoor_login] business_reject')
|
current_app.logger.warning('[casdoor_login] business_reject')
|
||||||
raise
|
raise
|
||||||
|
except AppError:
|
||||||
|
db.session.rollback()
|
||||||
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
current_app.logger.exception('[casdoor_login] failed state=%s redirect_uri=%s', state[:24] if state else '', redirect_uri)
|
current_app.logger.exception('[casdoor_login] failed state=%s redirect_uri=%s', state[:24] if state else '', redirect_uri)
|
||||||
raise UnauthorizedError(f'Casdoor login failed: {str(e)}')
|
_raise_casdoor_auth_error(e, context='code')
|
||||||
|
|
||||||
@user_bp.route('/casdoor/refresh', methods=['POST'])
|
@user_bp.route('/casdoor/refresh', methods=['POST'])
|
||||||
def casdoor_refresh():
|
def casdoor_refresh():
|
||||||
@@ -1460,8 +1555,7 @@ def change_password():
|
|||||||
message = str(e)
|
message = str(e)
|
||||||
if _is_casdoor_password_error(message):
|
if _is_casdoor_password_error(message):
|
||||||
_raise_incorrect_current_password()
|
_raise_incorrect_current_password()
|
||||||
current_app.logger.exception('[change_password] Casdoor failed user=%s', user.username)
|
_raise_casdoor_set_password_error(e)
|
||||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=f'Failed to change password: {message}', http_status=502, details={'error_code': 'CASDOOR_SET_PASSWORD_FAILED'})
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.api import user as user_api
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
('payload', 'context', 'expected_code'),
|
||||||
|
[
|
||||||
|
({'error': 'invalid_grant'}, 'password', 'CASDOOR_INVALID_CREDENTIALS'),
|
||||||
|
({'error': 'invalid_grant'}, 'code', 'CASDOOR_CODE_EXPIRED'),
|
||||||
|
({'error': 'invalid_client'}, 'password', 'CASDOOR_CONFIG_ERROR'),
|
||||||
|
({'error': 'access_denied'}, 'code', 'CASDOOR_ACCESS_DENIED'),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_raise_casdoor_auth_error_maps_oauth_errors(app, payload, context, expected_code):
|
||||||
|
with app.app_context():
|
||||||
|
with pytest.raises(user_api.AppError) as exc:
|
||||||
|
user_api._raise_casdoor_auth_error(payload, context=context)
|
||||||
|
assert exc.value.code == expected_code
|
||||||
|
|
||||||
|
|
||||||
|
def test_raise_casdoor_set_password_error_maps_user_missing(app):
|
||||||
|
with app.app_context():
|
||||||
|
with pytest.raises(user_api.AppError) as exc:
|
||||||
|
user_api._raise_casdoor_set_password_error({'status': 'error', 'msg': "The user: organization_HX/26050001 doesn't exist"})
|
||||||
|
assert exc.value.code == 'CASDOOR_USER_NOT_IN_IDP'
|
||||||
|
assert exc.value.http_status == 409
|
||||||
|
|
||||||
|
|
||||||
|
def test_raise_casdoor_set_password_error_maps_policy(app):
|
||||||
|
with app.app_context():
|
||||||
|
with pytest.raises(user_api.AppError) as exc:
|
||||||
|
user_api._raise_casdoor_set_password_error({'status': 'error', 'msg': 'password is too short'})
|
||||||
|
assert exc.value.code == 'CASDOOR_PASSWORD_POLICY'
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_casdoor_error_payload_from_runtime_message():
|
||||||
|
raw = "Casdoor password login failed: {'error': 'invalid_grant', 'error_description': 'wrong password'}"
|
||||||
|
payload = user_api._extract_casdoor_error_payload(raw)
|
||||||
|
assert payload.get('error') == 'invalid_grant'
|
||||||
@@ -36,6 +36,31 @@ const messages = {
|
|||||||
passwordResetEmailSent: '如果账号存在,重置链接已发送到您的邮箱。',
|
passwordResetEmailSent: '如果账号存在,重置链接已发送到您的邮箱。',
|
||||||
passwordResetRequestFailed: '请求密码重置失败',
|
passwordResetRequestFailed: '请求密码重置失败',
|
||||||
casdoorLogin: 'Login with Casdoor',
|
casdoorLogin: 'Login with Casdoor',
|
||||||
|
casdoorErrors: {
|
||||||
|
invalidCredentials: 'Incorrect username or password',
|
||||||
|
codeExpired: 'Login session expired, please sign in again',
|
||||||
|
stateExpired: 'Login session expired, please try again',
|
||||||
|
accessDenied: 'Login was cancelled or denied',
|
||||||
|
configError: 'Authentication service is unavailable. Please contact the administrator.',
|
||||||
|
authFailed: 'Authentication failed, please try again',
|
||||||
|
passwordPolicy: 'New password does not meet security requirements',
|
||||||
|
setPasswordFailed: 'Failed to change password. Please try again or contact the administrator.',
|
||||||
|
incorrectCurrentPassword: 'Current password is incorrect',
|
||||||
|
userNotInIdp: 'Your account has not been registered in the authentication system. Please contact the administrator to sync your account before changing your password.',
|
||||||
|
},
|
||||||
|
casdoorDialogTitles: {
|
||||||
|
userNotFound: 'No local account matched',
|
||||||
|
userNotInIdp: 'Account not registered in authentication system',
|
||||||
|
accountDisabled: 'Account is disabled',
|
||||||
|
sessionExpired: 'Login session expired',
|
||||||
|
configError: 'Authentication service error',
|
||||||
|
accessDenied: 'Login was not completed',
|
||||||
|
loginFailed: 'Login failed',
|
||||||
|
},
|
||||||
|
casdoorDialogDetails: {
|
||||||
|
contactAdmin: 'If the problem persists, please contact the administrator.',
|
||||||
|
retryLogin: 'Please close this dialog and sign in again.',
|
||||||
|
},
|
||||||
wecomLogin: 'Login with WeCom',
|
wecomLogin: 'Login with WeCom',
|
||||||
wecomConnecting: 'Connecting to WeCom...',
|
wecomConnecting: 'Connecting to WeCom...',
|
||||||
wecomStartFailed: 'Failed to start WeCom login',
|
wecomStartFailed: 'Failed to start WeCom login',
|
||||||
@@ -1502,6 +1527,7 @@ const messages = {
|
|||||||
newPassword: 'New Password',
|
newPassword: 'New Password',
|
||||||
confirmPassword: 'Confirm Password',
|
confirmPassword: 'Confirm Password',
|
||||||
changePassword: 'Change Password',
|
changePassword: 'Change Password',
|
||||||
|
changingPassword: 'Changing...',
|
||||||
changePasswordContactAdmin: 'Please contact the administrator to change your password.'
|
changePasswordContactAdmin: 'Please contact the administrator to change your password.'
|
||||||
},
|
},
|
||||||
feedback: {
|
feedback: {
|
||||||
@@ -1598,6 +1624,31 @@ const messages = {
|
|||||||
passwordResetEmailSent: '如果账号存在,重置链接已发送到您的邮箱。',
|
passwordResetEmailSent: '如果账号存在,重置链接已发送到您的邮箱。',
|
||||||
passwordResetRequestFailed: '请求密码重置失败',
|
passwordResetRequestFailed: '请求密码重置失败',
|
||||||
casdoorLogin: 'Casdoor 登录',
|
casdoorLogin: 'Casdoor 登录',
|
||||||
|
casdoorErrors: {
|
||||||
|
invalidCredentials: '用户名或密码错误',
|
||||||
|
codeExpired: '登录会话已过期,请重新登录',
|
||||||
|
stateExpired: '登录会话已过期,请重试',
|
||||||
|
accessDenied: '登录已取消或被拒绝',
|
||||||
|
configError: '认证服务暂不可用,请联系管理员',
|
||||||
|
authFailed: '登录失败,请稍后重试',
|
||||||
|
passwordPolicy: '新密码不符合安全要求',
|
||||||
|
setPasswordFailed: '修改密码失败,请稍后重试或联系管理员',
|
||||||
|
incorrectCurrentPassword: '当前密码不正确',
|
||||||
|
userNotInIdp: '您的账号尚未在统一认证系统中开通,请联系管理员同步账号后再修改密码。',
|
||||||
|
},
|
||||||
|
casdoorDialogTitles: {
|
||||||
|
userNotFound: '未匹配到本地账号',
|
||||||
|
userNotInIdp: '认证系统中无此账号',
|
||||||
|
accountDisabled: '账号已禁用',
|
||||||
|
sessionExpired: '登录会话已过期',
|
||||||
|
configError: '认证服务异常',
|
||||||
|
accessDenied: '登录未完成',
|
||||||
|
loginFailed: '登录失败',
|
||||||
|
},
|
||||||
|
casdoorDialogDetails: {
|
||||||
|
contactAdmin: '若问题持续出现,请联系管理员处理。',
|
||||||
|
retryLogin: '请关闭此窗口后重新登录。',
|
||||||
|
},
|
||||||
wecomLogin: '企业微信登录',
|
wecomLogin: '企业微信登录',
|
||||||
wecomConnecting: '正在连接企业微信...',
|
wecomConnecting: '正在连接企业微信...',
|
||||||
wecomStartFailed: '启动企业微信登录失败',
|
wecomStartFailed: '启动企业微信登录失败',
|
||||||
@@ -3044,6 +3095,7 @@ const messages = {
|
|||||||
newPassword: '新密码',
|
newPassword: '新密码',
|
||||||
confirmPassword: '确认密码',
|
confirmPassword: '确认密码',
|
||||||
changePassword: '修改密码',
|
changePassword: '修改密码',
|
||||||
|
changingPassword: '修改中...',
|
||||||
changePasswordContactAdmin: '请联系管理员修改'
|
changePasswordContactAdmin: '请联系管理员修改'
|
||||||
},
|
},
|
||||||
feedback: {
|
feedback: {
|
||||||
@@ -3129,6 +3181,31 @@ const messages = {
|
|||||||
forgotPasswordDesc: '輸入您的郵箱以重設密碼',
|
forgotPasswordDesc: '輸入您的郵箱以重設密碼',
|
||||||
findPassword: '找回密碼',
|
findPassword: '找回密碼',
|
||||||
casdoorLogin: 'Casdoor 登入',
|
casdoorLogin: 'Casdoor 登入',
|
||||||
|
casdoorErrors: {
|
||||||
|
invalidCredentials: '用戶名或密碼錯誤',
|
||||||
|
codeExpired: '登入會話已過期,請重新登入',
|
||||||
|
stateExpired: '登入會話已過期,請重試',
|
||||||
|
accessDenied: '登入已取消或被拒絕',
|
||||||
|
configError: '認證服務暫不可用,請聯繫管理員',
|
||||||
|
authFailed: '登入失敗,請稍後重試',
|
||||||
|
passwordPolicy: '新密碼不符合安全要求',
|
||||||
|
setPasswordFailed: '修改密碼失敗,請稍後重試或聯繫管理員',
|
||||||
|
incorrectCurrentPassword: '當前密碼不正確',
|
||||||
|
userNotInIdp: '您的賬號尚未在統一認證系統中開通,請聯繫管理員同步賬號後再修改密碼。',
|
||||||
|
},
|
||||||
|
casdoorDialogTitles: {
|
||||||
|
userNotFound: '未匹配到本地賬號',
|
||||||
|
userNotInIdp: '認證系統中無此賬號',
|
||||||
|
accountDisabled: '賬號已禁用',
|
||||||
|
sessionExpired: '登入會話已過期',
|
||||||
|
configError: '認證服務異常',
|
||||||
|
accessDenied: '登入未完成',
|
||||||
|
loginFailed: '登入失敗',
|
||||||
|
},
|
||||||
|
casdoorDialogDetails: {
|
||||||
|
contactAdmin: '若問題持續出現,請聯繫管理員處理。',
|
||||||
|
retryLogin: '請關閉此窗口後重新登入。',
|
||||||
|
},
|
||||||
wecomLogin: '企業微信登錄',
|
wecomLogin: '企業微信登錄',
|
||||||
wecomConnecting: '正在連接企業微信...',
|
wecomConnecting: '正在連接企業微信...',
|
||||||
wecomStartFailed: '啟動企業微信登錄失敗',
|
wecomStartFailed: '啟動企業微信登錄失敗',
|
||||||
@@ -4380,6 +4457,7 @@ const messages = {
|
|||||||
newPassword: '新密碼',
|
newPassword: '新密碼',
|
||||||
confirmPassword: '確認密碼',
|
confirmPassword: '確認密碼',
|
||||||
changePassword: '修改密碼',
|
changePassword: '修改密碼',
|
||||||
|
changingPassword: '修改中...',
|
||||||
changePasswordContactAdmin: '請聯繫管理員修改'
|
changePasswordContactAdmin: '請聯繫管理員修改'
|
||||||
},
|
},
|
||||||
feedback: {
|
feedback: {
|
||||||
@@ -4465,6 +4543,31 @@ const messages = {
|
|||||||
forgotPasswordDesc: 'กรอกอีเมลเพื่อรีเซ็ตรหัสผ่าน',
|
forgotPasswordDesc: 'กรอกอีเมลเพื่อรีเซ็ตรหัสผ่าน',
|
||||||
findPassword: 'ค้นหารหัสผ่าน',
|
findPassword: 'ค้นหารหัสผ่าน',
|
||||||
casdoorLogin: 'เข้าสู่ระบบด้วย Casdoor',
|
casdoorLogin: 'เข้าสู่ระบบด้วย Casdoor',
|
||||||
|
casdoorErrors: {
|
||||||
|
invalidCredentials: 'ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง',
|
||||||
|
codeExpired: 'เซสชันการเข้าสู่ระบบหมดอายุแล้ว กรุณาเข้าสู่ระบบใหม่',
|
||||||
|
stateExpired: 'เซสชันการเข้าสู่ระบบหมดอายุแล้ว กรุณาลองใหม่',
|
||||||
|
accessDenied: 'การเข้าสู่ระบบถูกยกเลิกหรือถูกปฏิเสธ',
|
||||||
|
configError: 'บริการยืนยันตัวตนไม่พร้อมใช้งาน กรุณาติดต่อผู้ดูแลระบบ',
|
||||||
|
authFailed: 'เข้าสู่ระบบไม่สำเร็จ กรุณาลองใหม่',
|
||||||
|
passwordPolicy: 'รหัสผ่านใหม่ไม่ตรงตามข้อกำหนดด้านความปลอดภัย',
|
||||||
|
setPasswordFailed: 'เปลี่ยนรหัสผ่านไม่สำเร็จ กรุณาลองใหม่หรือติดต่อผู้ดูแลระบบ',
|
||||||
|
incorrectCurrentPassword: 'รหัสผ่านปัจจุบันไม่ถูกต้อง',
|
||||||
|
userNotInIdp: 'บัญชีของคุณยังไม่ได้ลงทะเบียนในระบบยืนยันตัวตน กรุณาติดต่อผู้ดูแลระบบเพื่อซิงค์บัญชีก่อนเปลี่ยนรหัสผ่าน',
|
||||||
|
},
|
||||||
|
casdoorDialogTitles: {
|
||||||
|
userNotFound: 'ไม่พบบัญชีในระบบที่ตรงกัน',
|
||||||
|
userNotInIdp: 'ไม่พบบัญชีในระบบยืนยันตัวตน',
|
||||||
|
accountDisabled: 'บัญชีถูกปิดใช้งาน',
|
||||||
|
sessionExpired: 'เซสชันการเข้าสู่ระบบหมดอายุ',
|
||||||
|
configError: 'บริการยืนยันตัวตนผิดปกติ',
|
||||||
|
accessDenied: 'การเข้าสู่ระบบยังไม่สำเร็จ',
|
||||||
|
loginFailed: 'เข้าสู่ระบบไม่สำเร็จ',
|
||||||
|
},
|
||||||
|
casdoorDialogDetails: {
|
||||||
|
contactAdmin: 'หากปัญหายังคงอยู่ กรุณาติดต่อผู้ดูแลระบบ',
|
||||||
|
retryLogin: 'กรุณาปิดหน้าต่างนี้แล้วเข้าสู่ระบบใหม่',
|
||||||
|
},
|
||||||
wecomLogin: 'เข้าสู่ระบบด้วย WeCom',
|
wecomLogin: 'เข้าสู่ระบบด้วย WeCom',
|
||||||
wecomConnecting: 'กำลังเชื่อมต่อ WeCom...',
|
wecomConnecting: 'กำลังเชื่อมต่อ WeCom...',
|
||||||
wecomStartFailed: 'เริ่มต้นการเข้าสู่ระบบด้วย WeCom ไม่สำเร็จ',
|
wecomStartFailed: 'เริ่มต้นการเข้าสู่ระบบด้วย WeCom ไม่สำเร็จ',
|
||||||
@@ -5659,6 +5762,7 @@ const messages = {
|
|||||||
newPassword: 'รหัสผ่านใหม่',
|
newPassword: 'รหัสผ่านใหม่',
|
||||||
confirmPassword: 'ยืนยันรหัสผ่าน',
|
confirmPassword: 'ยืนยันรหัสผ่าน',
|
||||||
changePassword: 'เปลี่ยนรหัสผ่าน',
|
changePassword: 'เปลี่ยนรหัสผ่าน',
|
||||||
|
changingPassword: 'กำลังเปลี่ยน...',
|
||||||
changePasswordContactAdmin: 'กรุณาติดต่อผู้ดูแลระบบเพื่อเปลี่ยนรหัสผ่าน'
|
changePasswordContactAdmin: 'กรุณาติดต่อผู้ดูแลระบบเพื่อเปลี่ยนรหัสผ่าน'
|
||||||
},
|
},
|
||||||
feedback: {
|
feedback: {
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import type { BusinessError } from '../api/client';
|
||||||
|
|
||||||
|
type TranslateFn = (key: string, params?: Record<string, unknown>) => string;
|
||||||
|
|
||||||
|
function cleanText(value: unknown): string {
|
||||||
|
return typeof value === 'string' ? value.trim() : String(value ?? '').trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pickCasdoorErrorCode(err: BusinessError): string {
|
||||||
|
const code = cleanText(err.code);
|
||||||
|
if (code.startsWith('CASDOOR_') || code === 'ACCOUNT_DISABLED' || code === 'AUTH.INCORRECT_CURRENT_PASSWORD') {
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
const detailsCode = cleanText(err.details?.error_code);
|
||||||
|
if (detailsCode) return detailsCode;
|
||||||
|
const raw = cleanText(err.message).toLowerCase();
|
||||||
|
if (raw.includes('invalid or expired casdoor state')) return 'CASDOOR_STATE_EXPIRED';
|
||||||
|
if (raw.includes('invalid_grant')) return 'CASDOOR_INVALID_CREDENTIALS';
|
||||||
|
if (raw.includes("doesn't exist") || raw.includes('does not exist')) return 'CASDOOR_USER_NOT_IN_IDP';
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveCasdoorErrorMessage(err: BusinessError, t: TranslateFn): string {
|
||||||
|
const errorCode = pickCasdoorErrorCode(err);
|
||||||
|
const keyMap: Record<string, string> = {
|
||||||
|
CASDOOR_INVALID_CREDENTIALS: 'login.casdoorErrors.invalidCredentials',
|
||||||
|
CASDOOR_CODE_EXPIRED: 'login.casdoorErrors.codeExpired',
|
||||||
|
CASDOOR_STATE_EXPIRED: 'login.casdoorErrors.stateExpired',
|
||||||
|
CASDOOR_USER_NOT_FOUND: 'workspace.msg.casdoorNotMatchedContactAdmin',
|
||||||
|
ACCOUNT_DISABLED: 'login.accountDisabled',
|
||||||
|
CASDOOR_ACCESS_DENIED: 'login.casdoorErrors.accessDenied',
|
||||||
|
CASDOOR_CONFIG_ERROR: 'login.casdoorErrors.configError',
|
||||||
|
CASDOOR_AUTH_FAILED: 'login.casdoorErrors.authFailed',
|
||||||
|
CASDOOR_PASSWORD_POLICY: 'login.casdoorErrors.passwordPolicy',
|
||||||
|
CASDOOR_SET_PASSWORD_FAILED: 'login.casdoorErrors.setPasswordFailed',
|
||||||
|
CASDOOR_USER_NOT_IN_IDP: 'login.casdoorErrors.userNotInIdp',
|
||||||
|
'AUTH.INCORRECT_CURRENT_PASSWORD': 'login.casdoorErrors.incorrectCurrentPassword',
|
||||||
|
'VALIDATION.INVALID_PARAM': 'login.casdoorErrors.stateExpired',
|
||||||
|
};
|
||||||
|
const key = keyMap[errorCode];
|
||||||
|
if (key) return t(key);
|
||||||
|
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 === 'Invalid or expired Casdoor state') return t('login.casdoorErrors.stateExpired');
|
||||||
|
return raw || t('login.casdoorErrors.authFailed');
|
||||||
|
}
|
||||||
@@ -19,6 +19,7 @@ import { useMessage } from '../composables/useMessage';
|
|||||||
import { useIsMobile } from '../composables/useIsMobile';
|
import { useIsMobile } from '../composables/useIsMobile';
|
||||||
import loginBg from '../assets/login-bg.png';
|
import loginBg from '../assets/login-bg.png';
|
||||||
|
|
||||||
|
import { resolveCasdoorErrorMessage } from '../utils/casdoor';
|
||||||
import {
|
import {
|
||||||
buildWecomLoginDialogContent,
|
buildWecomLoginDialogContent,
|
||||||
formatWecomFieldLabel,
|
formatWecomFieldLabel,
|
||||||
@@ -461,18 +462,7 @@ const handleLogin = async (event?: Event) => {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
const err = e as BusinessError;
|
const err = e as BusinessError;
|
||||||
const rawError = String(err.message || '');
|
const rawError = String(err.message || '');
|
||||||
const errorCode = String(err.code || '');
|
let errorText = resolveCasdoorErrorMessage(err, t);
|
||||||
let errorText = rawError || t('login.failed');
|
|
||||||
const loginMode = String(config.auth?.loginMode || 'casdoor').toLowerCase();
|
|
||||||
if (loginMode === 'casdoor') {
|
|
||||||
if (errorCode === 'CASDOOR_USER_NOT_FOUND') {
|
|
||||||
errorText = t('workspace.msg.casdoorNotMatchedContactAdmin');
|
|
||||||
} else if (errorCode === 'ACCOUNT_DISABLED') {
|
|
||||||
errorText = t('login.accountDisabled');
|
|
||||||
} else if (rawError.includes('invalid_grant')) {
|
|
||||||
errorText = t('login.incorrectPassword');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (rawError === 'User not found') errorText = t('login.userNotFound');
|
if (rawError === 'User not found') errorText = t('login.userNotFound');
|
||||||
if (rawError === 'Incorrect password') errorText = t('login.incorrectPassword');
|
if (rawError === 'Incorrect password') errorText = t('login.incorrectPassword');
|
||||||
if (rawError === 'Account is disabled') errorText = t('login.accountDisabled');
|
if (rawError === 'Account is disabled') errorText = t('login.accountDisabled');
|
||||||
@@ -501,8 +491,7 @@ const tryCasdoorCallbackLogin = async () => {
|
|||||||
// strict frontend equality check to avoid false negatives during rollout.
|
// strict frontend equality check to avoid false negatives during rollout.
|
||||||
const shouldStrictCheck = !!expectedState && !!state && !String(state).startsWith('hxops_casdoor_v1.');
|
const shouldStrictCheck = !!expectedState && !!state && !String(state).startsWith('hxops_casdoor_v1.');
|
||||||
if (shouldStrictCheck && state !== expectedState) {
|
if (shouldStrictCheck && state !== expectedState) {
|
||||||
// Prevent CSRF/state mismatch replay.
|
msg.error(t('login.casdoorErrors.stateExpired'));
|
||||||
msg.error('Invalid or expired Casdoor state');
|
|
||||||
clearWecomCallbackQuery();
|
clearWecomCallbackQuery();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -521,14 +510,8 @@ const tryCasdoorCallbackLogin = async () => {
|
|||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const err = e as BusinessError;
|
const err = e as BusinessError;
|
||||||
if (err.code === 'CASDOOR_USER_NOT_FOUND') {
|
|
||||||
msg.error(t('workspace.msg.casdoorNotMatchedNeedLocalUser'));
|
|
||||||
} else if (err.code === 'ACCOUNT_DISABLED') {
|
|
||||||
msg.error(t('workspace.msg.localAccountDisabled'));
|
|
||||||
} else {
|
|
||||||
msg.error(err.message || 'Casdoor login failed');
|
|
||||||
}
|
|
||||||
console.error(e);
|
console.error(e);
|
||||||
|
msg.error(resolveCasdoorErrorMessage(err, t));
|
||||||
clearWecomCallbackQuery();
|
clearWecomCallbackQuery();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -751,6 +734,7 @@ const activeSidebarItem = ref<'profile' | 'applications' | 'feedback' | 'updates
|
|||||||
const wsScheduleFilterInputClass = 'admin-table-filter-input text-xs py-1.5 px-2';
|
const wsScheduleFilterInputClass = 'admin-table-filter-input text-xs py-1.5 px-2';
|
||||||
const isProfileLoading = ref(false);
|
const isProfileLoading = ref(false);
|
||||||
const isProfileSaving = ref(false);
|
const isProfileSaving = ref(false);
|
||||||
|
const isChangingPassword = ref(false);
|
||||||
const isProfileEditing = ref(false);
|
const isProfileEditing = ref(false);
|
||||||
const showPasswordModal = ref(false);
|
const showPasswordModal = ref(false);
|
||||||
|
|
||||||
@@ -934,12 +918,15 @@ const saveProfile = async () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleChangePassword = async () => {
|
const handleChangePassword = async () => {
|
||||||
|
if (isChangingPassword.value) return;
|
||||||
|
|
||||||
if (passwordForm.value.new !== passwordForm.value.confirm) {
|
if (passwordForm.value.new !== passwordForm.value.confirm) {
|
||||||
msg.warning(t('profile.passwordMismatch') || 'Passwords do not match');
|
msg.warning(t('profile.passwordMismatch') || 'Passwords do not match');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
isChangingPassword.value = true;
|
||||||
await requestJson('/api/user/change-password', {
|
await requestJson('/api/user/change-password', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
@@ -953,7 +940,9 @@ const handleChangePassword = async () => {
|
|||||||
showPasswordModal.value = false;
|
showPasswordModal.value = false;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
msg.error((e as Error)?.message || t('workspace.profile.msg.changePasswordFailed'));
|
msg.error(resolveCasdoorErrorMessage(e as BusinessError, t) || t('workspace.profile.msg.changePasswordFailed'));
|
||||||
|
} finally {
|
||||||
|
isChangingPassword.value = false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -2349,12 +2338,17 @@ onBeforeUnmount(() => {
|
|||||||
<div
|
<div
|
||||||
v-if="CHANGE_PASSWORD_ENABLED && showPasswordModal"
|
v-if="CHANGE_PASSWORD_ENABLED && showPasswordModal"
|
||||||
class="dialog-overlay z-50 items-center"
|
class="dialog-overlay z-50 items-center"
|
||||||
@click.self="showPasswordModal = false"
|
|
||||||
>
|
>
|
||||||
<div class="dialog-panel max-w-md">
|
<div class="dialog-panel max-w-md">
|
||||||
<div class="dialog-header">
|
<div class="dialog-header">
|
||||||
<h3 class="section-title">{{ $t('profile.changePassword') || 'Change Password' }}</h3>
|
<h3 class="section-title">{{ $t('profile.changePassword') || 'Change Password' }}</h3>
|
||||||
<button type="button" class="btn-icon-ds" :aria-label="$t('admin.close')" @click="showPasswordModal = false">
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn-icon-ds"
|
||||||
|
:aria-label="$t('admin.close')"
|
||||||
|
:disabled="isChangingPassword"
|
||||||
|
@click="showPasswordModal = false"
|
||||||
|
>
|
||||||
<X class="w-5 h-5" />
|
<X class="w-5 h-5" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -2362,23 +2356,50 @@ onBeforeUnmount(() => {
|
|||||||
<div class="dialog-body">
|
<div class="dialog-body">
|
||||||
<div>
|
<div>
|
||||||
<label class="label-field">{{ $t('profile.currentPassword') || 'Current Password' }}</label>
|
<label class="label-field">{{ $t('profile.currentPassword') || 'Current Password' }}</label>
|
||||||
<input v-model="passwordForm.current" type="password" class="input-field mt-1" required />
|
<input
|
||||||
|
v-model="passwordForm.current"
|
||||||
|
type="password"
|
||||||
|
class="input-field mt-1"
|
||||||
|
:disabled="isChangingPassword"
|
||||||
|
required
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label class="label-field">{{ $t('profile.newPassword') || 'New Password' }}</label>
|
<label class="label-field">{{ $t('profile.newPassword') || 'New Password' }}</label>
|
||||||
<input v-model="passwordForm.new" type="password" class="input-field mt-1" required />
|
<input
|
||||||
|
v-model="passwordForm.new"
|
||||||
|
type="password"
|
||||||
|
class="input-field mt-1"
|
||||||
|
:disabled="isChangingPassword"
|
||||||
|
required
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label class="label-field">{{ $t('profile.confirmPassword') || 'Confirm Password' }}</label>
|
<label class="label-field">{{ $t('profile.confirmPassword') || 'Confirm Password' }}</label>
|
||||||
<input v-model="passwordForm.confirm" type="password" class="input-field mt-1" required />
|
<input
|
||||||
|
v-model="passwordForm.confirm"
|
||||||
|
type="password"
|
||||||
|
class="input-field mt-1"
|
||||||
|
:disabled="isChangingPassword"
|
||||||
|
required
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="dialog-footer">
|
<div class="dialog-footer">
|
||||||
<button type="button" @click="showPasswordModal = false" class="btn-secondary flex-1">
|
<button
|
||||||
|
type="button"
|
||||||
|
:disabled="isChangingPassword"
|
||||||
|
@click="showPasswordModal = false"
|
||||||
|
class="btn-secondary flex-1 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
{{ $t('profile.cancel') || 'Cancel' }}
|
{{ $t('profile.cancel') || 'Cancel' }}
|
||||||
</button>
|
</button>
|
||||||
<button type="submit" class="btn-primary flex-1">
|
<button
|
||||||
{{ $t('profile.changePassword') || 'Update' }}
|
type="submit"
|
||||||
|
:disabled="isChangingPassword"
|
||||||
|
class="btn-primary flex-1 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
{{ isChangingPassword ? $t('profile.changingPassword') : ($t('profile.changePassword') || 'Update') }}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
Reference in new issue
Block a user