gnunet-svn
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[GNUnet-SVN] [taler-bank] branch master updated (62674ab -> 5761de4)


From: gnunet
Subject: [GNUnet-SVN] [taler-bank] branch master updated (62674ab -> 5761de4)
Date: Mon, 06 Nov 2017 16:01:08 +0100

This is an automated email from the git hooks/post-receive script.

marcello pushed a change to branch master
in repository bank.

    from 62674ab  shortening pin/tan handler
     new a52cdc0  linting pin/tan verify
     new 5761de4  addressing obvious pylint warnings

The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 talerbank/app/urls.py  |   6 +-
 talerbank/app/views.py | 206 +++++++++++++++++++++++--------------------------
 2 files changed, 98 insertions(+), 114 deletions(-)

diff --git a/talerbank/app/urls.py b/talerbank/app/urls.py
index 7578d81..5a1ce34 100644
--- a/talerbank/app/urls.py
+++ b/talerbank/app/urls.py
@@ -28,11 +28,11 @@ urlpatterns = [
     url(r'^logout/$', views.logout_view, name="logout"),
     url(r'^accounts/register/$', views.register, name="register"),
     url(r'^profile$', views.profile_page, name="profile"),
-    url(r'^history$', views.history, name="history"),
+    url(r'^history$', views.serve_history, name="history"),
     url(r'^withdraw$', views.withdraw_nojs, name="withdraw-nojs"),
-    url(r'^public-accounts$', views.public_accounts, name="public-accounts"),
+    url(r'^public-accounts$', views.serve_public_accounts, 
name="public-accounts"),
     url(r'^public-accounts/(?P<name>[a-zA-Z0-9 ]+)$',
-        views.public_accounts,
+        views.serve_public_accounts,
         name="public-accounts"),
     url(r'^pin/question$', views.pin_tan_question, name="pin-question"),
     url(r'^pin/verify$', views.pin_tan_verify, name="pin-verify"),
diff --git a/talerbank/app/views.py b/talerbank/app/views.py
index dc5aabc..ab96c34 100644
--- a/talerbank/app/views.py
+++ b/talerbank/app/views.py
@@ -15,12 +15,13 @@
 #  @author Marcello Stanisci
 #  @author Florian Dold
 
+from urllib.parse import urljoin
 import json
 import logging
 import time
 import hashlib
 import re
-from urllib.parse import urljoin
+import validictory
 import requests
 import django.contrib.auth
 import django.contrib.auth.views
@@ -29,14 +30,17 @@ from django.db import transaction
 from django import forms
 from django.conf import settings
 from django.contrib.auth.decorators import login_required
-from django.http import JsonResponse, HttpResponse, HttpResponseBadRequest, 
HttpResponseServerError
+from django.http import (JsonResponse,
+                         HttpResponse,
+                         HttpResponseBadRequest as HRBR,
+                         HttpResponseServerError)
 from django.shortcuts import render, redirect
 from django.views.decorators.csrf import csrf_exempt
 from django.views.decorators.http import require_POST, require_GET
-from simplemathcaptcha.fields import MathCaptchaField, MathCaptchaWidget
 from django.core.urlresolvers import reverse
 from django.contrib.auth.models import User
 from django.db.models import Q
+from simplemathcaptcha.fields import MathCaptchaField, MathCaptchaWidget
 from . import schemas
 from .models import BankAccount, BankTransaction
 from .amount import Amount, CurrencyMismatch, BadFormatAmount
@@ -56,6 +60,7 @@ class 
MyAuthenticationForm(django.contrib.auth.forms.AuthenticationForm):
         self.fields["password"].widget.attrs["placeholder"] = "Password"
 
 def ignore(request):
+    del request
     return HttpResponse()
 
 
@@ -133,8 +138,8 @@ def pin_tan_question(request):
         schemas.validate_pin_tan_args(request.GET.dict())
         # Currency is not checked, as any mismatches will be
         # detected afterwards
-    except ValueError as error:
-        return HttpResponseBadRequest("invalid '%s'" % error.fieldname)
+    except validictory.FieldValidationError as err:
+        return HRBR("invalid '%s'" % err.fieldname)
     user_account = BankAccount.objects.get(user=request.user)
     request.session["exchange_account_number"] = \
         json.loads(request.GET["wire_details"])["test"]["account_number"]
@@ -161,79 +166,63 @@ def pin_tan_question(request):
 @require_POST
 @login_required
 def pin_tan_verify(request):
-    try:
-        given = request.POST["pin_0"]
-        hashed_result = request.POST["pin_1"]
-        question_url = request.POST["question_url"]
-    except Exception:  # FIXME narrow the Exception type
-        return redirect("profile")
     hasher = hashlib.new("sha1")
     hasher.update(settings.SECRET_KEY.encode("utf-8"))
-    hasher.update(given.encode("utf-8"))
+    # pin_0 is the answer given by the user
+    hasher.update(request.POST.get("pin_0").encode("utf-8"))
     hashed_attempt = hasher.hexdigest()
-    if hashed_attempt != hashed_result:
+    if hashed_attempt != request.POST.get("pin_1"):
         request.session["captcha_failed"] = True
-        return redirect(question_url)
-    # We recover the info about reserve creation from the session (and
-    # not from POST parameters), since we don't what the user to
-    # change it after we've verified it.
-    try:
-        amount = Amount(**request.session["amount"])
-        exchange_url = request.session["exchange_url"]
-        reserve_pub = request.session["reserve_pub"]
-        exchange_account_number = request.session["exchange_account_number"]
-        sender_wiredetails = request.session["sender_wiredetails"]
-    except KeyError:
-        # This is not a withdraw session, we redirect the user to the
-        # profile page.
-        return redirect("profile")
+        return redirect(request.POST.get("question_url", "profile"))
+    # Check the session is a "pin tan" one
+    for i in ("amount", "exchange_url", "reserve_pub",
+              "exchange_account_number", "sender_wiredetails"):
+        if i not in request.session:
+            LOGGER.warning("Apparently NOT a withdraw session")
+            return redirect("profile")
+    amount = Amount(**request.session["amount"])
     try:
-        BankAccount.objects.get(account_no=exchange_account_number)
-    except BankAccount.DoesNotExist:
-        raise HttpResponseBadRequest("The bank account #{} \
-                                     of exchange {} does not \
-                                     exist".format(exchange_account_number,
-                                                   exchange_url))
-    logging.info("asking exchange {} to create reserve 
{}".format(exchange_url, reserve_pub))
-    json_body = dict(
-        reserve_pub=reserve_pub,
-        execution_date="/Date(" + str(int(time.time())) + ")/",
-        sender_account_details=sender_wiredetails,
-        # just something unique
-        transfer_details=dict(timestamp=int(time.time() * 1000)),
-        amount=amount.dump(),
-    )
-    user_account = BankAccount.objects.get(user=request.user)
-    exchange_account = 
BankAccount.objects.get(account_no=exchange_account_number)
-    try:
-        wire_transfer(amount, user_account, exchange_account, reserve_pub)
-    except DebtLimitExceededException:
-        LOGGER.warning("Withdrawal impossible due to debt limit exceeded")
+        exchange_bank_account = BankAccount.objects.get(
+            account_no=request.session["exchange_account_number"])
+        wire_transfer(amount,
+                      BankAccount.objects.get(user=request.user),
+                      exchange_bank_account,
+                      request.session["reserve_pub"])
+    except BankAccount.DoesNotExist as exc:
+        ctx = {"err": lambda: HRBR("That exchange is unknown to this bank"),
+               "exc": exc}
+    except DebtLimitExceededException as exc:
         request.session["debt_limit"] = True
-        return redirect("profile")
-    except SameAccountException:
-        LOGGER.error("Odd situation: SameAccountException should NOT occur in 
this function")
-        return JsonResponse(dict(error="Internal server error", status=500))
-    except BadFormatAmount:
-        LOGGER.error("parsing MAX_DEBT or MAX_BANK_DEBT failed")
-        return JsonResponse(dict(error="Internal server error", status=500))
-    except CurrencyMismatch:
-        LOGGER.error("currency mismatch internal to the bank, should never 
happen here")
-        return JsonResponse(dict(error="Internal server error", status=500))
-
-    request_url = urljoin(exchange_url, "admin/add/incoming")
-    res = requests.post(request_url, json=json_body)
+        ctx = {"err": lambda: redirect("profile"),
+               "exc": exc}
+    except (SameAccountException, BadFormatAmount, CurrencyMismatch) as exc:
+        ctx = {"err": lambda: JsonResponse(dict(error="Internal server error", 
status=500)),
+               "exc": exc}
+    if "err" in locals():
+        LOGGER.error(ctx["exc"])
+        return ctx["err"]()
+    res = requests.post(
+        urljoin(request.session["exchange_url"],
+                "admin/add/incoming"),
+        json={"reserve_pub": request.session["reserve_pub"],
+              "execution_date":
+                  "/Date(" + str(int(time.time())) + ")/",
+              "sender_account_details":
+                  request.session["sender_wiredetails"],
+              "transfer_details":
+                  {"timestamp": int(time.time() * 1000)},
+              "amount": amount.dump()})
     if res.status_code != 200:
-        return render(request, "error_exchange.html", dict(
-            message="Could not transfer funds to the exchange.  \
-                    The exchange ({}) gave a bad 
response.".format(exchange_url),
-            response_text=res.text,
-            response_status=res.status_code,
-        ))
+        return render(request,
+                      "error_exchange.html",
+                      {"message": "Could not transfer funds to the exchange. \
+                                   The exchange (%s) gave a bad response.\
+                                   " % request.session["exchange_url"],
+                       "response_text": res.text,
+                       "response_status": res.status_code})
     request.session["just_withdrawn"] = True
     return redirect("profile")
 
-
 class UserReg(forms.Form):
     username = forms.CharField()
     password = forms.CharField(widget=forms.PasswordInput())
@@ -261,18 +250,16 @@ def register(request):
         wire_transfer(Amount(settings.TALER_CURRENCY, 100, 0),
                       bank_internal_account, user_account,
                       "Joining bonus")
-    except DebtLimitExceededException:
-        LOGGER.info("Debt situation encountered")
+    except (CurrencyMismatch,
+            BadFormatAmount,
+            SameAccountException) as exc:
+        exc = exc
+    except DebtLimitExceededException as exc:
         request.session["no_initial_bonus"] = True
-        return HttpResponseServerError()
-    except CurrencyMismatch:
-        LOGGER.error("Currency mismatch internal to the bank")
-        return HttpResponseServerError()
-    except BadFormatAmount:
-        LOGGER.error("Could not parse MAX_DEBT|MAX_BANK_DEBT")
-        return HttpResponseServerError()
-    except SameAccountException:
-        LOGGER.error("Odd situation: SameAccountException should NOT occur in 
this function")
+        exc = exc
+
+    if "err" in locals():
+        LOGGER.error(exc)
         return HttpResponseServerError()
 
     request.session["just_registered"] = True
@@ -313,15 +300,13 @@ def extract_history(account):
     return history
 
 
-def public_accounts(request, name=None):
+def serve_public_accounts(request, name=None):
     if not name:
         name = settings.TALER_PREDEFINED_ACCOUNTS[0]
     try:
         user = User.objects.get(username=name)
         account = BankAccount.objects.get(user=user, is_public=True)
-    except User.DoesNotExist:
-        return HttpResponse("account '{}' not found".format(name), status=404)
-    except BankAccount.DoesNotExist:
+    except (User.DoesNotExist, BankAccount.DoesNotExist):
         return HttpResponse("account '{}' not found".format(name), status=404)
     public_accounts = BankAccount.objects.filter(is_public=True)
     history = extract_history(account)
@@ -336,7 +321,7 @@ def public_accounts(request, name=None):
     return render(request, "public_accounts.html", context)
 
 @require_GET
-def history(request):
+def serve_history(request):
     """
     This API is used to get a list of transactions related to one user.
     """
@@ -348,7 +333,7 @@ def history(request):
     # delta
     delta = request.GET.get("delta")
     if not delta:
-        return HttpResponseBadRequest()
+        return HRBR()
     #FIXME: make the '+' sign optional
     parsed_delta = re.search(r"([\+-])?([0-9]+)", delta)
     try:
@@ -363,13 +348,13 @@ def history(request):
 
     sign = parsed_delta.group(1)
 
-    if ("+" == sign) or (not sign):
+    if (sign == "+") or (not sign):
         sign = ""
     # Assuming Q() means 'true'
     sign_filter = Q()
-    if "-" == sign and start:
+    if sign == "-" and start:
         sign_filter = Q(id__lt=start)
-    elif "" == sign and start:
+    elif sign == "" and start:
         sign_filter = Q(id__gt=start)
     # direction (debit/credit)
     direction = request.GET.get("direction")
@@ -391,13 +376,13 @@ def history(request):
     query_string = Q(debit_account=target_account) | 
Q(credit_account=target_account)
     history = []
 
-    if "credit" == direction:
+    if direction == "credit":
         query_string = Q(credit_account=target_account)
-    if "debit" == direction:
+    if direction == "debit":
         query_string = Q(debit_account=target_account)
 
     qs = BankTransaction.objects.filter(query_string, 
sign_filter).order_by("%sid" % sign)[:delta]
-    if 0 == qs.count():
+    if qs.count() == 0:
         return HttpResponse(status=204)
     for entry in qs:
         counterpart = entry.credit_account.account_no
@@ -419,13 +404,12 @@ def auth_and_login(request):
        credentials, False if errors occur"""
 
     auth_type = None
-    if "POST" == request.method:
+    if request.method == "POST":
         data = json.loads(request.body.decode("utf-8"))
         auth_type = data["auth"]["type"]
-    if "GET" == request.method:
+    if request.method == "GET":
         auth_type = request.GET.get("auth")
-
-    if "basic" != auth_type:
+    if auth_type != "basic":
         LOGGER.error("auth method not supported")
         return False
 
@@ -473,15 +457,15 @@ def add_incoming(request):
         if settings.TALER_CURRENCY != data["amount"]["currency"]:
             LOGGER.error("Currency differs from bank's")
             return JsonResponse(dict(error="Currency differs from bank's"), 
status=406)
-        transaction = wire_transfer(Amount(**data["amount"]),
-                                    user_account.bankaccount,
-                                    credit_account,
-                                    subject)
-        return JsonResponse(dict(serial_id=transaction.id,
+        wtrans = wire_transfer(Amount(**data["amount"]),
+                               user_account.bankaccount,
+                               credit_account,
+                               subject)
+        return JsonResponse(dict(serial_id=wtrans.id,
                                  timestamp="/Date(%s)/" %
-                                 int(transaction.date.timestamp())))
-    except ValueError as e:
-        return JsonResponse(dict(error=e), status=400)
+                                 int(wtrans.date.timestamp())))
+    except ValueError as exc:
+        return JsonResponse(dict(error=exc), status=400)
 
     except BadFormatAmount:
         LOGGER.error("Bad MAX_DEBT|MAX_BANK_DEBT format")
@@ -508,7 +492,7 @@ def withdraw_nojs(request):
         amount = Amount.parse(request.POST.get("kudos_amount", ""))
     except BadFormatAmount:
         LOGGER.error("Amount did not pass parsing")
-        return HttpResponseBadRequest()
+        return HRBR()
 
     user_account = BankAccount.objects.get(user=request.user)
 
@@ -549,7 +533,7 @@ def wire_transfer(amount, debit_account, credit_account, 
subject):
 
     if not credit_account.debit:
         credit_account.amount.add(amount)
-    elif 1 == Amount.cmp(amount, credit_account.amount):
+    elif Amount.cmp(amount, credit_account.amount) == 1:
         credit_account.debit = False
         tmp = Amount(**amount.dump())
         tmp.subtract(credit_account.amount)
@@ -563,13 +547,13 @@ def wire_transfer(amount, debit_account, credit_account, 
subject):
     threshold = Amount.parse(settings.TALER_MAX_DEBT)
     if debit_account.user.username == "Bank":
         threshold = Amount.parse(settings.TALER_MAX_DEBT_BANK)
-    if 1 == Amount.cmp(debit_account.amount, threshold) \
-        and 0 != Amount.cmp(Amount(settings.TALER_CURRENCY), threshold) \
+    if Amount.cmp(debit_account.amount, threshold) == 1 \
+        and Amount.cmp(Amount(settings.TALER_CURRENCY), threshold) != 0 \
         and debit_account.debit:
-        LOGGER.info("Negative balance '%s' not allowed." % 
json.dumps(debit_account.amount.dump()))
-        LOGGER.info("%s's threshold is: '%s'." %
-                    (debit_account.user.username,
-                     json.dumps(threshold.dump())))
+        LOGGER.info("Negative balance '%s' not allowed.\
+                    " % json.dumps(debit_account.amount.dump()))
+        LOGGER.info("%s's threshold is: '%s'.\
+                    " % (debit_account.user.username, 
json.dumps(threshold.dump())))
         raise DebtLimitExceededException()
 
     with transaction.atomic():

-- 
To stop receiving notification emails like this one, please contact
address@hidden



reply via email to

[Prev in Thread] Current Thread [Next in Thread]