From 3298ef81c86c334d6a9de36c4df11f1e7a5a6658 Mon Sep 17 00:00:00 2001 From: Christian Grothoff Date: Thu, 29 Oct 2020 00:35:22 +0100 Subject: use HTTPStatus codes instead of hard-coding numeric values, fixing one that was 305 but clearly should have been 405 --- talerbank/app/middleware.py | 3 +- talerbank/app/schemas.py | 5 +-- talerbank/app/views.py | 74 +++++++++++++++++++++++---------------------- 3 files changed, 43 insertions(+), 39 deletions(-) diff --git a/talerbank/app/middleware.py b/talerbank/app/middleware.py index a2fc586..5c9d62c 100644 --- a/talerbank/app/middleware.py +++ b/talerbank/app/middleware.py @@ -18,6 +18,7 @@ from .schemas import JSONFieldException, URLParamValidationError, InvalidSession from taler.util.amount import CurrencyMismatchError, AmountFormatError from taler.util.taler_error_codes import ErrorCode +from http import HTTPStatus LOGGER = logging.getLogger() @@ -114,5 +115,5 @@ class ExceptionMiddleware: dict(code=ErrorCode.BANK_UNMANAGED_EXCEPTION, hint="unexpected exception", exception=str(exception)), - status=500) + status=HTTPStatus.INTERNAL_SERVER_ERROR) diff --git a/talerbank/app/schemas.py b/talerbank/app/schemas.py index 2ff7892..db58f19 100644 --- a/talerbank/app/schemas.py +++ b/talerbank/app/schemas.py @@ -26,6 +26,7 @@ from django import forms from django.core.validators import RegexValidator from urllib.parse import urlparse from taler.util.taler_error_codes import ErrorCode +from http import HTTPStatus ## # Constant value for the biggest number the bank handles. @@ -59,7 +60,7 @@ class InvalidSession(ValueError): class InternalServerError(Exception): def __init__(self, hint): self.hint = hint - self.http_status_code = 500 + self.http_status_code = HTTPStatus.INTERNAL_SERVER_ERROR self.taler_error_code = ErrorCode.INTERNAL_LOGIC_ERROR @@ -135,7 +136,7 @@ class BankValidator: def __init__(self, validator, data): self.validation_result = validator(data) if not self.validation_result.is_valid(): - raise JSONFieldException(self.validation_result.errors, 400) + raise JSONFieldException(self.validation_result.errors, HTTPStatus.BAD_REQUEST) def get(self, name, default=None): ret = self.validation_result.cleaned_data.get(name) diff --git a/talerbank/app/views.py b/talerbank/app/views.py index 94e9998..df4075e 100644 --- a/talerbank/app/views.py +++ b/talerbank/app/views.py @@ -50,6 +50,8 @@ from datetime import datetime from .models import BankAccount, BankTransaction, TalerWithdrawOperation from taler.util.amount import Amount, SignedAmount from taler.util.taler_error_codes import ErrorCode +from http import HTTPStatus + import qrcode import qrcode.image.svg import lxml @@ -115,7 +117,7 @@ class LoginFailed(Exception): def __init__(self, msg): super(LoginFailed, self).__init__(msg) self.hint = "Wrong password given" - self.http_status_code = 401 + self.http_status_code = HTTPStatus.UNAUTHORIZED self.taler_error_code = ErrorCode.BANK_LOGIN_FAILED @@ -123,7 +125,7 @@ class InvalidInputData(Exception): def __init__(self, msg): super(InvalidInputData, self).__init__(msg) self.hint = msg # should mention the picked username - self.http_status_code = 400 + self.http_status_code = HTTPStatus.BAD_REQUEST self.taler_error_code = ErrorCode.BANK_SOFT_EXCEPTION @@ -131,7 +133,7 @@ class UsernameUnavailable(Exception): def __init__(self, msg): super(UsernameUnavailable, self).__init__(msg) self.hint = msg # should mention the picked username - self.http_status_code = 406 + self.http_status_code = HTTPStatus.NOT_ACCEPTABLE self.taler_error_code = ErrorCode.BANK_SOFT_EXCEPTION @@ -142,7 +144,7 @@ class PrivateAccountException(Exception): def __init__(self, msg): super(PrivateAccountException, self).__init__(msg) self.hint = "Cannot show history from private persons accounts" - self.http_status_code = 402 + self.http_status_code = HTTPStatus.PAYMENT_REQUIRED # WTF? FORBIDDEN? ## @@ -152,7 +154,7 @@ class DebitLimitException(Exception): def __init__(self, msg): super(DebitLimitException, self).__init__(msg) self.hint = "Payment aborted for insufficient credit" - self.http_status_code = 406 + self.http_status_code = HTTPStatus.NOT_ACCEPTABLE # WTF? FORBIDDEN? self.taler_error_code = ErrorCode.BANK_UNALLOWED_DEBIT @@ -164,7 +166,7 @@ class SameAccountException(Exception): def __init__(self, msg): super(SameAccountException, self).__init__(msg) self.hint = "Cannot send payment to oneself." - self.http_status_code = 403 + self.http_status_code = HTTPStatus.FORBIDDEN # WTF? BAD_REQUEST? self.taler_error_code = ErrorCode.BANK_SAME_ACCOUNT @@ -172,7 +174,7 @@ class UnhandledException(Exception): def __init__(self, msg="Unhandled exception happened!"): super(UnhandledException, self).__init__(msg) self.hint = msg - self.http_status_code = 500 + self.http_status_code = HTTPStatus.INTERNAL_SERVER_ERROR self.taler_error_code = ErrorCode.BANK_UNMANAGED_EXCEPTION @@ -341,7 +343,7 @@ def profile_page(request): if "just_withdrawn" in request.session: del request.session["just_withdrawn"] response["Taler"] = "taler://notify-reserve/" - response.status_code = 202 + response.status_code = HTTPStatus.ACCEPTED return response @login_required @@ -463,17 +465,17 @@ def register_headless(request): registering a user. """ if not settings.ALLOW_REGISTRATIONS: - return JsonResponse(dict(error="registrations are not allowed"), status=403) + return JsonResponse(dict(error="registrations are not allowed"), status=HTTPStatus.FORBIDDEN) username = expect_json_body_str(request, "username") password = expect_json_body_str(request, "password") try: internal_register(username, password) except UsernameUnavailable: - return JsonResponse(dict(hint="username unavailable"), status=409) # Conflict + return JsonResponse(dict(hint="username unavailable"), status=HTTPStatus.CONFLICT) except InvalidInputData: - return HttpResponse(status=406) # Not Acceptable + return HttpResponse(status=HTTPStatus.NOT_ACCEPTABLE) # WTF? BAD REQUEST? - return HttpResponse(status=200) + return HttpResponse(status=HTTPStatus.OK) def register(request): @@ -485,7 +487,7 @@ def register(request): """ if not settings.ALLOW_REGISTRATIONS: # FIXME: shouldn't be JSON! - return JsonResponse(dict(error="registrations are not allowed"), status=403) + return JsonResponse(dict(error="registrations are not allowed"), status=HTTPStatus.FORBIDDEN) if request.method != "POST": return render(request, "register.html") @@ -545,7 +547,7 @@ def config_view(request): dict( version="0:0:0", currency=settings.TALER_CURRENCY, name="taler-bank-access" ), - status=200, + status=HTTPStatus.OK, ) @@ -561,7 +563,7 @@ def api_config(request): currency=settings.TALER_CURRENCY, name="taler-bank-integration", ), - status=200, + status=HTTPStatus.OK, ) @@ -765,7 +767,7 @@ def serve_history(request, user_account): history = build_history_response(qs, args.get("cancelled", "show"), user_account) - return JsonResponse(dict(data=history), status=200) + return JsonResponse(dict(data=history), status=HTTPStatus.OK) def expect_json_body_str(request, param_name): @@ -809,7 +811,7 @@ def twg_base(request, acct_id): check if the account is up, should not normally be used for anything else. """ - return JsonResponse(dict(), status=200) + return JsonResponse(dict(), status=HTTPStatus.OK) @require_GET @@ -825,7 +827,7 @@ def twg_config(request, acct_id): name="taler-wire-gateway", currency=settings.TALER_CURRENCY, ), - status=200, + status=HTTPStatus.OK, ) @@ -960,7 +962,7 @@ def twg_history_incoming(request, user_account, acct_id): debit_account=get_payto_from_account(request, item.debit_account), ) ) - return JsonResponse(dict(incoming_transactions=history), status=200) + return JsonResponse(dict(incoming_transactions=history), status=HTTPStatus.OK) @require_GET @@ -988,7 +990,7 @@ def twg_history_outgoing(request, user_account, acct_id): debit_account=get_payto_from_account(request, item.debit_account), ) ) - return JsonResponse(dict(outgoing_transactions=history), status=200) + return JsonResponse(dict(outgoing_transactions=history), status=HTTPStatus.OK) ## @@ -1043,13 +1045,13 @@ def withdraw_headless(request, user): exchange_payto = data.get("exchange_payto_uri") if not exchange_payto: - return JsonResponse(dict(hint="exchange_payto_uri missig"), status=400) + return JsonResponse(dict(hint="exchange_payto_uri missig"), status=HTTPStatus.BAD_REQUEST) exchange_account_name = get_acct_from_payto(exchange_payto) try: exchange_user = User.objects.get(username=exchange_account_name) except User.DoesNotExist: return JsonResponse( - dict(hint="exchange bank account does not exist"), status=404 + dict(hint="exchange bank account does not exist"), status=HTTPStatus.NOT_FOUND ) exchange_bankaccount = exchange_user.bankaccount wire_transfer( @@ -1072,7 +1074,7 @@ def api_withdraw_operation(request, withdraw_id): try: op = TalerWithdrawOperation.objects.get(withdraw_id=withdraw_id) except ObjectDoesNotExist: - return JsonResponse(dict(error="withdraw operation does not exist"), status=404) + return JsonResponse(dict(error="withdraw operation does not exist"), status=HTTPStatus.NOT_FOUND) if request.method == "POST": data = json.loads(decode_body(request)) @@ -1080,18 +1082,18 @@ def api_withdraw_operation(request, withdraw_id): try: exchange_account_name = get_acct_from_payto(exchange_payto_uri) except: - return JsonResponse(dict(error="exchange payto URI malformed"), status=400) + return JsonResponse(dict(error="exchange payto URI malformed"), status=HTTPStatus.BAD_REQUEST) try: exchange_user = User.objects.get(username=exchange_account_name) except User.DoesNotExist: return JsonResponse( dict(code=ErrorCode.BANK_UNKNOWN_ACCOUNT, - hint="bank account in payto URI unknown"), status=400 + hint="bank account in payto URI unknown"), status=HTTPStatus.BAD_REQUEST # WTF? NOT_FOUND? ) exchange_account = exchange_user.bankaccount selected_reserve_pub = data.get("reserve_pub") if not isinstance(selected_reserve_pub, str): - return JsonResponse(dict(error="reserve_pub must be a string"), status=400) + return JsonResponse(dict(error="reserve_pub must be a string"), status=HTTPStatus.BAD_REQUEST) if op.selection_done: if ( op.selected_exchange_account != exchange_account @@ -1102,7 +1104,7 @@ def api_withdraw_operation(request, withdraw_id): code=ErrorCode.BANK_WITHDRAWAL_OPERATION_RESERVE_SELECTION_CONFLICT, hint="selection of withdraw parameters already done" ), - status=409, + status=HTTPStatus.CONFLICT, ) else: with transaction.atomic(): @@ -1143,7 +1145,7 @@ def api_withdraw_operation(request, withdraw_id): ) ) else: - return JsonResponse(dict(error="only GET and POST are allowed"), status=305) + return JsonResponse(dict(error="only GET and POST are allowed"), status=HTTPStatus.METHOD_NOT_ALLOWED) @login_required @@ -1275,9 +1277,9 @@ def wire_transfer(amount, debit_account, credit_account, subject, request_uid=No return JsonResponse( data=dict( hint="conflicting transfer with same request_uid exists", - ec=5600, + ec=ErrorCode.BANK_WITHDRAWAL_OPERATION_RESERVE_SELECTION_CONFLICT, ), - status=409, + status=HTTPStatus.CONFLICT, ) LOGGER.info( @@ -1403,17 +1405,17 @@ def bank_accounts_api_get_withdrawal(request, user, acct_id, wid): def withdraw_abort_internal(wid): op = TalerWithdrawOperation.objects.get(withdraw_id=wid) if op.confirmation_done: - return dict(status=409, hint="can't abort confirmed withdrawal") + return dict(status=HTTPStauts.CONFLICT, hint="can't abort confirmed withdrawal") op.aborted = True op.save() - return dict(status=200, hint="withdraw successfully aborted") + return dict(status=HTTPStatus.OK, hint="withdraw successfully aborted") @require_POST @login_required def abort_withdrawal(request, withdraw_id): internal_status = withdraw_abort_internal(withdraw_id) - set_session_hint(request, success=internal_status["status"] == 200, hint=internal_status["hint"]) + set_session_hint(request, success=internal_status["status"] == HTTPStatus.OK, hint=internal_status["hint"]) return redirect("profile") @@ -1444,9 +1446,9 @@ def bank_accounts_api_confirm_withdrawal(request, user, acct_id, wid): ) op = TalerWithdrawOperation.objects.get(withdraw_id=wid) if op.confirmation_done: - return JsonResponse(dict(), status=200) + return JsonResponse(dict(), status=HTTPStatus.OK) if op.aborted: - return JsonResponse(dict(hint="can't confirm aborted withdrawal"), status=409) + return JsonResponse(dict(hint="can't confirm aborted withdrawal"), status=HTTPStatus.CONFLICT) with transaction.atomic(): if op.selection_done: @@ -1458,4 +1460,4 @@ def bank_accounts_api_confirm_withdrawal(request, user, acct_id, wid): ) op.confirmation_done = True op.save() - return JsonResponse(dict(), status=200) + return JsonResponse(dict(), status=HTTPStatus.OK) -- cgit v1.2.3