summaryrefslogtreecommitdiff
path: root/talerbank/app/views.py
blob: c97d86be35b4ae71c110f980c62f45853154e633 (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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
##
# This file is part of TALER
# (C) 2014, 2015, 2016 Taler Systems SA
#
# 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 functools import wraps
import math
import json
import logging
import hashlib
import random
import re
from urllib.parse import urlparse
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
from django.shortcuts import render, redirect
from django.core.exceptions import ObjectDoesNotExist
from datetime import datetime
from .models import BankAccount, BankTransaction, TalerWithdrawOperation
from taler.util.amount import Amount
import qrcode
import qrcode.image.svg
import lxml
from .schemas import (
    HistoryParams, HistoryRangeParams, URLParamValidationError, RejectData,
    AddIncomingData, JSONFieldException, PinTanParams, InvalidSession,
    WithdrawSessionData, WithdrawHeadless, WithdrawHeadlessUri
)

LOGGER = logging.getLogger(__name__)

##
# 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).
UINT64_MAX = (2**64) - 1

##
# Exception raised upon failing login.
#
class LoginFailed(Exception):
    hint = "Wrong username/password"
    http_status_code = 401
    taler_error_code = 5109

class InvalidInputData(Exception):
    def __init__(self, msg):
        super().__init__(msg)


class UsernameUnavailable(Exception):
    pass


##
# Exception raised when the public history from
# a ordinary user account is tried to be accessed.
class PrivateAccountException(Exception):
    hint = "The selected account is private"
    http_status_code = 402


##
# Exception raised when some financial operation goes
# beyond the limit threshold.
class DebitLimitException(Exception):
    hint = "Insufficient credit, operation not acceptable."
    http_status_code = 406
    taler_error_code = 5103


##
# Exception raised when some financial operation is
# attempted and both parties are the same account number.
#
class SameAccountException(Exception):
    hint = "Debit and credit account are the same."
    http_status_code = 403
    taler_error_code = 5102


##
# Exception raised when someone tries to reject a
# transaction, but they have no rights to accomplish
# such operation.
class RejectNoRightsException(Exception):
    hint = "You weren't the transaction credit account, " \
           "no rights to reject."
    http_status_code = 403
    taler_error_code = 5200

class UnhandledException(Exception):
    hint = "Unhandled exception happened!"
    http_status_code = 500
    taler_error_code = 5300




##
# The authentication for users to log in the bank.
#
class TalerAuthenticationForm(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"


##
# Return a empty response.  Used in "/favicon.ico" requests.
#
def ignore(request):
    del request
    return HttpResponse()


##
# Decode body, when it is expected to be UTF-8.
#
# @param request the HTTP request being served.
# @return the body as string.
def decode_body(request):
    return request.body.decode("utf-8")

##
# Get a flag from the session and clear it.
#
# @param request the HTTP request being served.
# @param name name of the session value that should be retrieved.
# @return the value, if found; otherwise False.
def get_session_flag(request, name):
    if name in request.session:
        ret = request.session[name]
        del request.session[name]
        return ret
    return False


##
# Get a hint from the session and clear it.  A 'hint' is a
# "message" that different parts of the bank can send to each
# other - via the state - communicating what is the state of
# the HTTP session.
#
# @param request the HTTP request being served.
# @param name hint name
# @return the hint (a "null" one if none was found)
def get_session_hint(request, name):
    if name in request.session:
        ret = request.session[name]
        del request.session[name]
        return ret
    # Fail message, success message, hint.
    return False, False, None


##
# Build the list containing all the predefined accounts; the
# list contains, for example, the exchange, the bank itself, and
# all the public accounts (like GNUnet / Tor / FSF / ..)
def predefined_accounts_list():
    account = 2
    ret = []
    for i in settings.TALER_PREDEFINED_ACCOUNTS[1:]:
        ret.append((account, "%s (#%d)" % (i, account)))
        account += 1
    return ret


##
# Thanks to [1], this class provides a dropdown menu that
# can be used within a <select> element, in a <form>.
# [1] https://stackoverflow.com/questions/24783275/django-form-with-choices-but-also-with-freetext-option
class InputDatalist(forms.TextInput):

    ##
    # Constructor function.
    #
    # @param self the object itself.
    # @param datalist a list of admitted values.
    # @param name the name of the value that will be sent
    #        along the POST.
    # @param args positional arguments
    # @param kwargs keyword arguments
    # @return the object
    def __init__(self, datalist, name, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._name = name
        self._datalist = datalist()
        self.attrs.update({"list": "%slist" % name, "pattern": "[1-9]+[0-9]*"})

    ##
    # Method that produces the final HTML from the object itself.
    #
    # @param self the object itself
    # @param name the name of the value that will be sent
    #        along the POST
    # @param value value to be sent along the @a name.
    # @param attrs a dict indicating which HTML attribtues should
    #        be defined in the rendered element.
    # @param renderer render engine (left as None, typically); it
    #        is a class that respects the low-level render API from
    #        Django, see [2]
    # [2] https://docs.djangoproject.com/en/2.1/ref/forms/renderers/#low-level-widget-render-api
    def render(self, name, value, attrs=None, renderer=None):
        html = super().render(name, value, attrs=attrs, renderer=renderer)
        datalist = '<datalist id="%slist">' % self._name
        for dl_value, dl_text in self._datalist:
            datalist += '<option value="%s">%s</option>' \
                % (dl_value, dl_text)
        datalist += "</datalist>"
        return html + datalist


##
# Form for sending wire transfers.  It usually appears in the
# user profile page.
#
class WTForm(forms.Form):
    amount = forms.FloatField(
        min_value=0.1,
        widget=forms.NumberInput(attrs={"class": "currency-input"})
    )
    receiver = forms.IntegerField(
        min_value=1, widget=InputDatalist(predefined_accounts_list, "receiver")
    )
    subject = forms.CharField()


##
# This method serves the profile page, which is the main
# page where the user interacts with the bank, and also the
# page that the user gets after a successful login.  It has
# to handle the following cases: (1) the user requests the
# profile page after haing POSTed a wire transfer request.
# (2) The user requests the page after having withdrawn coins,
# that means that a wire transfer has been issued to the exchange.
# In this latter case, the method has to notify the wallet about
# the operation outcome.  (3) Ordinary GET case, where the
# straight page should be returned.
#
# @param request Django-specific HTTP request object.
# @return Django-specific HTTP response object.
@login_required
def profile_page(request):
    if request.method == "POST":
        # WTForm ~ Wire Transfer Form.
        wtf = WTForm(request.POST)
        if wtf.is_valid():
            amount_parts = (
                settings.TALER_CURRENCY, wtf.cleaned_data.get("amount") + 0.0
            )
            wire_transfer(
                Amount.parse("%s:%s" % amount_parts),
                BankAccount.objects.get(user=request.user),
                BankAccount.objects.get(
                    account_no=wtf.cleaned_data.get("receiver")
                ), wtf.cleaned_data.get("subject")
            )
            request.session["profile_hint"
                            ] = False, True, "Wire transfer successful!"
            return redirect("profile")
    wtf = WTForm()
    fail_message, success_message, hint = get_session_hint(
        request, "profile_hint"
    )
    context = dict(
        name=request.user.username,
        balance=request.user.bankaccount.amount,
        sign="-" if request.user.bankaccount.debit else "",
        fail_message=fail_message,
        success_message=success_message,
        hint=hint,
        precision=settings.TALER_DIGITS,
        currency=request.user.bankaccount.amount.currency,
        account_no=request.user.bankaccount.account_no,
        wt_form=wtf,
        history=extract_history(
            request.user.bankaccount, -1 * (UINT64_MAX / 2 / 2)
        )
    )
    if settings.TALER_SUGGESTED_EXCHANGE:
        context["suggested_exchange"] = settings.TALER_SUGGESTED_EXCHANGE

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


##
# Helper function that hashes its input.  Usually
# used to hash the response to the math CAPTCHA.
#
# @param ans the plain text answer to hash.
# @return the hashed version of @a ans.
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()


##
# Helper function that makes CAPTCHA's question and
# answer pair.
#
# @return the question and (hashed) answer pair.
def make_question():
    num1 = random.randint(1, 10)
    operand = random.choice(("*", "+", "-"))
    num2 = random.randint(1, 10)
    if operand == "*":
        answer = str(num1 * num2)
    elif operand == "-":
        # ensure result is positive
        num1, num2 = max(num1, num2), min(num1, num2)
        answer = str(num1 - num2)
    else:
        answer = str(num1 + num2)
    question = "{} {} {}".format(num1, operand, num2)
    return question, hash_answer(answer)


def get_acct_from_payto(uri_str: str) -> int:
    wire_uri = urlparse(uri_str)
    if wire_uri.scheme != "payto":
        raise Exception("Bad Payto URI: '%s'" % uri_str)
    return int(wire_uri.path.split("/")[-1])


##
# Class representing the registration form.
class UserReg(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput())


def internal_register(request):
    input_data = UserReg(request.POST)

    if not input_data.is_valid():
        msg = "Wrong field(s): %s." % \
            ", ".join(input_data.errors.keys())
        raise InvalidInputData(msg)

    username = input_data.cleaned_data["username"]
    password = input_data.cleaned_data["password"]

    if User.objects.filter(username=username).exists():
        raise UsernameUnavailable()

    # Registration goes through.
    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)

    # Raise:
    #
    #  SameAccountException
    #  DebitLimitException
    #  CurrencyMismatch
    #
    #  Amount group:
    #    BadFormatAmount
    #    NumberTooBig
    #    NegativeNumber
    wire_transfer(
        Amount(settings.TALER_CURRENCY, 100, 0),
        bank_internal_account,
        user_account, "Joining bonus"
    )

    return user


##
# This method serves the request for programmatically
# registering a user.
#
# @param request Django-specific HTTP request object.
# @return Django-specific HTTP response object.
@require_POST
@csrf_exempt
def register_headless(request):

    try:
        user = internal_register(request)

    except UsernameUnavailable:
        return HttpResponse(status=409)  # Conflict

    except InvalidInputData:
        return HttpResponse(status=406)  # Not Acceptable

    return HttpResponse(status=200)


##
# This method serves the request for registering a user.
# If successful, it redirects the user to their profile page;
# otherwise it will show again the same form (currently, without
# displaying _any_ error/warning message.)
#
# @param request Django-specific HTTP request object.
# @return Django-specific HTTP response object.
def register(request):
    if request.method != "POST":
        return render(request, "register.html")

    # Process POST.

    try:
        user = internal_register(request)

    except UsernameUnavailable as e:
        return render(request, "register.html", {"not_available": True})

    except InvalidInputData as e:
        return render(
            request, "register.html", {
                "wrong": True,
                "hint": "Wrong field(s): %s." % ", ".join(form.errors.keys())
            }
        )

    except DebitLimitException as e:
        return render(
            request, "register.html", {
                "wrong": True,
                "hint": "Out of business, cannot admit new customers."
            }
        )

    request.session["profile_hint"] = False, True, "Registration successful!"
    django.contrib.auth.login(request, user)
    return redirect("profile")


##
# Logs the user out, redirecting it to the bank's homepage.
#
# @param request Django-specific HTTP request object.
# @return Django-specific HTTP response object.
def logout_view(request):
    django.contrib.auth.logout(request)
    return redirect("index")


##
# Build the history array.
#
# @param account the bank account object whose history is being
#        extracted.
# @param descending currently not used.
# @param delta how many history entries will be contained in the
#        array (will be passed as-is to the internal routine
#        @a query_history).
# @param start any history will be searched starting from this
#        value (which is a row ID), and going to the past or to
#        the future (depending on the user choice).  However, this
#        value itself will not be included in the history.
# @param sign this value ("+"/"-") determines whether the history
#        entries will be younger / older than @a start.
# @return the history array.
def extract_history(account, delta, start=UINT64_MAX):
    history = []
    qs = query_history(account, "both", delta, start, "descending")
    for item in qs:
        if item.credit_account == account:
            counterpart = item.debit_account
            sign = ""
        else:
            counterpart = item.credit_account
            sign = "-"
        entry = dict(
            row_id=item.id,
            cancelled=item.cancelled,
            sign=sign,
            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")
        )
        history.append(entry)
    return history


##
# Serve the page showing histories from publicly visible accounts.
#
# @param request Django-specific HTTP request object.
# @param name name of the public account to show.
# @param page given that public histories are paginated, this
#        value is the page number to display in the response.
# @return Django-specific HTTP response object.
def serve_public_accounts(request, name=None, page=None):
    try:
        page = abs(int(page))
        if page == 0:
            raise Exception
    except Exception:
        page = 1

    if not name:
        name = settings.TALER_PREDEFINED_ACCOUNTS[0]
    user = User.objects.get(username=name)
    if not user.bankaccount.is_public:
        raise PrivateAccountException(
            "Can't display public history for private account"
        )

    # How many records does a user have.
    num_records = query_history(
        user.bankaccount,
        "both",
        # Note: the parameter below is used for slicing arrays
        # and django/python is not allowing slicing with big numbers.
        UINT64_MAX / 2 / 2,
        0,
        "descending"
    ).count()
    DELTA = 30
    # '//' operator is NO floating point.
    num_pages = max(num_records // DELTA, 1)

    public_accounts = BankAccount.objects.filter(is_public=True)

    # Retrieve DELTA records younger than 'start_row' (included).
    history = extract_history(user.bankaccount, DELTA * page,
                              0)[DELTA * (page - 1):(DELTA * page)]

    pages = list(range(1, num_pages + 1))

    context = dict(
        current_page=page,
        back=page - 1 if page > 1 else None,
        forth=page + 1 if page < num_pages else None,
        public_accounts=public_accounts,
        selected_account=dict(
            name=name,
            number=user.bankaccount.account_no,
            history=history,
        ),
        pages=pages
    )
    return render(request, "public_accounts.html", context)


##
# Decorator function that authenticates requests by fetching
# the credentials over the HTTP requests headers.
#
# @param view_func function that will be called after the
#        authentication, and that will usually serve the requested
#        endpoint.
# @return FIXME.
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")
            raise LoginFailed("authentication failed")
        return view_func(request, user_account, *args, **kwargs)

    return wraps(view_func)(_decorator)


##
# Build the DB query switch based on the "direction" history
# argument given by the user.
#
# @param bank_account bank account of the user requesting history.
# @param direction the "direction" URL parameter given by the user.
#        Note: this values got sanity-checked before this function
#        is called.
def direction_switch(bank_account, direction):
    direction_switch = {
        "both":
        (Q(debit_account=bank_account) | Q(credit_account=bank_account)),
        "credit": Q(credit_account=bank_account),
        "debit": Q(debit_account=bank_account),
        "cancel+": (Q(credit_account=bank_account) & Q(cancelled=True)),
        "cancel-": (Q(debit_account=bank_account) & Q(cancelled=True)),
    }
    return direction_switch.get(direction)


##
# Main routine querying for histories, based on _date ranges_.
#
# @param bank_account the bank account object whose
#        history is being extracted.
# @param direction takes the following three values,
#        * debit: only entries where the querying user has _paid_
#                 will be returned.
#        * credit: only entries where the querying user _got_
#                  paid will be returned.
#        * both: both of the cases above will be returned.
#        * cancel+: only entries where the querying user cancelled
#                   the _receiving_ of money will be returned.
#        * cancel-: only entries where the querying user cancelled
#                   the _paying_ of money will be returned.
# @param start timestamp of the oldest element allowed in the
#        result.
# @param end timestamp of the youngest element allowed in the
#        result.
# @param descending if True, then the results will have the
#        youngest entry in the first position.
def query_history_range(bank_account, direction, start, end, descending):
    qs = BankTransaction.objects.filter(
        direction_switch(bank_account, direction), Q(date__gte=start),
        Q(date__lte=end)
    )

    order = "-id" if descending else "id"
    return qs.order_by(order)


##
# Main routine querying for histories.
#
# @param bank_account the bank account object whose
#        history is being extracted.
# @param direction takes the following three values,
#        * debit: only entries where the querying user has _paid_
#                 will be returned.
#        * credit: only entries where the querying user _got_
#                  paid will be returned.
#        * both: both of the cases above will be returned.
#        * cancel+: only entries where the querying user cancelled
#                   the _receiving_ of money will be returned.
#        * cancel-: only entries where the querying user cancelled
#                   the _paying_ of money will be returned.
# @param delta how many history entries will be contained in the
#        array.
# @param start any history will be searched starting from this
#        value (which is a row ID), and going to the past or to
#        the future (depending on the user choice).  However, this
#        value itself will not be included in the history.
# @param sign this value ("+"/"-") determines whether the history
#        entries will be younger / older than @a start.
# @param ordering "descending" or anything else (for "ascending").
def query_history(bank_account, direction, delta, start, ordering):
    def sign_filter(delta):
        if 0 > delta:
            return Q(id__lt=start)
        return Q(id__gt=start)

    qs = BankTransaction.objects.filter(
        direction_switch(bank_account, direction), sign_filter(delta)
    )

    order = "-id" if "descending" == ordering else "id"
    return qs.order_by(order)[:abs(delta)]


##
# Build response object for /history.
#
# @param qs the query set for a history request.
# @param cancelled controls whether we omit/show
#        cancelled transactions.
# @param user_account bank account of the user who
#        asked for the history.
# @return the history object as specified in the
#         API reference documentation.
def build_history_response(qs, cancelled, user_account):
    history = []
    for entry in qs:
        counterpart = entry.credit_account.account_no
        sign_ = "-"
        if entry.cancelled and cancelled == "omit":
            continue
        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 history


##
# Serve a request of /history-range.
#
# @param request Django-specific HTTP request.
# @param user_account the account whose history should be gotten.
# @return Django-specific HTTP response object.
@require_GET
@login_via_headers
def serve_history_range(request, user_account):

    get_params = HistoryRangeParams(request.GET.dict())
    if not get_params.is_valid():
        raise URLParamValidationError(get_params.errors, 400)

    start_td = datetime.fromtimestamp(get_params.cleaned_data.get("start"))
    end_td = datetime.fromtimestamp(get_params.cleaned_data.get("end"))

    qs = query_history_range(
        user_account.bankaccount, request.GET.get("direction"), start_td,
        end_td, get_params.cleaned_data.get("ordering")
    )

    history = build_history_response(
        qs, get_params.cleaned_data.get("cancelled"), user_account
    )

    if not history:
        return HttpResponse(status=204)
    return JsonResponse(dict(data=history), status=200)


##
# Serve a request of /history.
#
# @param request Django-specific HTTP request.
# @param user_account the account whose history should be gotten.
# @return Django-specific HTTP response object.
@require_GET
@login_via_headers
def serve_history(request, user_account):
    get_params = HistoryParams(request.GET.dict())
    if not get_params.is_valid():
        raise URLParamValidationError(get_params.errors, 400)

    qs = query_history(
        user_account.bankaccount, get_params.cleaned_data.get("direction"),
        get_params.cleaned_data.get("delta"),
        get_params.cleaned_data.get("start"),
        get_params.cleaned_data.get("ordering")
    )

    history = build_history_response(
        qs, get_params.cleaned_data.get("cancelled"), user_account
    )

    if not history:
        return HttpResponse(status=204)
    return JsonResponse(dict(data=history), status=200)


##
# Helper function that authenticates a user by fetching the
# credentials from the HTTP headers.  Typically called from
# decorators.
#
# @param request Django-specific HTTP request object.
# @return Django-specific "authentication object".
def auth_and_login(request):
    """Return user instance after checking authentication
       credentials, False if errors occur"""

    username = request.META.get("HTTP_X_TALER_BANK_USERNAME")
    password = request.META.get("HTTP_X_TALER_BANK_PASSWORD")
    if not username or not password:
        LOGGER.error("user or password not given")
        raise LoginFailed("missing user/password")
    return django.contrib.auth.authenticate(
        username=username, password=password
    )


##
# Serve a request of /reject (for rejecting wire transfers).
#
# @param request Django-specific HTTP request object.
# @param user_account the account that is going to reject the
#        transfer.  Used to check whether they have this right
#        or not (only accounts which _got_ payed can cancel the
#        transaction.)
@transaction.atomic
@csrf_exempt
@require_http_methods(["PUT", "POST"])
@login_via_headers
def reject(request, user_account):

    data = RejectData(json.loads(decode_body(request)))
    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()
    trans.cancelled = True
    if trans.debit_account.debit:
        # balance is negative
        if 1 > Amount.cmp(trans.debit_account.amount, trans.amount):
            # debit_account.amount <= trans.amount
            trans.debit_account.debit = False
            tmp = Amount(**trans.amount.dump())
            tmp.subtract (trans.debit_account.amount)
            trans.debit_account.amount.set (**tmp.dump())
        else:
            # debit_account > trans.amount
            trans.debit_account.amount.subtract (trans.amount)
    else:
        # balance is positive, simply add
        trans.debit_account.amount.add(trans.amount)
    if trans.credit_account.debit:
        # credit account balance is already negative
        trans.credit_account.amount.add(trans.amount)
    else:
        if -1 == Amount.cmp(trans.credit_account.amount, trans.amount):
            # credit_account.amount < trans.amount
            trans.credit_account.debit = True
            tmp = Amount(**trans.amount.dump())
            tmp.subtract (trans.credit_account.amount)
            trans.credit_account.amount.set (**tmp.dump())
        else:
            # credit_account.amount >= trans.amount
            trans.credit_account.amount.subtract(trans.amount)

    trans.save()
    return HttpResponse(status=204)


##
# Serve a request to make a wire transfer.  Allows fintech
# providers to issues payments in a programmatic way.
#
# @param request Django-specific HTTP request object.
# @param user_account the (authenticated) user issuing this
#        request.
# @return Django-specific HTTP response object.
@csrf_exempt
@require_POST
@login_via_headers
def add_incoming(request, user_account):

    data = AddIncomingData(json.loads(decode_body(request)))

    subject = "%s %s" % (
        data.get("subject"), data.get("exchange_url")
    )

    credit_account = BankAccount.objects.get(
        account_no=data.get("credit_account")
    )

    wtrans = wire_transfer(
        Amount.parse(data.get("amount")), user_account.bankaccount,
        credit_account, subject
    )

    return JsonResponse({
        "row_id": wtrans.id,
        "timestamp": "/Date(%s)/" % int(wtrans.date.timestamp())
    })



@login_via_headers
@csrf_exempt
@require_POST
def withdraw_headless_uri(request, user):
    data = WithdrawHeadlessUri(json.loads(decode_body(request)))
    if not data.is_valid():
        raise JSONFieldException(data.errors, 400)
    amount = Amount.parse(data.cleaned_data["amount"])
    user_account = BankAccount.objects.get(user=user)
    op = TalerWithdrawOperation(amount=amount, withdraw_account=user_account)
    op.save()
    host = request.get_host()
    taler_withdraw_uri = f"taler://withdraw/{host}/-/{op.withdraw_id}"
    return JsonResponse({
        "taler_withdraw_uri": taler_withdraw_uri,
    })

##
# Serves a headless withdrawal request for the Taler protocol.
#
# @param request Django-specific HTTP request.
# @return Django-specific HTTP response object.
@login_via_headers
@csrf_exempt
@require_POST
def withdraw_headless(request, user):
    
    data = WithdrawHeadless(json.loads(decode_body(request)))
    sender_payto = "payto://x-taler-bank/%s/%d" % \
        (request.get_host(), user.bankaccount.account_no)
    ret_obj = ({"sender_wire_details": sender_payto})

    if not data.is_valid():
        raise JSONFieldException(data.errors, 400)

    # Pick default exchange.
    if None == data.cleaned_data["exchange_wire_details"]:
        exchange_accno = get_acct_from_payto(
            settings.TALER_SUGGESTED_EXCHANGE_PAYTO
        )
        ret_obj.update(exchange_url=settings.TALER_SUGGESTED_EXCHANGE)
    else:
        exchange_accno = get_acct_from_payto(
            data.cleaned_data["exchange_wire_details"]
        )

    exchange_bankaccount = BankAccount.objects.get(account_no=exchange_accno)

    wire_transfer(
        Amount.parse(data.cleaned_data["amount"]), user.bankaccount,
        exchange_bankaccount, data.cleaned_data["reserve_pub"]
    )

    return JsonResponse(ret_obj)


# Endpoint used by the browser and wallet to check withdraw status and
# put in the exchange info.
@csrf_exempt
def api_withdraw_operation(request, withdraw_id):
    try:
        op = TalerWithdrawOperation.objects.get(withdraw_id=withdraw_id)
    except ObjectDoesNotExist:
        return JsonResponse(
            dict(error="withdraw operation does not exist"), status=404
        )
    user_acct_no = op.withdraw_account.account_no
    host = request.get_host()

    if request.method == "POST":
        data = json.loads(decode_body(request))
        exchange_payto_uri = data.get("selected_exchange")
        try:
            account_no = get_acct_from_payto(exchange_payto_uri)
        except:
            return JsonResponse(
                dict(error="exchange payto URI malformed"), status=400
            )
        try:
            exchange_acct = BankAccount.objects.get(account_no=account_no)
        except ObjectDoesNotExist:
            return JsonResponse(
                dict(error="bank accound in payto URI unknown"), status=400
            )
        selected_reserve_pub = data.get("reserve_pub")
        if not isinstance(selected_reserve_pub, str):
            return JsonResponse(
                dict(error="reserve_pub must be a string"), status=400
            )
        if op.selection_done or op.withdraw_done:
            if (
                op.selected_exchange_account != exchange_acct
                or op.selected_reserve_pub != selected_reserve_pub
            ):
                return JsonResponse(
                    dict(error="selection of withdraw parameters already done"),
                    status=409
                )
            # No conflict, same data!
            return JsonResponse(dict(), status=200)
        op.selected_exchange_account = exchange_acct
        op.selected_reserve_pub = selected_reserve_pub
        op.selection_done = True
        op.save()
        return JsonResponse(dict(), status=200)
    elif request.method == "GET":
        return JsonResponse(
            dict(
                selection_done=op.selection_done,
                transfer_done=op.withdraw_done,
                amount=op.amount.stringify(),
                wire_types=["x-taler-bank"],
                sender_wire=f"payto://x-taler-bank/{host}/{user_acct_no}",
                suggested_exchange=settings.TALER_SUGGESTED_EXCHANGE,
                confirm_transfer_url=request.build_absolute_uri(
                    reverse("withdraw-confirm", args=(withdraw_id, ))
                )
            )
        )
    else:
        return JsonResponse(
            dict(error="only GET and POST are allowed"), status=305
        )


##
# Serve a Taler withdrawal request; takes the amount chosen
# by the user, and builds a response to trigger the wallet into
# the withdrawal protocol
#
# @param request Django-specific HTTP request.
# @return Django-specific HTTP response object.
@login_required
@require_POST
def start_withdrawal(request):
    user_account = BankAccount.objects.get(user=request.user)
    amount = Amount.parse(request.POST.get("kudos_amount", "not-given"))
    op = TalerWithdrawOperation(amount=amount, withdraw_account=user_account)
    op.save()
    return redirect("withdraw-show", withdraw_id=op.withdraw_id)


def get_qrcode_svg(data):
    factory = qrcode.image.svg.SvgImage
    img = qrcode.make(data, image_factory=factory)
    return lxml.etree.tostring(img.get_image()).decode("utf-8")


@login_required
@require_GET
def show_withdrawal(request, withdraw_id):
    op = TalerWithdrawOperation.objects.get(withdraw_id=withdraw_id)
    if op.selection_done:
        return redirect("withdraw-confirm", withdraw_id=op.withdraw_id)
    host = request.get_host()
    taler_withdraw_uri = f"taler://withdraw/{host}/-/{op.withdraw_id}"
    qrcode_svg = get_qrcode_svg(taler_withdraw_uri)
    context = dict(
        taler_withdraw_uri=taler_withdraw_uri,
        qrcode_svg=qrcode_svg,
        withdraw_check_url=reverse(
            "api-withdraw-operation", kwargs=dict(withdraw_id=op.withdraw_id)
        ),
    )
    resp = render(request, "withdraw_show.html", context, status=402)
    resp["Taler"] = taler_withdraw_uri
    return resp


@login_required
@require_http_methods(["GET", "POST"])
def confirm_withdrawal(request, withdraw_id):
    op = TalerWithdrawOperation.objects.get(withdraw_id=withdraw_id)
    if not op.selection_done:
        raise Exception(
            "invalid state (withdrawal parameter selection not done)"
        )
    if op.withdraw_done:
        return redirect("profile")
    if request.method == "POST":
        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, False, "Wrong CAPTCHA answer."
            return redirect("withdraw-confirm", withdraw_id=withdraw_id)
        op.withdraw_done = True
        op.save()
        wire_transfer(
            op.amount, BankAccount.objects.get(user=request.user),
            op.selected_exchange_account, op.selected_reserve_pub
        )
        request.session["profile_hint"] = False, True, "Withdrawal successful!"
        request.session["just_withdrawn"] = True
        return redirect("profile")
    if request.method == "GET":
        question, hashed_answer = make_question()
        context = dict(
            question=question,
            hashed_answer=hashed_answer,
            withdraw_id=withdraw_id,
            amount=op.amount.stringify(settings.TALER_DIGITS),
            exchange=op.selected_exchange_account.user
        )
        return render(request, "withdraw_confirm.html", context)
    raise Exception("not reached")


##
# Make a wire transfer between two accounts (internal to the bank)
#
# @param amount (object type) how much money the wire transfer is worth.
#        FIXME: a check about whether this value is zero is missing
# @param debit_account the account that gives money.
# @param credit_account the account that receives money.
# @return a @a BankTransaction object.
def wire_transfer(amount, debit_account, credit_account, subject):
    LOGGER.debug(
        "%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
    )

    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 DebitLimitException()

    with transaction.atomic():
        debit_account.save()
        credit_account.save()
        transaction_item.save()

    return transaction_item