fix(profile): 修改密码,同步修改casdoor密码
This commit is contained in:
1 parent
0bb1946b7e
commit
2d59be2f92
9 files changed
+485
-8
No files matched your search
+87
-3
@@ -225,6 +225,78 @@ def _casdoor_password_login(username: str, password: str):
|
||||
raise RuntimeError(f'Casdoor password login failed: {data}')
|
||||
return data
|
||||
|
||||
def _is_casdoor_login_mode() -> bool:
|
||||
return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor'
|
||||
|
||||
def _is_casdoor_configured() -> bool:
|
||||
if not _clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
|
||||
return False
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
return bool(base and client_id and client_secret)
|
||||
|
||||
def _casdoor_user_owner() -> str:
|
||||
owner = _clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
|
||||
if not owner:
|
||||
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
|
||||
return owner
|
||||
|
||||
def _verify_casdoor_password(username: str, password: str):
|
||||
_casdoor_password_login(username, password)
|
||||
|
||||
def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str):
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
if not base or not client_id or not client_secret:
|
||||
raise RuntimeError('Casdoor is not configured')
|
||||
url = f'{base}/api/set-password'
|
||||
resp = requests.post(url, files={'userOwner': (None, user_owner), 'userName': (None, user_name), 'oldPassword': (None, old_password), 'newPassword': (None, new_password)}, auth=(client_id, client_secret), timeout=8)
|
||||
try:
|
||||
data = resp.json() or {}
|
||||
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}')
|
||||
|
||||
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 _raise_incorrect_current_password():
|
||||
raise AppError(
|
||||
code='AUTH.INCORRECT_CURRENT_PASSWORD',
|
||||
message='Incorrect current password',
|
||||
http_status=403,
|
||||
)
|
||||
|
||||
def _verify_current_password_for_change(user, current_password: str):
|
||||
if user.check_password(current_password):
|
||||
return
|
||||
if not _is_casdoor_configured():
|
||||
_raise_incorrect_current_password()
|
||||
try:
|
||||
_verify_casdoor_password(user.username, current_password)
|
||||
except RuntimeError as e:
|
||||
if _is_casdoor_password_error(str(e)):
|
||||
_raise_incorrect_current_password()
|
||||
raise
|
||||
|
||||
def _sync_casdoor_password(username: str, current_password: str, new_password: str):
|
||||
if not _is_casdoor_configured():
|
||||
return
|
||||
user_owner = _casdoor_user_owner()
|
||||
try:
|
||||
_casdoor_set_password(user_owner, username, current_password, new_password)
|
||||
except RuntimeError as first_error:
|
||||
if _is_casdoor_password_error(str(first_error)):
|
||||
_raise_incorrect_current_password()
|
||||
try:
|
||||
_casdoor_set_password(user_owner, username, '', new_password)
|
||||
except RuntimeError:
|
||||
raise first_error
|
||||
|
||||
def _cleanup_wecom_state_cache():
|
||||
now = datetime.utcnow()
|
||||
expired = [k for k, v in _WECOM_STATE_CACHE.items() if not v or v < now]
|
||||
@@ -1362,7 +1434,10 @@ def user_profile():
|
||||
@user_bp.route('/change-password', methods=['POST'])
|
||||
def change_password():
|
||||
"""
|
||||
Change password
|
||||
Change password for the current user.
|
||||
|
||||
Verify current password against local DB and/or Casdoor, then update both stores
|
||||
to keep them in sync regardless of AUTH_LOGIN_MODE or login method.
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
@@ -1372,12 +1447,21 @@ 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 not user.check_password(current_password):
|
||||
raise ForbiddenError('Incorrect current password')
|
||||
try:
|
||||
_verify_current_password_for_change(user, current_password)
|
||||
_sync_casdoor_password(user.username, current_password, new_password)
|
||||
user.set_password(new_password)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Password changed successfully'})
|
||||
except AppError:
|
||||
raise
|
||||
except RuntimeError as e:
|
||||
db.session.rollback()
|
||||
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'})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||||
|
||||
@@ -136,6 +136,8 @@ class Config:
|
||||
# Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881.
|
||||
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
|
||||
CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE')
|
||||
# Casdoor organization (userOwner) for set-password and other management APIs.
|
||||
CASDOOR_ORGANIZATION = (os.getenv('CASDOOR_ORGANIZATION') or 'organization_HX').strip()
|
||||
# WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url).
|
||||
CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
|
||||
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
import pytest
|
||||
|
||||
from app import create_app, db
|
||||
|
||||
from app.models import User
|
||||
|
||||
from app.api import user as user_api
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
def client():
|
||||
|
||||
app = create_app('testing')
|
||||
|
||||
app.config['AUTH_LOGIN_MODE'] = 'password'
|
||||
|
||||
|
||||
|
||||
with app.test_client() as client:
|
||||
|
||||
with app.app_context():
|
||||
|
||||
db.create_all()
|
||||
|
||||
user = User(username='testuser', role='user', email='test@example.com')
|
||||
|
||||
user.set_password('old-password')
|
||||
|
||||
db.session.add(user)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
yield client
|
||||
|
||||
db.session.remove()
|
||||
|
||||
db.drop_all()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def _auth_headers(client):
|
||||
|
||||
res = client.post('/api/user/login', json={'username': 'testuser', 'password': 'old-password'})
|
||||
|
||||
data = res.get_json()
|
||||
|
||||
return {
|
||||
|
||||
'X-User-Id': str(data['id']),
|
||||
|
||||
'X-Username': data['username'],
|
||||
|
||||
'X-Role': data['role'],
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_change_password_local_mode(client):
|
||||
|
||||
headers = _auth_headers(client)
|
||||
|
||||
res = client.post(
|
||||
|
||||
'/api/user/change-password',
|
||||
|
||||
headers=headers,
|
||||
|
||||
json={'current_password': 'old-password', 'new_password': 'new-password'},
|
||||
|
||||
)
|
||||
|
||||
assert res.status_code == 200
|
||||
|
||||
|
||||
|
||||
user = db.session.query(User).filter_by(username='testuser').first()
|
||||
|
||||
assert user.check_password('new-password')
|
||||
|
||||
assert not user.check_password('old-password')
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_change_password_local_mode_syncs_casdoor(client, monkeypatch):
|
||||
|
||||
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(user_owner, user_name, old_password, new_password):
|
||||
|
||||
casdoor_calls['set_password'] += 1
|
||||
|
||||
assert user_owner == 'organization_HX'
|
||||
|
||||
assert user_name == 'testuser'
|
||||
|
||||
assert old_password == 'old-password'
|
||||
|
||||
assert new_password == 'new-password'
|
||||
|
||||
|
||||
|
||||
monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password)
|
||||
|
||||
|
||||
|
||||
headers = _auth_headers(client)
|
||||
|
||||
res = client.post(
|
||||
|
||||
'/api/user/change-password',
|
||||
|
||||
headers=headers,
|
||||
|
||||
json={'current_password': 'old-password', 'new_password': 'new-password'},
|
||||
|
||||
)
|
||||
|
||||
assert res.status_code == 200
|
||||
|
||||
assert casdoor_calls == {'set_password': 1}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_change_password_local_mode_wrong_current(client):
|
||||
|
||||
headers = _auth_headers(client)
|
||||
|
||||
res = client.post(
|
||||
|
||||
'/api/user/change-password',
|
||||
|
||||
headers=headers,
|
||||
|
||||
json={'current_password': 'wrong-password', 'new_password': 'new-password'},
|
||||
|
||||
)
|
||||
|
||||
assert res.status_code == 403
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_change_password_casdoor_mode(client, monkeypatch):
|
||||
|
||||
client.application.config['AUTH_LOGIN_MODE'] = 'casdoor'
|
||||
|
||||
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(user_owner, user_name, old_password, new_password):
|
||||
|
||||
casdoor_calls['set_password'] += 1
|
||||
|
||||
assert user_owner == 'organization_HX'
|
||||
|
||||
assert user_name == 'testuser'
|
||||
|
||||
assert old_password == 'old-password'
|
||||
|
||||
assert new_password == 'new-password'
|
||||
|
||||
|
||||
|
||||
monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password)
|
||||
|
||||
|
||||
|
||||
headers = _auth_headers(client)
|
||||
|
||||
res = client.post(
|
||||
|
||||
'/api/user/change-password',
|
||||
|
||||
headers=headers,
|
||||
|
||||
json={'current_password': 'old-password', 'new_password': 'new-password'},
|
||||
|
||||
)
|
||||
|
||||
assert res.status_code == 200
|
||||
|
||||
assert casdoor_calls == {'set_password': 1}
|
||||
|
||||
|
||||
|
||||
user = db.session.query(User).filter_by(username='testuser').first()
|
||||
|
||||
assert user.check_password('new-password')
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_change_password_accepts_casdoor_password_when_local_out_of_sync(client, monkeypatch):
|
||||
|
||||
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'
|
||||
|
||||
|
||||
|
||||
user = db.session.query(User).filter_by(username='testuser').first()
|
||||
user.set_password('stale-local-password')
|
||||
db.session.commit()
|
||||
headers = {
|
||||
'X-User-Id': str(user.id),
|
||||
'X-Username': user.username,
|
||||
'X-Role': user.role,
|
||||
}
|
||||
|
||||
def fake_verify(username, password):
|
||||
|
||||
assert username == 'testuser'
|
||||
|
||||
assert password == 'casdoor-password'
|
||||
|
||||
|
||||
|
||||
def fake_set_password(user_owner, user_name, old_password, new_password):
|
||||
|
||||
assert old_password == 'casdoor-password'
|
||||
|
||||
assert new_password == 'new-password'
|
||||
|
||||
|
||||
|
||||
monkeypatch.setattr(user_api, '_verify_casdoor_password', fake_verify)
|
||||
monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password)
|
||||
|
||||
res = client.post(
|
||||
|
||||
'/api/user/change-password',
|
||||
|
||||
headers=headers,
|
||||
|
||||
json={'current_password': 'casdoor-password', 'new_password': 'new-password'},
|
||||
|
||||
)
|
||||
|
||||
assert res.status_code == 200
|
||||
|
||||
|
||||
|
||||
user = db.session.query(User).filter_by(username='testuser').first()
|
||||
|
||||
assert user.check_password('new-password')
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_change_password_casdoor_mode_wrong_current(client, monkeypatch):
|
||||
|
||||
client.application.config['AUTH_LOGIN_MODE'] = 'casdoor'
|
||||
|
||||
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'
|
||||
|
||||
|
||||
|
||||
def fake_verify(username, password):
|
||||
|
||||
raise RuntimeError('Casdoor password login failed: invalid_grant')
|
||||
|
||||
|
||||
|
||||
monkeypatch.setattr(user_api, '_verify_casdoor_password', fake_verify)
|
||||
|
||||
|
||||
|
||||
headers = _auth_headers(client)
|
||||
|
||||
res = client.post(
|
||||
|
||||
'/api/user/change-password',
|
||||
|
||||
headers=headers,
|
||||
|
||||
json={'current_password': 'wrong-password', 'new_password': 'new-password'},
|
||||
|
||||
)
|
||||
|
||||
assert res.status_code == 403
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_change_password_casdoor_admin_override_when_old_password_mismatch(client, monkeypatch):
|
||||
|
||||
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 = []
|
||||
|
||||
|
||||
|
||||
def fake_set_password(user_owner, user_name, old_password, new_password):
|
||||
|
||||
casdoor_calls.append((old_password, new_password))
|
||||
|
||||
if old_password:
|
||||
|
||||
raise RuntimeError('Casdoor set-password failed: old password is incorrect')
|
||||
|
||||
|
||||
|
||||
monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password)
|
||||
|
||||
|
||||
|
||||
headers = _auth_headers(client)
|
||||
|
||||
res = client.post(
|
||||
|
||||
'/api/user/change-password',
|
||||
|
||||
headers=headers,
|
||||
|
||||
json={'current_password': 'old-password', 'new_password': 'new-password'},
|
||||
|
||||
)
|
||||
|
||||
assert res.status_code == 200
|
||||
|
||||
assert casdoor_calls == [('old-password', 'new-password'), ('', 'new-password')]
|
||||
|
||||
Reference in new issue
Block a user