summaryrefslogtreecommitdiff
path: root/talerblog/blog/blog.py
blob: 02c6c2dda73d0afbaaf7a1d1fd3bc53cac3ff673 (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
# This file is part of GNU TALER.
# Copyright (C) 2014-2017 INRIA
#
# TALER is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free Software
# Foundation; either version 2.1, 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License along with
# GNU TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
#
# @author Florian Dold
# @author Marcello Stanisci


"""
Implement URL handlers and payment logic for the blog merchant.
"""

import flask
from urllib.parse import urljoin, urlencode, quote, parse_qsl
import requests
import logging
import os
import base64
import random
import time
import json
import datetime
from pprint import pprint
from talerfrontends.talerconfig import TalerConfig
from talerfrontends.helpers import (make_url,
        expect_parameter, join_urlparts, get_query_string,
        backend_error)
from talerfrontends.blog.content import (articles,
get_article_file, get_image_file)

logger = logging.getLogger(__name__)

base_dir = os.path.dirname(os.path.abspath(__file__))

app = flask.Flask(__name__, template_folder=base_dir)
app.debug = True
app.secret_key = base64.b64encode(os.urandom(64)).decode('utf-8')

tc = TalerConfig.from_env()

BACKEND_URL = tc["frontends"]["backend"].value_string(required=True)
CURRENCY = tc["taler"]["currency"].value_string(required=True)
INSTANCE = tc["blog"]["instance"].value_string(required=True)
ARTICLE_AMOUNT = dict(value=1, fraction=0, currency=CURRENCY)

app.config.from_object(__name__)


@app.context_processor
def utility_processor():
    def url(my_url):
        return join_urlparts(flask.request.script_root, my_url)
    def env(name, default=None):
        return os.environ.get(name, default)
    return dict(url=url, env=env)


@app.route("/")
def index():
    return flask.render_template("templates/index.html",
                                 merchant_currency=CURRENCY,
                                 articles=articles.values())


@app.route("/javascript")
def javascript_licensing():
    return flask.render_template("templates/javascript.html")

# Triggers the refund by serving /refund/test?order_id=XY.
# Will be triggered by a "refund button".
@app.route("/refund", methods=["GET", "POST"])
def refund():
    if flask.request.method == "POST":
        payed_articles = flask.session["payed_articles"] = flask.session.get("payed_articles", {})
        article_name = flask.request.form.get("article_name")
        if not article_name:
            return flask.jsonify(dict(error="No article_name found in form")), 400
        logger.info("Looking for %s to refund" % article_name)
        order_id = payed_articles.get(article_name)
        if not order_id:
            return flask.jsonify(dict(error="Aborting refund: article not payed")), 401
        r = requests.post(urljoin(BACKEND_URL, "refund"),
                          json=dict(order_id=order_id,
                                    refund=dict(value=1, fraction=0, currency=CURRENCY),
                                    reason="Demo reimbursement",
                                    instance=INSTANCE))
        if 200 != r.status_code:
            return backend_error(r)
        payed_articles[article_name] = "__refunded"
        response = flask.make_response()
        response.headers["X-Taler-Refund-Url"] = make_url("/refund", ("order_id", order_id))
        return response, 402

    else:
        order_id = expect_parameter("order_id", False)
        if not order_id:
            logger.error("Missing parameter 'order_id'")
            return flask.jsonify(dict(error="Missing parameter 'order_id'")), 400
        r = requests.get(urljoin(BACKEND_URL, "refund"), params=dict(order_id=order_id,
                                                                     instance=INSTANCE))
        if 200 != r.status_code:
            return backend_error(r)
        return flask.jsonify(r.json()), r.status_code


@app.route("/generate-contract", methods=["GET"])
def generate_contract():
    article_name = expect_parameter("article_name")
    pretty_name = article_name.replace("_", " ")
    order = dict(
        summary=pretty_name,
        nonce=flask.request.args.get("nonce"),
        amount=ARTICLE_AMOUNT,
        max_fee=dict(value=1, fraction=0, currency=CURRENCY),
        products=[
            dict(
                description="Essay: " + pretty_name,
                quantity=1,
                product_id=0,
                price=ARTICLE_AMOUNT,
            ),
        ],
        fulfillment_url=make_url("/essay/" + quote(article_name)),
        pay_url=make_url("/pay"),
        merchant=dict(
            instance=INSTANCE,
            address="nowhere",
            name="Kudos Inc.",
            jurisdiction="none",
        ),
        extra=dict(article_name=article_name),
    )
    r = requests.post(urljoin(BACKEND_URL, "proposal"), json=dict(order=order))
    if r.status_code != 200:
        return backend_error(r)
    proposal_resp = r.json()
    return flask.jsonify(**proposal_resp)


@app.route("/cc-payment/<name>")
def cc_payment(name):
    return flask.render_template("templates/cc-payment.html",
                                 article_name=name)


@app.route("/essay/<name>")
@app.route("/essay/<name>/data/<data>")
def article(name, data=None):
    logger.info("processing %s" % name)
    payed_articles = flask.session.get("payed_articles", {})

    if payed_articles.get(name, "") == "__refunded":
        return flask.render_template("templates/article_refunded.html", article_name=name)

    if name in payed_articles:
        article = articles[name]
        if article is None:
            flask.abort(500)
        if data is not None:
            if data in article.extra_files:
                return flask.send_file(get_image_file(data))
            else:
                return "permission denied", 400
        return flask.render_template("templates/article_frame.html",
                                     article_file=get_article_file(article),
                                     article_name=name)

    contract_url = make_url("/generate-contract", ("article_name",name))
    response = flask.make_response(flask.render_template("templates/fallback.html"), 402)
    response.headers["X-Taler-Contract-Url"] = contract_url
    response.headers["X-Taler-Contract-Query"] = "fulfillment_url"
    # Useless (?) header, as X-Taler-Contract-Url takes always (?) precedence
    # over X-Offer-Url.  This one might only be useful if the contract retrieval
    # goes wrong.
    response.headers["X-Taler-Offer-Url"] = make_url("/essay/" + quote(name))
    return response


@app.route("/pay", methods=["POST"])
def pay():
    deposit_permission = flask.request.get_json()
    if deposit_permission is None:
        e = flask.jsonify(error="no json in body"),
        return e, 400
    r = requests.post(urljoin(BACKEND_URL, "pay"), json=deposit_permission)
    if 200 != r.status_code:
        return backend_error(r)
    proposal_data = r.json()["contract_terms"]
    article_name = proposal_data["extra"]["article_name"]
    payed_articles = flask.session["payed_articles"] = flask.session.get("payed_articles", {})
    if len(r.json()["refund_permissions"]) != 0:
        # we had some refunds on the article purchase already!
        logger.info("Article %s was refunded, before /pay" % article_name)
        payed_articles[article_name] = "__refunded"
        return flask.jsonify(r.json()), 200
    if not deposit_permission["order_id"]:
        logger.error("order_id missing from deposit_permission!")
        return flask.jsonify(dict(error="internal error: ask for refund!")), 500
    if article_name not in payed_articles:
        logger.info("Article %s goes in state" % article_name)
        payed_articles[article_name] = deposit_permission["order_id"]
    return flask.jsonify(r.json()), 200


@app.route("/history")
def history():
    qs = get_query_string().decode("utf-8")
    url = urljoin(BACKEND_URL, "history")
    r = requests.get(url, params=dict(parse_qsl(qs)))
    if 200 != r.status_code:
        return backend_error(r)
    return flask.jsonify(r.json()), r.status_code


@app.route("/backoffice")
def track():
    response = flask.make_response(flask.render_template("templates/backoffice.html"))
    return response


@app.route("/track/transfer")
def track_transfer():
    qs = get_query_string().decode("utf-8")
    url = urljoin(BACKEND_URL, "track/transfer")
    r = requests.get(url, params=dict(parse_qsl(qs)))
    if 200 != r.status_code:
        return backend_error(r)
    return flask.jsonify(r.json()), r.status_code


@app.route("/track/order")
def track_order():
    qs = get_query_string().decode("utf-8")
    url = urljoin(BACKEND_URL, "track/transaction")
    r = requests.get(url, params=dict(parse_qsl(qs)))
    if 200 != r.status_code:
        return backend_error(r)
    return flask.jsonify(r.json()), r.status_code