summaryrefslogtreecommitdiff
path: root/talerbank/app/views.py
blob: ed89f6d10f09298687192ebf2374c17111ed8dfc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
#  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, see <http://www.gnu.org/licenses/>
#
#  @author Marcello Stanisci
#  @author Florian Dold

from urllib.parse import urljoin
from functools import wraps
import json
import logging
import time
import hashlib
import random
import re
import requests
import django.contrib.auth
import django.contrib.auth.views
import django.contrib.auth.forms
from django.db import transaction
from django import forms
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST, require_GET
from django.views.decorators.http import require_http_methods
from django.urls import reverse
from django.contrib.auth.models import User
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 .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_reject_request)

LOGGER = logging.getLogger(__name__)

class DebtLimitExceededException(Exception):
    def __init__(self) -> None:
        super().__init__("Debt limit exceeded")

class SameAccountException(Exception):
    pass

class MyAuthenticationForm(django.contrib.auth.forms.AuthenticationForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["username"].widget.attrs["autofocus"] = True
        self.fields["username"].widget.attrs["placeholder"] = "Username"
        self.fields["password"].widget.attrs["placeholder"] = "Password"

def ignore(request):
    del request
    return HttpResponse()

def login_view(request):
    just_logged_out = get_session_flag(request, "just_logged_out")
    response = django.contrib.auth.views.login(
        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

def get_session_flag(request, name):
    """
    Get a flag from the session and clear it.
    """
    if name in request.session:
        del request.session[name]
        return True
    return False


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)
    counterpart = forms.IntegerField()
    subject = forms.CharField()

# Check if user's logged in.  Check if he/she has withdrawn or
# registered; render profile page.

@login_required
def profile_page(request):
    info_bar = None
    if request.method == "POST":
        wtf = WTForm(request.POST)
        if wtf.is_valid():
            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"))
                request.session["just_wire_transferred"] = True
            except BankAccount.DoesNotExist:
                request.session["wire_transfer_error"] = True
                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!"
    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),
        sign="-" if user_account.debit else "",
        precision=settings.TALER_DIGITS,
        currency=user_account.amount.currency,
        account_no=user_account.account_no,
        wt_form=wtf,
        history=history,
        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,
        info_bar=info_bar
    )
    if settings.TALER_SUGGESTED_EXCHANGE:
        context["suggested_exchange"] = settings.TALER_SUGGESTED_EXCHANGE

    response = render(request, "profile_page.html", context)
    if just_withdrawn:
        response["X-Taler-Operation"] = "confirm-reserve"
        response["X-Taler-Reserve-Pub"] = reserve_pub
        response.status_code = 202
    return response


def hash_answer(ans):
    hasher = hashlib.new("sha1")
    hasher.update(settings.SECRET_KEY.encode("utf-8"))
    hasher.update(ans.encode("utf-8"))
    return hasher.hexdigest()

def make_question():
    num1 = random.randint(1, 10)
    op = random.choice(("*", "+", "-"))
    num2 = random.randint(1, 10)
    if op == "*":
        answer = str(num1 * num2)
    elif op == "-":
        # ensure result is positive
        num1, num2 = max(num1, num2), min(num1, num2)
        answer = str(num1 - num2)
    else:
        answer = str(num1 + num2)
    question = "{} {} {}".format(num1, op, num2)
    return question, hash_answer(answer)


@require_GET
@login_required
def pin_tan_question(request):
    try:
        validate_pin_tan_args(request.GET.dict())
        # Currency is not checked, as any mismatches will be
        # detected afterwards
    except (FVE, RFVE) 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"]
    amount = Amount(request.GET["amount_currency"],
                    int(request.GET["amount_value"]),
                    int(request.GET["amount_fraction"]))
    request.session["amount"] = amount.dump()
    request.session["exchange_url"] = request.GET["exchange"]
    request.session["reserve_pub"] = request.GET["reserve_pub"]
    request.session["sender_wiredetails"] = dict(
        type="test",
        bank_uri=request.build_absolute_uri(reverse("index")),
        account_number=user_account.account_no
    )
    previous_failed = get_session_flag(request, "captcha_failed")
    question, hashed_answer = make_question()
    context = dict(
        question=question,
        hashed_answer=hashed_answer,
        amount=amount.stringify(settings.TALER_DIGITS),
        previous_failed=previous_failed,
        exchange=request.GET["exchange"])
    return render(request, "pin_tan.html", context)


