diff options
author | Marcello Stanisci <marcello.stanisci@inria.fr> | 2016-04-13 18:44:05 +0200 |
---|---|---|
committer | Marcello Stanisci <marcello.stanisci@inria.fr> | 2016-04-13 18:44:05 +0200 |
commit | f1e13526df6d369faa2994e22e20f493958d7ee6 (patch) | |
tree | 7badc275b0eef9b5c0a47fd38c74e8be0410c90a /talerbank/app | |
parent | 911461080a1f2eb8cd57d2102eeb44030cd6f13c (diff) | |
parent | 176459ec20d1c9ad771fa9caeba06e6133b8ead6 (diff) | |
download | bank-f1e13526df6d369faa2994e22e20f493958d7ee6.tar.gz bank-f1e13526df6d369faa2994e22e20f493958d7ee6.tar.bz2 bank-f1e13526df6d369faa2994e22e20f493958d7ee6.zip |
Merge branch 'master' of ssh://taler.net/var/git/bank
Conflicts:
talerbank/app/apps.py
talerbank/app/config.py
talerbank/app/config.py.in
talerbank/app/funds_mgmt.py
talerbank/app/startup.py
talerbank/app/test.py
talerbank/app/user_mgmt.py
Diffstat (limited to 'talerbank/app')
-rw-r--r-- | talerbank/app/apps.py | 9 | ||||
-rw-r--r-- | talerbank/app/captcha.py | 82 | ||||
-rw-r--r-- | talerbank/app/funds_mgmt.py | 49 | ||||
-rw-r--r-- | talerbank/app/history.py | 34 | ||||
-rw-r--r-- | talerbank/app/lib.py | 80 | ||||
-rw-r--r-- | talerbank/app/management/commands/basic_accounts.py | 26 | ||||
-rw-r--r-- | talerbank/app/management/commands/pre_accounts.py | 53 | ||||
-rw-r--r-- | talerbank/app/management/commands/provide_accounts.py | 80 | ||||
-rw-r--r-- | talerbank/app/management/commands/sample_donations.py | 5 | ||||
-rw-r--r-- | talerbank/app/migrations/0001_initial.py | 3 | ||||
-rw-r--r-- | talerbank/app/models.py | 9 | ||||
-rw-r--r-- | talerbank/app/schemas.py | 10 | ||||
-rw-r--r-- | talerbank/app/startup.py | 57 | ||||
-rw-r--r-- | talerbank/app/templates/error.html | 2 | ||||
-rw-r--r-- | talerbank/app/templates/public_histories_reloaded.html | 2 | ||||
-rw-r--r-- | talerbank/app/test.py | 29 | ||||
-rw-r--r-- | talerbank/app/urls.py | 23 | ||||
-rw-r--r-- | talerbank/app/user_mgmt.py | 58 | ||||
-rw-r--r-- | talerbank/app/views.py | 25 |
19 files changed, 194 insertions, 442 deletions
diff --git a/talerbank/app/apps.py b/talerbank/app/apps.py deleted file mode 100644 index cf82012..0000000 --- a/talerbank/app/apps.py +++ /dev/null @@ -1,9 +0,0 @@ -#this file is in the public domain - -from __future__ import unicode_literals - -from django.apps import AppConfig - - -class BankConfig(AppConfig): - name = 'Bank' diff --git a/talerbank/app/captcha.py b/talerbank/app/captcha.py index 85a9e34..bb2f52a 100644 --- a/talerbank/app/captcha.py +++ b/talerbank/app/captcha.py @@ -14,41 +14,19 @@ # # @author Marcello Stanisci -from .user_mgmt import is_logged -from .funds_mgmt import (Reserve, - create_reserve_at_exchange) -from .schemas import Schemas -from .lib import (write_log_file, - get_currency, - check_db, - get_pretty_exchange_details, - floatify_amount) -from simplemathcaptcha.fields import (MathCaptchaField, - MathCaptchaWidget) +import hashlib +import json +from urllib.parse import urlunparse, urlparse, unquote +from simplemathcaptcha.fields import MathCaptchaField, MathCaptchaWidget from django.http import HttpResponse, JsonResponse from django.shortcuts import render from django.conf import settings from django import forms -from urllib.parse import (urlunparse, - urlparse, - unquote) -import hashlib -import json -from .errors import (UserNotLogged, - BadAmount, - MissingGetParameter, - WrongMethod, - user_not_logged_handler, - BadGetParameter, - BadPostValue, - BadWireDetails, - ExchangeUnknown, - NoBankMatch, - NoWireMethodMatch, - bad_get_parameter_handler, - bad_post_value_handler, - exchange_unknown_handler, - wrong_method_handler) +from .user_mgmt import is_logged +from .funds_mgmt import Reserve, create_reserve_at_exchange +from .schemas import Schemas +from .lib import get_currency, check_db, get_pretty_exchange_details, floatify_amount +from . import errors class Pin(forms.Form): @@ -60,7 +38,7 @@ class Pin(forms.Form): @is_logged def pin_tan_question_attempt(request): if request.method != 'GET': - raise WrongMethod('GET') + raise errors.WrongMethod('GET') for param in ["amount_value", "amount_fraction", "amount_currency", @@ -68,20 +46,20 @@ def pin_tan_question_attempt(request): "reserve_pub", "wire_details"]: if param not in request.GET: - raise MissingGetParameter(param) + raise errors.MissingGetParameter(param) try: amount = {'value': int(request.GET['amount_value']), 'fraction': int(request.GET['amount_fraction']), 'currency': request.GET['amount_currency']} except ValueError: - raise BadGetParameter + raise errors.BadGetParameter wiredetails = json.loads(unquote(request.GET['wire_details'])) Schemas.validate_wiredetails(wiredetails, Schemas.wiredetails_schema) if "test" not in wiredetails: - raise NoWireMethodMatch + raise errors.NoWireMethodMatch # always false to run local tests.. if urlparse(wiredetails['test']['bank_uri']).netloc != request.META['HTTP_HOST'] and False: - raise NoBankMatch + raise errors.NoBankMatch request.session['account_number'] = wiredetails['test']['account_number'] Schemas.validate_amount(amount, Schemas.amount_schema) # raise BadAmount request.session['amount'] = amount @@ -98,19 +76,19 @@ def pin_tan_question_attempt(request): def pin_tan_question(request): try: return pin_tan_question_attempt(request) - except MissingGetParameter as e: + except errors.MissingGetParameter as e: return JsonResponse({'reason': e.par + " missing in query parameters"}, status=400) - except (BadAmount, BadGetParameter): + except (errors.BadAmount, errors.BadGetParameter): return JsonResponse({'reason': "bad amount given"}, status=400) - except WrongMethod as e: + except errors.WrongMethod as e: return JsonResponse({'reason': 'only GET method allowed'}, status=405) - except BadWireDetails: + except errors.BadWireDetails: return JsonResponse({'reason': "bad wiredetails given"}, status=400) except ValueError: return JsonResponse({'reason': "garbage in query string"}, status=400) - except NoWireMethodMatch: + except errors.NoWireMethodMatch: return JsonResponse({'reason': "incompatible wire methods"}, status=400) - except NoBankMatch: + except errors.NoBankMatch: return JsonResponse({'reason': "bank given in wiredetails is not this one"}, status=400) @@ -119,22 +97,22 @@ def pin_tan_question(request): def pin_tan_verify(request): try: return pin_tan_verify_attempt(request) - except WrongMethod as e: - return wrong_method_handler(request, e) - except UserNotLogged: - return user_not_logged_handler(request) - except BadPostValue: - return bad_post_value_handler(request) + except errors.WrongMethod as e: + return errors.wrong_method_handler(request, e) + except errors.UserNotLogged: + return errors.user_not_logged_handler(request) + except errors.BadPostValue: + return errors.bad_post_value_handler(request) def pin_tan_verify_attempt(request): if request.method != 'POST': - raise WrongMethod("POST") + raise errors.WrongMethod("POST") try: given = request.POST['pin_0'] hashed_result = request.POST['pin_1'] except Exception: # FIXME narrow the Exception type - raise BadPostValue + raise errors.BadPostValue() hasher = hashlib.new("sha1") hasher.update(settings.SECRET_KEY.encode('utf-8')) hasher.update(given.encode('utf-8')) @@ -153,8 +131,8 @@ def pin_tan_verify_attempt(request): "/success.html", '', '', '']) try: return create_reserve_at_exchange(request, success_url, reserve) - except ExchangeUnknown: - return exchange_unknown_handler(request) + except errors.ExchangeUnknown: + return errors.exchange_unknown_handler(request) else: return render(request, 'error.html', {'type': "wrong_pin"}, status=400) diff --git a/talerbank/app/funds_mgmt.py b/talerbank/app/funds_mgmt.py index edd45be..2bf33b4 100644 --- a/talerbank/app/funds_mgmt.py +++ b/talerbank/app/funds_mgmt.py @@ -16,33 +16,22 @@ from .user_mgmt import is_logged from .schemas import Schemas -from .errors import (BadIncomingRequest, - CurrencyMismatch, - WrongMethod) -from .lib import (write_log_file, - check_exchange_account_no, - wire_transfer_in_out) +from .errors import BadIncomingRequest, CurrencyMismatch, WrongMethod +from .lib import check_exchange_account_no, wire_transfer_in_out from django.views.decorators.csrf import csrf_exempt -from django.http import (HttpResponse, - JsonResponse) +from django.http import HttpResponse, JsonResponse from .models import BankAccount -from django.shortcuts import (render, - redirect) +from django.shortcuts import render, redirect from django.db.utils import OperationalError from django import forms from django.http import HttpResponseServerError -from urllib.parse import (urlparse, - urljoin) +from urllib.parse import urlparse, urljoin import requests import time import json +import logging - -class DebugForm(forms.Form): - reserve_pk = forms.CharField(initial="DVHS4CQRC3ZQPW9PD6A5BCTYS9Z460P261M6M660QS7N16BXP19G") - kudos_amount = forms.CharField(initial="3.3 KUDOS") - mint_rcv = forms.CharField(initial="http://mint.demo.taler.net/") - +logger = logging.getLogger(__name__) class Reserve: def __init__(self, amount, exchange, exchange_account, reserve_pub, wire_type): @@ -54,17 +43,10 @@ class Reserve: self.reserve_pub = reserve_pub self.wire_type = wire_type - -class Transaction: - def __init__(self, direction, amount, counterpart="Unknown"): - self.direction = direction - self.amount = amount - self.counterpart = counterpart - -#The CSRF exempt is due to the fact Django looks for an anti-CSRF token -#in any POST it gets. Since the following function is meant to serve mints, -#and mints don't send any such token, it is necessary to disable it. -#Those tokens are normally hidden fields in Django-generated HTML forms. +# The CSRF exempt is due to the fact Django looks for an anti-CSRF token +# In any POST it gets. Since the following function is meant to serve mints, +# And mints don't send any such token, it is necessary to disable it. +# Those tokens are normally hidden fields in Django-generated HTML forms. @csrf_exempt def add_incoming_attempt(request): @@ -95,6 +77,8 @@ def add_incoming(request): raise WrongMethod('GET') data = json.loads(request.body.decode('utf-8')) Schemas.validate_incoming_request(data, Schemas.incoming_request_schema) + logger.info("add_incoming for debit account %s and credit accout %s", data['debit_account'], data['credit_account']) + wire_transfer_in_out(data['amount'], data['debit_account'], data['credit_account'], @@ -103,13 +87,8 @@ def add_incoming(request): @is_logged -def withdraw_attempt(request): - return render(request, 'withdraw.html', {'account_no': request.session["account_no"]}) - - -@is_logged def withdraw_process(request): - return withdraw_attempt(request) + return render(request, 'withdraw.html', {'account_no': request.session["account_no"]}) def create_reserve_at_exchange(request, success_url, reserve_set): diff --git a/talerbank/app/history.py b/talerbank/app/history.py index 1e659c2..ba37f8c 100644 --- a/talerbank/app/history.py +++ b/talerbank/app/history.py @@ -14,16 +14,10 @@ # # @author Marcello Stanisci -from .lib import (get_logged_user_account, - get_public_accounts, - get_bank_account_from_username, - write_log_file, - check_db, - is_logged, - get) +from .lib import get_logged_user_account, get_public_accounts, get_bank_account_from_username, check_db, is_logged from .errors import internal_error_handler -from django.shortcuts import (render, - redirect) +from django.shortcuts import render, redirect +import logging def extract_history(bank_account): @@ -38,34 +32,24 @@ def extract_history(bank_account): return ret -def history_attempt(request): +@is_logged +def history_process(request): user_bank_account = get_logged_user_account(request.session['account_no']) render_history = [] render_history = extract_history(user_bank_account) return render(request, 'history.html', {'history': render_history}) -@check_db -@is_logged -def history_process(request): - return history_attempt(request) - - -@check_db def public_accounts_process(request): - return public_accounts_attempt(request) - - -def public_accounts_attempt(request): accounts = [] for item in get_public_accounts(): accounts.append({'account_name': item.user.username}) - sel_account_name = get(request.GET, 'account') + sel_account_name = request.GET.get('account') if not sel_account_name: - return redirect("/public-accounts/?account=Tor") + return redirect("/public-accounts?account=Tor") sel_account = get_bank_account_from_username(sel_account_name) - if not sel_account: - return internal_error_handler(request) + if sel_account == False: + return internal_error_handler(request, "User '%s' does not exist" % (sel_account_name,)) history = extract_history(sel_account) return render(request, 'public_histories_reloaded.html', diff --git a/talerbank/app/lib.py b/talerbank/app/lib.py index b43caed..63716e6 100644 --- a/talerbank/app/lib.py +++ b/talerbank/app/lib.py @@ -15,47 +15,20 @@ # @author Marcello Stanisci from .models import BankAccount, History -from .errors import (SubPathNotFound, - user_not_logged_handler, - ExchangeUnknown, - CurrencyMismatch, - internal_error_handler, - no_bank_account_handler, - non_existent_db_handler) +from . import errors from .config import explicit_currency from urllib.parse import urlparse from os.path import split from django.contrib.auth.models import User -from django.db.utils import (OperationalError, - ProgrammingError) - - -def get(arr, key, default=False): - if key not in arr: - return default - return arr[key] +from django.db.utils import OperationalError, ProgrammingError +import logging +logger = logging.getLogger(__name__) def get_pin_tan_url(request): return request.build_absolute_uri("/auth/pin/question") -# return the path's part after 'limit' -# example: given /a/b/c and limit='b', returns 'c' -def get_relative_parameter(request, limit): - path = request.path - l = [''] - while True: - p = split(path) - if p[1] == limit: - break - if p[0] == '/' and p[1] == '': - raise SubPathNotFound - l.append(p[1]) - path = p[0] - return l.pop() - - def get_currency(request): switcher = {'bank.demo.taler.net': 'KUDOS', 'bank.test.taler.net': 'PUDOS'} @@ -75,7 +48,7 @@ def check_exchange_account_no(account_no): try: BankAccount.objects.get(account_no=account_no) except BankAccount.DoesNotExist: - raise ExchangeUnknown + raise errors.ExchangeUnknown() def get_exchange_account_no(exchange_baseurl): @@ -83,7 +56,7 @@ def get_exchange_account_no(exchange_baseurl): exchange = get_bank_account_from_username(normalized_url) if exchange: return exchange.account_no - raise ExchangeUnknown + raise errors.ExchangeUnknown() # if the exchange has an account here, it returns its 'username' @@ -108,6 +81,7 @@ def get_bank_account_from_username(username): user_account = User.objects.get(username=username) return user_account.bankaccount except User.DoesNotExist: + logging.warn("user '%s' does not exist", username) return False @@ -119,51 +93,34 @@ def floatify_amount(amount_dict): return amount_dict['value'] + (amount_dict['fraction'] / 1000000) -def write_log_file(data, log_file="/tmp/django.log", flag='a'): - f = open(log_file, flag) - f.write(data) - f.close() - - def check_db(fn): - def fake_query(request): + def wrapper(request): + logging.error("doing check_db") try: User.objects.get(username='Bank') except User.DoesNotExist: - return no_bank_account_handler(request) + logging.error("user does not exist") + return errors.no_bank_account_handler(request) except ProgrammingError: - return internal_error_handler(request, + logging.error("internal error, db has no tables") + return errors.internal_error_handler(request, "(db available but no tables in it. Run" " 'taler-bank-manage --definetables')") except OperationalError: - return non_existent_db_handler(request) + logging.error("db does not exist") + return errors.non_existent_db_handler(request) return fn(request) - return fake_query + return wrapper def is_logged(fn): def check_login(request): if "account_no" not in request.session: - return user_not_logged_handler(request) + return errors.user_not_logged_handler(request) return fn(request) return check_login -# FIXME to be obsoleted by 'wire_tranfer()' -def transfer_in(amount, account_no, wtid, counterpart="unknown"): - account = BankAccount.objects.get(account_no=account_no) - float_amount = floatify_amount(amount) - account.balance += float_amount - account.save() - history_item = History(amount=float_amount, - currency=amount['currency'], - direction="IN", - counterpart=counterpart, - subject=wtid, - account=account) - history_item.save() - - def wire_transfer_in_out(amount, debit, credit, @@ -190,7 +147,8 @@ def wire_transfer(amount, counterpart="unknown"): account = BankAccount.objects.get(account_no=account_no) if account.currency != amount['currency']: - raise CurrencyMismatch + logger.error("currency %s and currency %s mismatch", account.currency, amount['currency']) + raise errors.CurrencyMismatch() float_amount = floatify_amount(amount) if "IN" == direction: account.balance += float_amount diff --git a/talerbank/app/management/commands/basic_accounts.py b/talerbank/app/management/commands/basic_accounts.py deleted file mode 100644 index 78435ba..0000000 --- a/talerbank/app/management/commands/basic_accounts.py +++ /dev/null @@ -1,26 +0,0 @@ -""" - This file is part of TALER - (C) 2014, 2015, 2106 INRIA - - TALER is free software; you can redistribute it and/or modify it under the - terms of the GNU 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. - - You should have received a copy of the GNU General Public License along with - TALER; see the file COPYING. If not, If not, see <http://www.gnu.org/licenses/> - - @author Marcello Stanisci -""" -from django.core.management.base import BaseCommand -from django.contrib.auth.models import User -from django.db.utils import OperationalError -from ...startup import basic_accounts - - -class Command(BaseCommand): - def handle(self, *args, **options): - basic_accounts() diff --git a/talerbank/app/management/commands/pre_accounts.py b/talerbank/app/management/commands/pre_accounts.py deleted file mode 100644 index 35e8bd1..0000000 --- a/talerbank/app/management/commands/pre_accounts.py +++ /dev/null @@ -1,53 +0,0 @@ -""" - This file is part of TALER - (C) 2014, 2015, 2106 INRIA - - TALER is free software; you can redistribute it and/or modify it under the - terms of the GNU 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. - - You should have received a copy of the GNU General Public License along with - TALER; see the file COPYING. If not, If not, see <http://www.gnu.org/licenses/> - - @author Marcello Stanisci -""" -from django.core.management.base import BaseCommand -from django.db.utils import DataError -from django.contrib.auth.models import User -from django.db.utils import OperationalError -from ...models import BankAccount -from ...lib import get_currency -from ...lib import write_log_file -from ...config import pre_accounts - - -def make_accounts(): - for u in pre_accounts: - print("Processing " + u) - try: - User.objects.get(username=u) - except OperationalError: - print("Please create DB before running this option") - return - except User.DoesNotExist: - try: - a = User.objects.create_user(username=u, password='') - except DataError: - print("Given username exceeded 30 chars, please make it shorter!") - return - is_public = not (u == 'http://mint.test.taler.net' or - u == 'http://mint.demo.taler.net') - b = BankAccount(user=a, - currency=get_currency(None), - is_public=is_public) - b.save() - print (" getting account number " + str(b.account_no)) - - -class Command(BaseCommand): - def handle(self, *args, **options): - make_accounts() diff --git a/talerbank/app/management/commands/provide_accounts.py b/talerbank/app/management/commands/provide_accounts.py new file mode 100644 index 0000000..93f4306 --- /dev/null +++ b/talerbank/app/management/commands/provide_accounts.py @@ -0,0 +1,80 @@ +""" + This file is part of TALER + (C) 2014, 2015, 2106 INRIA + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU 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. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, If not, see <http://www.gnu.org/licenses/> + + @author Marcello Stanisci + @author Florian Dold +""" + +import sys +import logging +from django.apps import AppConfig +from django.contrib.auth.models import User +from django.db.utils import ProgrammingError, DataError +from django.core.management.base import BaseCommand +from ...lib import get_currency +from ...models import BankAccount +from ...config import pre_accounts, expects_donations + +logger = logging.getLogger(__name__) + +def demo_accounts(): + for name in pre_accounts: + try: + User.objects.get(username=name) + except ProgrammingError as e: + logger.error("DB does not exist") + sys.exit(1) + except User.DoesNotExist: + try: + a = User.objects.create_user(username=name, password='') + except DataError: + logger.error("Given username exceeded 30 chars, please make it shorter!") + return + is_public = not (name == 'http://mint.test.taler.net' or + name == 'http://mint.demo.taler.net') + b = BankAccount(user=a, + currency=get_currency(None), + is_public=is_public) + b.save() + logger.info("Creating account '%s' with number %s", name, b.account_no) + + +def ensure_account(name): + try: + bank = User.objects.get(username=name) + except ProgrammingError: + logging.error("Please create DB before running the bank") + sys.exit(1) + except User.DoesNotExist: + user = User.objects.create_user(username=name, password='') + acc = BankAccount(user=user, + currency=get_currency(None), + is_public=True) + acc.save() + logger.info("Creating account '%s', with number %s", name, acc.account_no) + + +def basic_accounts(): + ensure_account("Bank") + ensure_account("Exchange") + + +class Command(BaseCommand): + help = "Provide initial user accounts" + + def handle(self, *args, **options): + basic_accounts() + demo_accounts() + diff --git a/talerbank/app/management/commands/sample_donations.py b/talerbank/app/management/commands/sample_donations.py index 06e4599..253f0ae 100644 --- a/talerbank/app/management/commands/sample_donations.py +++ b/talerbank/app/management/commands/sample_donations.py @@ -18,10 +18,7 @@ from random import randint from django.core.management.base import BaseCommand -from ...lib import (write_log_file, - get_public_accounts, - get_currency, - wire_transfer_in_out) +from ...lib import get_public_accounts, get_currency, wire_transfer_in_out from ...config import expects_donations from ...models import BankAccount diff --git a/talerbank/app/migrations/0001_initial.py b/talerbank/app/migrations/0001_initial.py index d92797c..703e17d 100644 --- a/talerbank/app/migrations/0001_initial.py +++ b/talerbank/app/migrations/0001_initial.py @@ -1,12 +1,11 @@ # -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-04-08 14:17 from __future__ import unicode_literals - +import logging from django.conf import settings from django.db import migrations, models import django.db.models.deletion - class Migration(migrations.Migration): initial = True diff --git a/talerbank/app/models.py b/talerbank/app/models.py index 047d367..f86bcc5 100644 --- a/talerbank/app/models.py +++ b/talerbank/app/models.py @@ -39,12 +39,3 @@ class History(models.Model): subject = models.CharField(default="not given", max_length=200) date = models.DateField(auto_now=True) account = models.ForeignKey(BankAccount, on_delete=models.CASCADE) - - def set_balance(self, new_balance): - if isinstance(new_balance, int) or isinstance(new_balance, float): - self.balance = new_balance - else: - print("Not a number given for new balance") - - def push_history(self, obj): - self.history.append(obj) diff --git a/talerbank/app/schemas.py b/talerbank/app/schemas.py index ad19f20..4a8ba60 100644 --- a/talerbank/app/schemas.py +++ b/talerbank/app/schemas.py @@ -15,9 +15,7 @@ # @author Marcello Stanisci import validictory -from .errors import (BadIncomingRequest, - BadWireDetails, - BadAmount) +from .errors import BadIncomingRequest, BadWireDetails, BadAmount # definitions of JSON schemas for validating data @@ -50,7 +48,7 @@ class Schemas: try: validictory.validate(amount, schema) except (ValueError, TypeError): - raise BadAmount + raise BadAmount() return True @staticmethod @@ -58,7 +56,7 @@ class Schemas: try: validictory.validate(wiredetails, schema) except (ValueError, TypeError): - raise BadWireDetails + raise BadWireDetails() return True @@ -67,5 +65,5 @@ class Schemas: try: validictory.validate(incoming_request, schema) except (ValueError, TypeError): - raise BadIncomingRequest + raise BadIncomingRequest() return True diff --git a/talerbank/app/startup.py b/talerbank/app/startup.py deleted file mode 100644 index c1ec825..0000000 --- a/talerbank/app/startup.py +++ /dev/null @@ -1,57 +0,0 @@ -# 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 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, If not, see <http://www.gnu.org/licenses/> -# -# @author Marcello Stanisci -# @file Container for routines to be run at startup - -from .models import BankAccount -from django.contrib.auth.models import User -from django.db.utils import OperationalError -from .lib import get_currency -import sys - -# Creates basic accounts (bank's and exchange's) if the user didn't manually - -def basic_accounts(): - try: - if sys.argv[1] != 'runserver' and sys.argv[1] != 'basic_accounts' \ - and sys.argv[1] != 'sample_donations': - print("basic_accounts() not supposed to be fired..") - print(sys.argv) - return - except IndexError: - print("Got IndexError, unmanaged..") - return - try: - bank = User.objects.get(username='Bank') - print("Basic accounts found\n") - except OperationalError: - print("Please create DB before running the bank") - sys.exit() - # bank not existent, so neither other accounts are - except User.DoesNotExist: - print("Basic accounts not found..\n") - bank = User.objects.create_user(username='Bank', password='') - exchange = User.objects.create_user(username='Exchange', password='') - bank_ba = BankAccount(user=bank, - currency=get_currency(None), - is_public=True) - bank_ba.save() - print("Creating '" + bank_ba.user.username + "' account, with number " + str(bank_ba.account_no) + "\n") - exchange_ba = BankAccount(user=exchange, - currency=get_currency(None), - is_public=True) - exchange_ba.save() - print("Creating '" + exchange_ba.user.username + "' account, with number " + str(exchange_ba.account_no) + "\n") - diff --git a/talerbank/app/templates/error.html b/talerbank/app/templates/error.html index 1878583..adda120 100644 --- a/talerbank/app/templates/error.html +++ b/talerbank/app/templates/error.html @@ -64,7 +64,7 @@ {% if type = "wrong_pin" %} Return to your <a href="/profile">profile page</a> {% elif type = "internal_error" %} - Resource unavailable {{ hint }} + Internal error: {{ hint }} {% elif type = "non_supported_method" %} This bank supports TEST wire method only {% elif type = "exchange_unknown" %} diff --git a/talerbank/app/templates/public_histories_reloaded.html b/talerbank/app/templates/public_histories_reloaded.html index 4551326..e3acc58 100644 --- a/talerbank/app/templates/public_histories_reloaded.html +++ b/talerbank/app/templates/public_histories_reloaded.html @@ -44,7 +44,7 @@ {% for item in public_accounts %} <td width="12%" align="center"> <a id="{{ item.account_name }}" - href="/public-accounts/?account={{ item.account_name }}"> + href="/public-accounts?account={{ item.account_name }}"> {{ item.account_name }} </a> diff --git a/talerbank/app/test.py b/talerbank/app/test.py deleted file mode 100644 index a22a3ce..0000000 --- a/talerbank/app/test.py +++ /dev/null @@ -1,29 +0,0 @@ -# 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 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, If not, see <http://www.gnu.org/licenses/> -# -# @author Marcello Stanisci - -from .lib import check_db - - -def check_db_test_process(request): - # this indirection is needed since is not possible - # to call "decorated" functions without importing the - # decorator in urls.py as well - return check_db_test_attempt(request) - - -@check_db -def check_db_test_attempt(request): - pass diff --git a/talerbank/app/urls.py b/talerbank/app/urls.py index 7269ddb..73ad09c 100644 --- a/talerbank/app/urls.py +++ b/talerbank/app/urls.py @@ -20,16 +20,15 @@ from . import views urlpatterns = [ url(r'^$', views.home_page), url(r'^favicon\.ico$', views.ignore), - url(r'check-db-test', views.check_db_test_process), - url(r'register', views.register_process), - url(r'login', views.login_process), - url(r'logout', views.logout_process), - url(r'withdraw', views.withdraw_process), - url(r'public-accounts/details', views.view_public_accno_process), - url(r'public-accounts', views.public_accounts_process), - url(r'pin/question', views.pin_tan_question), - url(r'pin/verify', views.pin_tan_verify), - url(r'add/incoming', views.add_incoming_attempt), - url(r'profile', views.profile_process), - url(r'history', views.history_process) + url(r'^register$', views.register_process), + url(r'^login$', views.login_process), + url(r'^logout$', views.logout_process), + url(r'^withdraw$', views.withdraw_process), + url(r'^public-accounts/details$', views.view_public_accno_process), + url(r'^public-accounts$', views.public_accounts_process), + url(r'^pin/question$', views.pin_tan_question), + url(r'^pin/verify$', views.pin_tan_verify), + url(r'^add/incoming$', views.add_incoming_attempt), + url(r'^profile$', views.profile_process), + url(r'^history$', views.history_process) ] diff --git a/talerbank/app/user_mgmt.py b/talerbank/app/user_mgmt.py index 67a1859..60716ad 100644 --- a/talerbank/app/user_mgmt.py +++ b/talerbank/app/user_mgmt.py @@ -14,23 +14,14 @@ # # @author Marcello Stanisci -from django.contrib.auth import (authenticate, - login, - logout) +from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User -from .lib import (write_log_file, - is_logged, - check_db, - get, - get_currency) -from .util import (get_central_page, - LoginForm) +from .lib import is_logged, check_db, get_currency +from .util import get_central_page, LoginForm from .models import BankAccount from .errors import bad_get_parameter_handler -from .lib import (wire_transfer_in_out, - get_bank_account_from_username) -from django.shortcuts import (render, - redirect) +from .lib import wire_transfer_in_out, get_bank_account_from_username +from django.shortcuts import render, redirect from django import forms from random import randint import django.db @@ -41,8 +32,11 @@ class UserReg(forms.Form): password = forms.CharField(widget=forms.PasswordInput()) -# register a new user giving 100 KUDOS bonus -def register_attempt(request): +@check_db +def register_process(request): + """ + register a new user giving 100 KUDOS bonus + """ wrong_field = False not_available = False if request.method == 'POST': @@ -76,7 +70,8 @@ def register_attempt(request): 'not_available': not_available}) -def login_attempt(request): +@check_db +def login_process(request): if "account_no" in request.session: return get_central_page(request) if request.method == 'POST': @@ -99,15 +94,18 @@ def login_attempt(request): return render(request, 'login.html', {'form': form, 'currency': get_currency(request)}) -def logout_attempt(request): +@check_db +@is_logged +def logout_process(request): del request.session["account_no"] logout(request) request.session['logged_out'] = True return redirect("/") -def view_public_accno_attempt(request): - account_name = get(request.GET, 'account') +@check_db +def view_public_accno_process(request): + account_name = request.GET.get('account') if not account_name: return bad_get_parameter_handler(request) # FIXME the following function must be exception-driven @@ -124,23 +122,3 @@ def view_public_accno_attempt(request): {'account_no': bank_account.account_no, 'account_name': account_name}) - -@check_db -def login_process(request): - return login_attempt(request) - - -@check_db -@is_logged -def logout_process(request): - return logout_attempt(request) - - -@check_db -def register_process(request): - return register_attempt(request) - - -@check_db -def view_public_accno_process(request): - return view_public_accno_attempt(request) diff --git a/talerbank/app/views.py b/talerbank/app/views.py index 47d98b7..a1b7754 100644 --- a/talerbank/app/views.py +++ b/talerbank/app/views.py @@ -14,27 +14,12 @@ # # @author Marcello Stanisci -from .user_mgmt import (register_process, - login_process, - view_public_accno_process, - logout_process) -from .captcha import (pin_tan_question_attempt, - pin_tan_question, - pin_tan_verify) -from .funds_mgmt import (withdraw_process, - add_incoming_attempt) -from .history import (history_process, - public_accounts_process) -from .util import (home_page, - profile_process) -from .test import check_db_test_process +from .user_mgmt import register_process, login_process, view_public_accno_process, logout_process +from .captcha import pin_tan_question_attempt, pin_tan_question, pin_tan_verify +from .funds_mgmt import withdraw_process, add_incoming_attempt +from .history import history_process, public_accounts_process +from .util import home_page, profile_process from django.http import HttpResponse -from .startup import basic_accounts - def ignore(request): return HttpResponse() - - -# create basic accounts if they don't exist -basic_accounts() |