summaryrefslogtreecommitdiff
path: root/talerbank/app/views.py
blob: 00d3cc4b3d814ad0f0b226e5179dbc3cc396572d (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
#  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 functools import wraps
import json
import logging
import hashlib
import random
import re
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 .models import BankAccount, BankTransaction
from .amount import Amount
from .schemas import validate_data
LOGGER = logging.getLogger(__name__)

class LoginFailed(Exception):
    hint = "Wrong username/password"
    http_status_code = 401

class DebitLimitException(Exception):
    hint = "Debit too high, operation forbidden."
    http_status_code = 403

class SameAccountException(Exception):
    hint = "Debit and credit account are the same."
    http_status_code = 403

class RejectNoRightsException(Exception):
    hint = "You weren't the transaction credit account, " \
           "no rights to reject."
    http_status_code = 403

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):
    fail_message, success_message, hint = get_session_hint(request, "login_hint")
    response = django.contrib.auth.views.login(
        request,
        authentication_form=MyAuthenticationForm,
        template_name="login.html",
        extra_context={"user": request.user})
    if hasattr(response, "context_data"):
        response.context_data["fail_message"] = fail_message
        response.context_data["success_message"] = success_message
        response.context_data["hint"] = hint
    return response

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

def get_session_hint(request, name):
    """
    Get a hint from the session and clear it.
    """
    if name in request.session:
        ret = request.session[name]
        del request.session[name]
        return ret
    # Fail message, success message, hint.
    return False, False, None


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]
class InputDatalist(forms.TextInput):

    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]+"})

    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


class WTForm(forms.Form):
    '''Form used to wire transfer money internally in the bank.'''
    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()

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

@login_required
def profile_page(request):
    if request.method == "POST":
        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.stringify(
            settings.TALER_DIGITS, pretty=True),
        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),
    )
    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


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


@require_GET
@login_required
def pin_tan_question(request):
    validate_data(request, request.GET.dict())
    user_account = BankAccount.objects.get(user=request.user)
    wire_details = json.loads(request.GET["exchange_wire_details"])
    request.session["exchange_account_number"] = \
        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["reserve_pub"] = request.GET["reserve_pub"]
    request.session["sender_wiredetails"] = {
        "type": "test",
        "bank_uri": request.build_absolute_uri(reverse("index")),
        "account_number": user_account.account_no}
    fail_message, success_message, hint = get_session_hint(request, "captcha_failed")
    question, hashed_answer = make_question()
    context = dict(
        question=question,
        hashed_answer=hashed_answer,
        amount=amount.stringify(settings.TALER_DIGITS),
        exchange=request.GET["exchange"],
        fail_message=fail_message,
        success_message=success_message,
        hint=hint)
    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, False, "Wrong CAPTCHA answer."
        return redirect(request.POST.get("question_url", "profile"))
    # Check the session is a "pin tan" one
    validate_data(request, 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.session["profile_hint"] = False, True, "Withdrawal successful!"
    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",
                      {"fail_message": True,
                       "success_message": False,
                       "hint": "Wrong field(s): %s." % ", ".join(form.errors.keys())})
    username = form.cleaned_data["username"]
    password = form.cleaned_data["password"]
    if User.objects.filter(username=username).exists():
        return render(request, "register.html",
                      {"fail_message": True,
                       "success_message": False,
                       "hint": "Username not available."})
    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)
    wire_transfer(Amount(settings.TALER_CURRENCY, 100, 0),
                  bank_internal_account,
                  user_account,
                  "Joining bonus")
    request.session["profile_hint"] = False, True, "Registration successful!"
    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["login_hint"] = False, True, "Logged out!"
    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(
            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


def serve_public_accounts(request, name=None):
    if not name:
        name = settings.TALER_PREDEFINED_ACCOUNTS[0]
    user = User.objects.get(username=name)
    if not user.bankaccount.is_public:
        request.session["public_accounts_hint"] = \
            True, False, "Could not query private accounts!"
    fail_message, success_message, hint = \
        get_session_hint(request, "public_accounts_hint")
    public_accounts = BankAccount.objects.filter(is_public=True)
    history = extract_history(user.bankaccount)
    context = dict(
        public_accounts=public_accounts,
        selected_account=dict(
            fail_message=fail_message,
            success_message=success_message,
            hint=hint,
            name=name,
            number=user.bankaccount.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")
            raise LoginFailed("authentication failed")
        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.
    """
    validate_data(request, request.GET.dict())
    # 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 = []
    cancelled = request.GET.get("cancelled", "show")
    qs = BankTransaction.objects.filter(
        query_string, sign_filter).order_by(
            "-id" if sign == "-" else "id") \
            [:int(parsed_delta.group(2))]
    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()))+")/"))
    if not history:
        return HttpResponse(status=204)
    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")
        raise LoginFailed("auth method not supported")

    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)

@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"))
    validate_data(request, data)
    trans = BankTransaction.objects.get(id=data["row_id"])
    if trans.credit_account.account_no != \
            user_account.bankaccount.account_no:
        raise RejectNoRightsException()
    trans.cancelled = True
    trans.debit_account.amount.add(trans.amount)
    trans.credit_account.amount.subtract(trans.amount)
    trans.save()
    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"))
    validate_data(request, data)
    subject = "%s %s" % (data["subject"], data["exchange_url"])
    credit_account = BankAccount.objects.get(
        account_no=data["credit_account"])
    wtrans = wire_transfer(Amount(**data["amount"]),
                           user_account.bankaccount,
                           credit_account,
                           subject)
    return JsonResponse(
        {"row_id": wtrans.id,
         "timestamp": "/Date(%s)/" % int(wtrans.date.timestamp())})


@login_required
@require_POST
def withdraw_nojs(request):

    amount = Amount.parse(
        request.POST.get("kudos_amount", "not-given"))
    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

def wire_transfer(amount, debit_account, credit_account,
                  subject):
    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)
    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

# [1] https://stackoverflow.com/questions/24783275/django-form-with-choices-but-also-with-freetext-option