@require_POST
@login_required
def pin_tan_verify(request):
    hashed_attempt = hash_answer(request.POST.get("pin_0", ""))
    hashed_solution = request.POST.get("pin_1", "")
    if hashed_attempt != hashed_solution:
        LOGGER.warning("Wrong CAPTCHA answer: %s vs %s",
                       type(hashed_attempt),
                       type(request.POST.get("pin_1")))
        request.session["captcha_failed"] = True
        return redirect(request.POST.get("question_url", "profile"))
    # Check the session is a "pin tan" one
    try:
        check_withdraw_session(request.session)
        amount = Amount(**request.session["amount"])
        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"],
                      request=request,
                      session_expand=dict(debt_limit=True))
    except (FVE, RFVE) as exc:
        LOGGER.warning("Not a withdrawing session")
        return redirect("profile")

    except BankAccount.DoesNotExist as exc:
        return JsonResponse({"error": "That exchange is unknown to this bank"},
                            status=404)
    except WireTransferException as exc:
        return exc.response
    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",
                      {"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())


def register(request):
    """
    register a new user giving 100 KUDOS bonus
    """
    if request.method != "POST":
        return render(request, "register.html")
    form = UserReg(request.POST)
    if not form.is_valid():
        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))
    with transaction.atomic():
        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)
    try:
        wire_transfer(Amount(settings.TALER_CURRENCY, 100, 0),
                      bank_internal_account,
                      user_account,
                      "Joining bonus",
                      request=request,
                      session_expand=dict(no_initial_bobus=True))
    except WireTransferException as exc:
        return exc.response
    request.session["just_registered"] = True
    user = django.contrib.auth.authenticate(username=username, password=password)
    django.contrib.auth.login(request, user)
    return redirect("profile")


def logout_view(request):
    """
    Log out the user and redirect to index page.
    """
    django.contrib.auth.logout(request)
    request.session["just_logged_out"] = True
    return redirect("index")


def extract_history(account):
    history = []
    related_transactions = BankTransaction.objects.filter(
        Q(debit_account=account) | Q(credit_account=account))
    for item in related_transactions:
        if item.credit_account == account:
            counterpart = item.debit_account
            sign = ""
        else:
            counterpart = item.credit_account
            sign = "-"
        entry = dict(
            sign=sign,
            amount=item.amount.stringify(settings.TALER_DIGITS),
            counterpart=counterpart.account_no,
            counterpart_username=counterpart.user.username,
            subject=item.subject,
            date=item.date.strftime("%d/%m/%y %H:%M"),
        )
        history.append(entry)
    return history


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, BankAccount.DoesNotExist):
        return HttpResponse("account '{}' not found".format(name), status=404)
    public_accounts = BankAccount.objects.filter(is_public=True)
    history = extract_history(account)
    context = dict(
        public_accounts=public_accounts,
        selected_account=dict(
            name=name,
            number=account.account_no,
            history=history,
        )
    )
    return render(request, "public_accounts.html", context)

def login_via_headers(view_func):
    def _decorator(request, *args, **kwargs):
        user_account = auth_and_login(request)
        if not user_account:
            LOGGER.error("authentication failed")
            return JsonResponse(dict(error="authentication failed"),
                                status=401)
        return view_func(request, user_account, *args, **kwargs)
    return wraps(view_func)(_decorator)

