[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[GNUnet-SVN] [taler-bank] branch master updated: being nice with small s
From: |
gnunet |
Subject: |
[GNUnet-SVN] [taler-bank] branch master updated: being nice with small screens |
Date: |
Wed, 13 Dec 2017 18:39:55 +0100 |
This is an automated email from the git hooks/post-receive script.
marcello pushed a commit to branch master
in repository bank.
The following commit(s) were added to refs/heads/master by this push:
new 3a53b2d being nice with small screens
3a53b2d is described below
commit 3a53b2d442d7776d3360cde8d06cd1675b311762
Author: Marcello Stanisci <address@hidden>
AuthorDate: Wed Dec 13 18:39:35 2017 +0100
being nice with small screens
---
talerbank/app/views.py | 240 ++++++++++++++++++++++++++++---------------------
1 file changed, 138 insertions(+), 102 deletions(-)
diff --git a/talerbank/app/views.py b/talerbank/app/views.py
index 8e6351b..fc7fa2a 100644
--- a/talerbank/app/views.py
+++ b/talerbank/app/views.py
@@ -1,16 +1,18 @@
# This file is part of TALER
# (C) 2014, 2015, 2016 INRIA
#
-# TALER is free software; you can redistribute it and/or modify it under the
-# terms of the GNU Affero General Public License as published by the Free
Software
-# Foundation; either version 3, or (at your option) any later version.
+# TALER is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation; either version 3, or
+# (at your option) any later version. TALER is distributed in the
+# hope that it will be useful, but WITHOUT ANY WARRANTY; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE. See the GNU General Public License for more
+# details.
#
-# TALER is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR
-# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License along with
-# TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
+# You should have received a copy of the GNU General Public
+# License along with TALER; see the file COPYING. If not, see
+# <http://www.gnu.org/licenses/>
#
# @author Marcello Stanisci
# @author Florian Dold
@@ -40,12 +42,14 @@ from django.db.models import Q
from django.http import (JsonResponse, HttpResponse,
HttpResponseBadRequest as HRBR)
from django.shortcuts import render, redirect
-from validictory.validator import (RequiredFieldValidationError as RFVE,
- FieldValidationError as FVE)
+from validictory.validator import \
+ (RequiredFieldValidationError as RFVE,
+ FieldValidationError as FVE)
from .models import BankAccount, BankTransaction
from .amount import Amount, CurrencyMismatch, BadFormatAmount
from .schemas import (validate_pin_tan_args, check_withdraw_session,
- validate_history_request, validate_incoming_request,
+ validate_history_request,
+ validate_incoming_request,
validate_reject_request)
LOGGER = logging.getLogger(__name__)
@@ -57,7 +61,8 @@ class DebtLimitExceededException(Exception):
class SameAccountException(Exception):
pass
-class MyAuthenticationForm(django.contrib.auth.forms.AuthenticationForm):
+class MyAuthenticationForm(
+ django.contrib.auth.forms.AuthenticationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["username"].widget.attrs["autofocus"] = True
@@ -75,7 +80,6 @@ def login_view(request):
authentication_form=MyAuthenticationForm,
template_name="login.html",
extra_context={"user": request.user})
- # sometimes the response is a redirect and not a template response
if hasattr(response, "context_data"):
response.context_data["just_logged_out"] = just_logged_out
return response
@@ -92,7 +96,8 @@ def get_session_flag(request, name):
class WTForm(forms.Form):
'''Form used to wire transfer funds internally in the bank.'''
- amount = forms.FloatField(label=settings.TALER_CURRENCY, min_value=0.1)
+ amount = forms.FloatField(
+ label=settings.TALER_CURRENCY, min_value=0.1)
counterpart = forms.IntegerField()
subject = forms.CharField()
@@ -108,46 +113,48 @@ def profile_page(request):
amount_parts = (settings.TALER_CURRENCY,
wtf.cleaned_data.get("amount") + 0.0)
try:
- wire_transfer(Amount.parse("%s:%s" % amount_parts),
- BankAccount.objects.get(
- user=request.user),
- BankAccount.objects.get(
-
account_no=wtf.cleaned_data.get("counterpart")),
- wtf.cleaned_data.get("subject"))
+ wire_transfer(
+ Amount.parse("%s:%s" % amount_parts),
+ BankAccount.objects.get(
+ user=request.user),
+ BankAccount.objects.get(
+ account_no=wtf.cleaned_data.get(
+ "counterpart")),
+ wtf.cleaned_data.get("subject"))
request.session["just_wire_transferred"] = True
except BankAccount.DoesNotExist:
request.session["wire_transfer_error"] = True
- info_bar = "Specified account for receiver does not exist"
+ info_bar = "Specified account for receiver does not" \
+ " exist"
except WireTransferException as exc:
request.session["wire_transfer_error"] = True
info_bar = "Internal server error, sorry!"
if isinstance(exc.exc, SameAccountException):
- info_bar = "Operation not possible: debit and credit
account are the same!"
+ info_bar = "Operation not possible:" \
+ " debit and credit account" \
+ " are the same!"
wtf = WTForm()
- just_wire_transferred = get_session_flag(request, "just_wire_transferred")
- wire_transfer_error = get_session_flag(request, "wire_transfer_error")
just_withdrawn = get_session_flag(request, "just_withdrawn")
- just_registered = get_session_flag(request, "just_registered")
- no_initial_bonus = get_session_flag(request, "no_initial_bonus")
- user_account = BankAccount.objects.get(user=request.user)
- history = extract_history(user_account)
- reserve_pub = request.session.get("reserve_pub")
-
context = dict(
- name=user_account.user.username,
- balance=user_account.amount.stringify(settings.TALER_DIGITS,
pretty=True),
- sign="-" if user_account.debit else "",
+ name=request.user.username,
+ balance=request.user.bankaccount.amount.stringify(
+ settings.TALER_DIGITS, pretty=True),
+ sign="-" if request.user.bankaccount.debit else "",
precision=settings.TALER_DIGITS,
- currency=user_account.amount.currency,
- account_no=user_account.account_no,
+ currency=request.user.bankaccount.amount.currency,
+ account_no=request.user.bankaccount.account_no,
wt_form=wtf,
- history=history,
+ history=extract_history(request.user.bankaccount),
just_withdrawn=just_withdrawn,
- just_registered=just_registered,
- no_initial_bonus=no_initial_bonus,
- just_wire_transferred=just_wire_transferred,
- wire_transfer_error=wire_transfer_error,
+ just_registered=get_session_flag(
+ request, "just_registered"),
+ no_initial_bonus=get_session_flag(
+ request, "no_initial_bonus"),
+ just_wire_transferred=get_session_flag(
+ request, "just_wire_transferred"),
+ wire_transfer_error=get_session_flag(
+ request, "wire_transfer_error"),
info_bar=info_bar
)
if settings.TALER_SUGGESTED_EXCHANGE:
@@ -156,7 +163,8 @@ def profile_page(request):
response = render(request, "profile_page.html", context)
if just_withdrawn:
response["X-Taler-Operation"] = "confirm-reserve"
- response["X-Taler-Reserve-Pub"] = reserve_pub
+ response["X-Taler-Reserve-Pub"] = request.session.get(
+ "reserve_pub")
response.status_code = 202
return response
@@ -193,8 +201,9 @@ def pin_tan_question(request):
except (FVE, RFVE) as err:
return HRBR("invalid '%s'" % err.fieldname)
user_account = BankAccount.objects.get(user=request.user)
+ wd = json.loads(request.GET["wire_details"])
request.session["exchange_account_number"] = \
- json.loads(request.GET["wire_details"])["test"]["account_number"]
+ wd["test"]["account_number"]
amount = Amount(request.GET["amount_currency"],
int(request.GET["amount_value"]),
int(request.GET["amount_fraction"]))
@@ -245,8 +254,9 @@ def pin_tan_verify(request):
return redirect("profile")
except BankAccount.DoesNotExist as exc:
- return JsonResponse({"error": "That exchange is unknown to this bank"},
- status=404)
+ return JsonResponse(
+ {"error": "That exchange is unknown to this bank"},
+ status=404)
except WireTransferException as exc:
return exc.response
res = requests.post(
@@ -261,13 +271,15 @@ def pin_tan_verify(request):
{"timestamp": int(time.time() * 1000)},
"amount": amount.dump()})
if res.status_code != 200:
- 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})
+ 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")
@@ -284,13 +296,16 @@ def register(request):
return render(request, "register.html")
form = UserReg(request.POST)
if not form.is_valid():
- return render(request, "register.html", dict(wrong_field=True))
+ return render(request, "register.html",
+ dict(wrong_field=True))
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
if User.objects.filter(username=username).exists():
- return render(request, "register.html", dict(not_available=True))
+ return render(request, "register.html",
+ dict(not_available=True))
with transaction.atomic():
- user = User.objects.create_user(username=username, password=password)
+ user = User.objects.create_user(username=username,
+ password=password)
user_account = BankAccount(user=user)
user_account.save()
bank_internal_account = BankAccount.objects.get(account_no=1)
@@ -304,7 +319,8 @@ def register(request):
except WireTransferException as exc:
return exc.response
request.session["just_registered"] = True
- user = django.contrib.auth.authenticate(username=username,
password=password)
+ user = django.contrib.auth.authenticate(
+ username=username, password=password)
django.contrib.auth.login(request, user)
return redirect("profile")
@@ -334,12 +350,12 @@ def extract_history(account):
cancelled=item.cancelled,
reimburses=item.reimburses,
sign=sign,
- amount=item.amount.stringify(settings.TALER_DIGITS, pretty=True),
+ amount=item.amount.stringify(
+ settings.TALER_DIGITS, pretty=True),
counterpart=counterpart.account_no,
counterpart_username=counterpart.user.username,
subject=item.subject,
- date=item.date.strftime("%d/%m/%y %H:%M"),
- )
+ date=item.date.strftime("%d/%m/%y %H:%M"))
history.append(entry)
return history
@@ -351,7 +367,8 @@ def serve_public_accounts(request, name=None):
user = User.objects.get(username=name)
account = BankAccount.objects.get(user=user, is_public=True)
except (User.DoesNotExist, BankAccount.DoesNotExist):
- return HttpResponse("account '{}' not found".format(name), status=404)
+ return HttpResponse("account '{}' not found".format(name),
+ status=404)
public_accounts = BankAccount.objects.filter(is_public=True)
history = extract_history(account)
context = dict(
@@ -378,14 +395,16 @@ def login_via_headers(view_func):
@login_via_headers
def serve_history(request, user_account):
"""
- This API is used to get a list of transactions related to one user.
+ This API is used to get a list of transactions related to one
+ user.
"""
try:
# Note, this does check the currency.
validate_history_request(request.GET.dict())
except (FVE, RFVE) as exc:
LOGGER.error("/history, bad '%s' arg" % exc.fieldname)
- return JsonResponse({"error": "invalid '%s'" % exc.fieldname},
+ return JsonResponse({"error": "invalid '%s'" \
+ % exc.fieldname},
status=400)
# delta
@@ -419,23 +438,26 @@ def serve_history(request, user_account):
qs = BankTransaction.objects.filter(
query_string, sign_filter).order_by(
- "-id" if sign == "-" else "id")[:int(parsed_delta.group(2))]
+ "-id" if sign == "-" else "id") \
+ [:int(parsed_delta.group(2))]
if qs.count() == 0:
return HttpResponse(status=204)
for entry in qs:
counterpart = entry.credit_account.account_no
sign_ = "-"
- if entry.credit_account.account_no ==
user_account.bankaccount.account_no:
+ if entry.credit_account.account_no == \
+ user_account.bankaccount.account_no:
counterpart = entry.debit_account.account_no
sign_ = "+"
cancel = "cancel" if entry.cancelled else ""
sign_ = cancel + sign_
- history.append(dict(counterpart=counterpart,
- amount=entry.amount.dump(),
- sign=sign_,
- wt_subject=entry.subject,
- row_id=entry.id,
- date="/Date(" + str(int(entry.date.timestamp())) +
")/"))
+ history.append(dict(
+ counterpart=counterpart,
+ amount=entry.amount.dump(),
+ sign=sign_,
+ wt_subject=entry.subject,
+ row_id=entry.id,
+ date="/Date("+str(int(entry.date.timestamp()))+")/"))
return JsonResponse(dict(data=history), status=200)
@@ -479,15 +501,21 @@ def reject(request, user_account):
validate_reject_request(data)
except (FVE, RFVE) as exc:
LOGGER.error("invalid %s" % exc.fieldname)
- return JsonResponse({"error": "invalid '%s'" % exc.fieldname},
status=400)
+ return JsonResponse(
+ {"error": "invalid '%s'" % exc.fieldname}, status=400)
try:
trans = BankTransaction.objects.get(id=data["row_id"])
except BankTransaction.DoesNotExist:
- return JsonResponse({"error": "unknown transaction"}, status=404)
- if trans.credit_account.account_no != user_account.bankaccount.account_no:
- LOGGER.error("you can only reject a transaction where you _got_ money")
- return JsonResponse({"error": "you can only reject a transaction where
you _got_ money"},
- status=401) # Unauthorized
+ return JsonResponse(
+ {"error": "unknown transaction"}, status=404)
+ if trans.credit_account.account_no != \
+ user_account.bankaccount.account_no:
+ LOGGER.error("you can only reject a transaction where you"
+ "_got_ money")
+ return JsonResponse(
+ {"error": "you can only reject a transaction where"
+ " you _got_ money"},
+ status=401) # Unauthorized
trans.cancelled = True
trans.save()
try:
@@ -517,25 +545,27 @@ def add_incoming(request, user_account):
# Note, this does check the currency.
validate_incoming_request(data)
except (FVE, RFVE) as exc:
- return JsonResponse({"error": "invalid '%s'" % exc.fieldname},
- status=406 if exc.fieldname == "currency" else 400)
-
-
+ return JsonResponse(
+ {"error": "invalid '%s'" % exc.fieldname},
+ status=406 if exc.fieldname == "currency" else 400)
subject = "%s %s" % (data["subject"], data["exchange_url"])
try:
- credit_account =
BankAccount.objects.get(account_no=data["credit_account"])
+ credit_account = BankAccount.objects.get(
+ account_no=data["credit_account"])
wtrans = wire_transfer(Amount(**data["amount"]),
user_account.bankaccount,
credit_account,
subject)
except BankAccount.DoesNotExist:
- return JsonResponse({"error": "credit_account (%d) not found" %
data["credit_account"]},
+ return JsonResponse(
+ {"error": "credit_account (%d) not found" \
+ % data["credit_account"]},
status=404)
except WireTransferException as exc:
return exc.response
- return JsonResponse({"row_id": wtrans.id,
- "timestamp":
- "/Date(%s)/" % int(wtrans.date.timestamp())})
+ return JsonResponse(
+ {"row_id": wtrans.id,
+ "timestamp": "/Date(%s)/" % int(wtrans.date.timestamp())})
@login_required
@@ -594,11 +624,12 @@ def wire_transfer(amount,
LOGGER.error("Debit and credit account are the same!")
raise SameAccountException()
- transaction_item = BankTransaction(amount=amount,
- credit_account=credit_account,
- debit_account=debit_account,
- subject=subject,
- reimburses=reimburses)
+ transaction_item = BankTransaction(
+ amount=amount,
+ credit_account=credit_account,
+ debit_account=debit_account,
+ subject=subject,
+ reimburses=reimburses)
if debit_account.debit:
debit_account.amount.add(amount)
@@ -627,12 +658,14 @@ def wire_transfer(amount,
if debit_account.user.username == "Bank":
threshold = Amount.parse(settings.TALER_MAX_DEBT_BANK)
if Amount.cmp(debit_account.amount, threshold) == 1 \
- and Amount.cmp(Amount(settings.TALER_CURRENCY), threshold) != 0 \
- and debit_account.debit:
+ 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("%s's threshold is: '%s'." \
+ % (debit_account.user.username,
+ json.dumps(threshold.dump())))
raise DebtLimitExceededException()
with transaction.atomic():
@@ -643,23 +676,26 @@ def wire_transfer(amount,
return transaction_item
try:
- return wire_transfer_internal(amount,
- debit_account,
- credit_account,
- subject,
- kwargs.get("reimburses", None))
+ return wire_transfer_internal(
+ amount,
+ debit_account,
+ credit_account,
+ subject,
+ kwargs.get("reimburses", None))
except (CurrencyMismatch, BadFormatAmount) as exc:
err_cb(exc, JsonResponse({"error": "internal server error"},
status=500))
except DebtLimitExceededException as exc:
if kwargs.get("request"):
if kwargs.get("session_expand"):
- kwargs["request"].session.update(kwargs["session_expand"])
+ kwargs["request"].session.update(
+ kwargs["session_expand"])
if kwargs["request"].request.path == "/pin/verify":
err_cb(exc, redirect("profile"))
else:
err_cb(exc, JsonResponse({"error": "Unallowed debit"},
status=403))
except SameAccountException as exc:
- err_cb(exc, JsonResponse({"error": "sender account == receiver
account"},
- status=422))
+ err_cb(exc, JsonResponse(
+ {"error": "sender account == receiver account"},
+ status=422))
--
To stop receiving notification emails like this one, please contact
address@hidden
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- [GNUnet-SVN] [taler-bank] branch master updated: being nice with small screens,
gnunet <=