fix(exception): 优化异常错误处理
This commit is contained in:
1 parent
2a036764e3
commit
14c5903aef
3 files changed
+24
-6
No files matched your search
@@ -632,15 +632,15 @@ def login():
|
||||
if not user:
|
||||
_write_login_audit('password', 'failed', username=username, reason='user_not_found')
|
||||
db.session.commit()
|
||||
raise NotFoundError('User not found')
|
||||
raise AppError(code='AUTH.USER_NOT_FOUND', message='User not found', http_status=404)
|
||||
if not user.check_password(password):
|
||||
_write_login_audit('password', 'failed', user=user, reason='incorrect_password')
|
||||
db.session.commit()
|
||||
raise UnauthorizedError('Incorrect password')
|
||||
raise AppError(code='AUTH.INCORRECT_PASSWORD', message='Incorrect password', http_status=401)
|
||||
if user.status != 'active':
|
||||
_write_login_audit('password', 'failed', user=user, reason='account_disabled')
|
||||
db.session.commit()
|
||||
raise ForbiddenError('Account is disabled')
|
||||
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
|
||||
_write_login_audit('password', 'success', user=user)
|
||||
db.session.commit()
|
||||
return jsonify(_build_login_payload(user, 'password'))
|
||||
@@ -662,6 +662,8 @@ def login():
|
||||
except (OperationalError, DatabaseError) as retry_exc:
|
||||
current_app.logger.warning('Password login retry failed: %s', retry_exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
except AppError:
|
||||
raise
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
current_app.logger.exception('Login error: %s', e)
|
||||
|
||||
@@ -100,8 +100,12 @@ def test_login_success(client):
|
||||
def test_login_fail(client):
|
||||
res = client.post('/api/user/login', json={'username': 'test1', 'password': 'wrongpassword'})
|
||||
assert res.status_code == 401
|
||||
assert 'Incorrect password' in res.get_json()['error']
|
||||
|
||||
body = res.get_json()
|
||||
assert body['error']['code'] == 'AUTH.INCORRECT_PASSWORD'
|
||||
assert 'Incorrect password' in body['error']['message']
|
||||
|
||||
res = client.post('/api/user/login', json={'username': 'nonexistent', 'password': 'password'})
|
||||
assert res.status_code == 404
|
||||
assert 'User not found' in res.get_json()['error']
|
||||
body = res.get_json()
|
||||
assert body['error']['code'] == 'AUTH.USER_NOT_FOUND'
|
||||
assert 'User not found' in body['error']['message']
|
||||
Reference in new issue
Block a user