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 json
|
||||
import re
|
||||
import ast
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
user_bp = Blueprint('user', __name__)
|
||||
_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)
|
||||
data = resp.json() or {}
|
||||
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
|
||||
|
||||
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)
|
||||
data = resp.json() or {}
|
||||
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
|
||||
|
||||
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)
|
||||
data = resp.json() or {}
|
||||
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
|
||||
|
||||
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:
|
||||
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||
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:
|
||||
lowered = (message or '').lower()
|
||||
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():
|
||||
raise AppError(
|
||||
code='AUTH.INCORRECT_CURRENT_PASSWORD',
|
||||
@@ -278,6 +357,10 @@ def _verify_current_password_for_change(user, current_password: str):
|
||||
_raise_incorrect_current_password()
|
||||
try:
|
||||
_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:
|
||||
if _is_casdoor_password_error(str(e)):
|
||||
_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()
|
||||
try:
|
||||
_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:
|
||||
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)):
|
||||
_raise_incorrect_current_password()
|
||||
try:
|
||||
@@ -775,9 +864,12 @@ def casdoor_password_login():
|
||||
except WeComLoginError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as e:
|
||||
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'])
|
||||
def casdoor_authorize_url():
|
||||
@@ -903,10 +995,13 @@ def casdoor_login():
|
||||
db.session.rollback()
|
||||
current_app.logger.warning('[casdoor_login] business_reject')
|
||||
raise
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
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'])
|
||||
def casdoor_refresh():
|
||||
@@ -1460,8 +1555,7 @@ def change_password():
|
||||
message = str(e)
|
||||
if _is_casdoor_password_error(message):
|
||||
_raise_incorrect_current_password()
|
||||
current_app.logger.exception('[change_password] Casdoor failed user=%s', user.username)
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=f'Failed to change password: {message}', http_status=502, details={'error_code': 'CASDOOR_SET_PASSWORD_FAILED'})
|
||||
_raise_casdoor_set_password_error(e)
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||||
|
||||
Reference in new issue
Block a user