@require_GET
@login_via_headers
def serve_history(request, user_account):
    """
    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},
                            status=400)

    # delta
    parsed_delta = re.search(r"([\+-])?([0-9]+)",
                             request.GET.get("delta"))
    sign = parsed_delta.group(1)
    # start
    start = int(request.GET.get("start", -1))

    # translating delta's sign into query object
    sign_filter = Q()
    if start >= 0:
        sign_filter = Q(id__gt=start)
        if sign == "-":
            sign_filter = Q(id__lt=start)

    direction_switch = {
        "both": Q(debit_account=user_account.bankaccount) \
                | Q(credit_account=user_account.bankaccount),
        "credit": Q(credit_account=user_account.bankaccount),
        "debit": Q(debit_account=user_account.bankaccount),
        "cancel+": Q(credit_account=user_account.bankaccount) \
                      & Q(cancelled=True),
        "cancel-": Q(debit_account=user_account.bankaccount) \
                      & Q(cancelled=True)
    }
    # Sanity checks are done at the beginning, so 'direction' key
    # (and its value as switch's key) does exist here.
    query_string = direction_switch[request.GET["direction"]]
    history = []

    qs = BankTransaction.objects.filter(
        query_string, sign_filter).order_by(
            "-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:
            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())) + ")/"))
    return JsonResponse(dict(data=history), status=200)


def auth_and_login(request):
    """Return user instance after checking authentication
       credentials, False if errors occur"""

    auth_type = None
    if request.method in ["POST", "PUT"]:
        data = json.loads(request.body.decode("utf-8"))
        auth_type = data["auth"]["type"]
    if request.method == "GET":
        auth_type = request.GET.get("auth")
    if auth_type != "basic":
        LOGGER.error("auth method not supported")
        return False

    username = request.META.get("HTTP_X_TALER_BANK_USERNAME")
    password = request.META.get("HTTP_X_TALER_BANK_PASSWORD")
    LOGGER.info("Trying to log '%s/%s' in" % (username, password))
    if not username or not password:
        LOGGER.error("user or password not given")
        return False
    return django.contrib.auth.authenticate(username=username,
                                            password=password)

@transaction.atomic
@csrf_exempt
@require_http_methods(["PUT", "POST"])
@login_via_headers
def reject(request, user_account):
    data = json.loads(request.body.decode("utf-8"))
    try:
        validate_reject_request(data)
    except (FVE, RFVE) as exc:
        LOGGER.error("invalid %s" % exc.fieldname)
        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
    trans.cancelled = True
    trans.save()
    try:
        wire_transfer(trans.amount, user_account.bankaccount,
                      trans.debit_account, "/reject: reimbursement",
                      reimburses=trans)
    except WireTransferException as exc:
        # Logging the error is taken care of wire_transfer()
        return exc.response

    return HttpResponse(status=204)


@csrf_exempt
@require_POST
@login_via_headers
def add_incoming(request, user_account):
    """
    Internal API used by exchanges to notify the bank
    of incoming payments.

    This view is CSRF exempt, since it is not used from
    within the browser, and only over the private admin interface.
    """
    data = json.loads(request.body.decode("utf-8"))
    try:
        # 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)


    subject = "%s %s" % (data["subject"], data["exchange_url"])
    try:
        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"]},
                            status=404)
    except WireTransferException as exc:
        return exc.response
    return JsonResponse({"row_id": wtrans.id,
                         "timestamp":
                             "/Date(%s)/" % int(wtrans.date.timestamp())})


@login_required
@require_POST
def withdraw_nojs(request):

    try:
        amount = Amount.parse(request.POST.get("kudos_amount", ""))
    except BadFormatAmount:
        LOGGER.error("Amount did not pass parsing")
        return HRBR()

    user_account = BankAccount.objects.get(user=request.user)

    response = HttpResponse(status=202)
    response["X-Taler-Operation"] = "create-reserve"
    response["X-Taler-Callback-Url"] = reverse("pin-question")
    response["X-Taler-Wt-Types"] = '["test"]'
    response["X-Taler-Amount"] = json.dumps(amount.dump())
    response["X-Taler-Sender-Wire"] = json.dumps(dict(
        type="test",
        bank_uri=request.build_absolute_uri(reverse("index")),
        account_number=user_account.account_no
    ))
    if settings.TALER_SUGGESTED_EXCHANGE:
        response["X-Taler-Suggested-Exchange"] = settings.TALER_SUGGESTED_EXCHANGE
    return response

class WireTransferException(Exception):
    def __init__(self, exc, response):
        self.exc = exc
        self.response = response
        super().__init__()

def wire_transfer(amount,
                  debit_account,
                  credit_account,
                  subject,
                  **kwargs):

    def err_cb(exc, resp):
        LOGGER.error(str(exc))
        raise WireTransferException(exc, resp)

    def wire_transfer_internal(amount,
                               debit_account,
                               credit_account,
                               subject,
                               reimburses=None):
        LOGGER.info("%s => %s, %s, %s" %
                    (debit_account.account_no,
                     credit_account.account_no,
                     amount.stringify(2),
                     subject))
        if debit_account.pk == credit_account.pk:
            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)
        if debit_account.debit:
            debit_account.amount.add(amount)

        elif -1 == Amount.cmp(debit_account.amount, amount):
            debit_account.debit = True
            tmp = Amount(**amount.dump())
            tmp.subtract(debit_account.amount)
            debit_account.amount.set(**tmp.dump())
        else:
            debit_account.amount.subtract(amount)

        if not credit_account.debit:
            credit_account.amount.add(amount)
        elif Amount.cmp(amount, credit_account.amount) == 1:
            credit_account.debit = False
            tmp = Amount(**amount.dump())
            tmp.subtract(credit_account.amount)
            credit_account.amount.set(**tmp.dump())
        else:
            credit_account.amount.subtract(amount)

        # Check here if any account went beyond the allowed
        # debit threshold.

        threshold = Amount.parse(settings.TALER_MAX_DEBT)
        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:
            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():
            debit_account.save()
            credit_account.save()
            transaction_item.save()

        return transaction_item

    try:
        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"])
            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))