gnunet-svn
[Top][All Lists]
Advanced

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

[GNUnet-SVN] [taler-bank] 01/02: 5715


From: gnunet
Subject: [GNUnet-SVN] [taler-bank] 01/02: 5715
Date: Fri, 31 May 2019 18:56:36 +0200

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

marcello pushed a commit to branch master
in repository bank.

commit 992a33997c3eb8098c5c042fc04961aa79ab862f
Author: Marcello Stanisci <address@hidden>
AuthorDate: Fri May 31 18:42:40 2019 +0200

    5715
    
    Nesting the Form definitions to validate (nested) JSONs,
    and putting default policies _inside_ the Form definition.
---
 talerbank/app/schemas.py | 60 +++++++++++++++++++++++++++++++++++++++++++-----
 talerbank/app/views.py   | 26 ++++++++-------------
 2 files changed, 64 insertions(+), 22 deletions(-)

diff --git a/talerbank/app/schemas.py b/talerbank/app/schemas.py
index 01503a2..20d5e01 100644
--- a/talerbank/app/schemas.py
+++ b/talerbank/app/schemas.py
@@ -31,6 +31,15 @@ from django.core.validators import RegexValidator
 
 
 ##
+# Constant value for the biggest number the bank handles.
+# This value is just equal to the biggest number that JavaScript
+# can handle (because of the wallet).
+# FIXME: also defined in views.py.  Need a common.py to contain
+# such definitions ?
+UINT64_MAX = (2**64) - 1
+
+
+##
 # Exception class to be raised when at least one expected URL
 # parameter is either not found or malformed.
 class URLParamValidationError(ValidationError):
@@ -39,7 +48,7 @@ class URLParamValidationError(ValidationError):
     # Init method.
     #
     # @param self the object itself.
-    # @param param the missing URL parameter name.
+    # @param error object containing the hint.
     # @param http_status_code the HTTP response code to return
     #        to the caller (client).
     def __init__(self, error, http_status_code):
@@ -47,6 +56,37 @@ class URLParamValidationError(ValidationError):
         self.http_status_code = http_status_code
         super().__init__()
 
+class AuthForm(forms.Form):
+
+    type = forms.CharField(
+        validators=[RegexValidator(
+            "^basic$",
+            message="Only 'basic' method provided for now")])
+
+    # Just any value is good here.
+    data = forms.Field(required=False) 
+
+class AuthField(forms.Field):
+    ##
+    # No need to touch the input.  Dict is good
+    # and gets validated by the "validate()" method.
+    def to_python(self, value):
+        return value
+
+    ##
+    # Validate input.
+    def validate(self, value):
+        af = AuthForm(value)
+        if not af.is_valid():
+            raise ValidationError(
+                json.dumps(af.errors.as_json()))
+
+class RejectData(forms.Form):
+    auth = AuthField()
+    # FIXME: adjust min/max values.
+    row_id = forms.IntegerField()
+    account_number = forms.IntegerField()
+
 ##
 # Form specification that validates GET parameters from a
 # /history request.
@@ -80,6 +120,14 @@ class HistoryParamsBase(forms.Form):
 
 
 class HistoryParams(HistoryParamsBase):
+    
+    def clean_start(self):
+        delta = self.cleaned_data.get("delta")        
+        start = self.cleaned_data.get("start")
+        if None == start:
+            return 0 if 0 <= delta else UINT64_MAX
+        return start
+
     # FIXME: adjust min/max values.
     delta = forms.IntegerField()
     start = forms.IntegerField(required=False)
@@ -133,11 +181,11 @@ class JSONFieldException(ValueError):
     # Init method.
     #
     # @param self the object itself.
-    # @param hint the hint to be displayed along the error.
-    # @param http_status_code HTTP response code to be returned
-    #        along the error.
-    def __init__(self, hint, http_status_code):
-        self.hint = hint
+    # @param error object containing the hint.
+    # @param http_status_code the HTTP response code to return
+    #        to the caller (client).
+    def __init__(self, error, http_status_code):
+        self.hint = json.dumps(error.as_json())
         self.http_status_code = http_status_code
         super().__init__()
 
diff --git a/talerbank/app/views.py b/talerbank/app/views.py
index 34a5b70..77f2477 100644
--- a/talerbank/app/views.py
+++ b/talerbank/app/views.py
@@ -44,7 +44,8 @@ from django.shortcuts import render, redirect
 from datetime import datetime
 from .models import BankAccount, BankTransaction
 from .amount import Amount
-from .schemas import validate_data, HistoryParams, HistoryRangeParams, 
URLParamValidationError
+from .schemas import validate_data, HistoryParams, HistoryRangeParams, 
URLParamValidationError, RejectData, JSONFieldException
+
 LOGGER = logging.getLogger(__name__)
 
 ##
@@ -743,16 +744,10 @@ def serve_history(request, user_account):
     if not get_params.is_valid():
         raise URLParamValidationError(get_params.errors, 400)
 
-    delta = get_params.cleaned_data.get("delta")
-    start = get_params.cleaned_data.get("start")
-
-    if None == start:
-        start = 0 if 0 <= delta else UINT64_MAX
-
     qs = query_history(user_account.bankaccount,
                        get_params.cleaned_data.get("direction"),
-                       delta,
-                       start,
+                       get_params.cleaned_data.get("delta"),
+                       get_params.cleaned_data.get("start"),
                        get_params.cleaned_data.get("ordering"))
 
     history = build_history_response(
@@ -794,9 +789,6 @@ def auth_and_login(request):
     return django.contrib.auth.authenticate(
         username=username,
         password=password)
-
-
-
 ##
 # Serve a request of /reject (for rejecting wire transfers).
 #
@@ -811,8 +803,12 @@ def auth_and_login(request):
 @login_via_headers
 def reject(request, user_account):
     data = json.loads(request.body.decode("utf-8"))
-    validate_data(request, data)
-    trans = BankTransaction.objects.get(id=data["row_id"])
+    data = RejectData(data)
+
+    if not data.is_valid():
+        raise JSONFieldException(data.errors, 400)
+
+    trans = BankTransaction.objects.get(id=data.cleaned_data.get("row_id"))
     if trans.credit_account.account_no != \
             user_account.bankaccount.account_no:
         raise RejectNoRightsException()
@@ -822,8 +818,6 @@ def reject(request, user_account):
     trans.save()
     return HttpResponse(status=204)
 
-
-
 ##
 # Serve a request to make a wire transfer.  Allows fintech
 # providers to issues payments in a programmatic way.

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



reply via email to

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