summaryrefslogtreecommitdiff
path: root/talerblog/blog/blog.py
blob: 02d10d0389f9c9001eff2d711824d4194ac427d6 (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
# 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.
"""

from urllib.parse import urljoin, quote
import logging
import os
import traceback
import uuid
import base64
import requests
import flask
from werkzeug.contrib.cache import UWSGICache, SimpleCache
from talerblog.talerconfig import TalerConfig
from ..blog.content import ARTICLES, get_article_file, get_image_file


BASE_DIR = os.path.dirname(os.path.abspath(__file__))
app = flask.Flask(__name__, template_folder=BASE_DIR)
app.secret_key = base64.b64encode(os.urandom(64)).decode('utf-8')

LOGGER = logging.getLogger(__name__)
TC = TalerConfig.from_env()
BACKEND_URL = TC["frontends"]["backend"].value_string(required=True)
CURRENCY = TC["taler"]["currency"].value_string(required=True)
APIKEY = TC["frontends"]["backend_apikey"].value_string(required=True)
INSTANCE = TC["blog"]["instance"].value_string(required=True)
ARTICLE_AMOUNT = CURRENCY + ":0.5"

app.config.from_object(__name__)


@app.context_processor
def utility_processor():
    # These helpers will be available in templates
    def env(name, default=None):
        return os.environ.get(name, default)
    return dict(env=env)


def err_abort(abort_status_code, **params):
    t = flask.render_template("templates/error.html", **params)
    flask.abort(flask.make_response(t, abort_status_code))


def backend_get(endpoint, params):
    headers = {"Authorization": "ApiKey " + APIKEY}
    try:
        resp = requests.get(urljoin(BACKEND_URL, endpoint), params=params, headers=headers)
    except requests.ConnectionError:
        err_abort(500, message="Could not establish connection to backend")
    try:
        response_json = resp.json()
    except ValueError:
        err_abort(500, message="Could not parse response from backend")
    if resp.status_code != 200:
        err_abort(500, message="Backend returned error status",
                  json=response_json, status_code=resp.status_code)
    return response_json


def backend_post(endpoint, json):
    headers = {"Authorization": "ApiKey " + APIKEY}
    try:
        resp = requests.post(urljoin(BACKEND_URL, endpoint), json=json, headers=headers)
    except requests.ConnectionError:
        err_abort(500, message="Could not establish connection to backend")
    try:
        response_json = resp.json()
    except ValueError:
        err_abort(500, message="Could not parse response from backend",
                  status_code=resp.status_code)
    if resp.status_code != 200:
        err_abort(500, message="Backend returned error status",
                  json=response_json, status_code=resp.status_code)
    return response_json


@app.errorhandler(Exception)
def internal_error(e):
    return flask.render_template("templates/error.html",
                                 message="Internal error",
                                 stack=traceback.format_exc())


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


# Cache for paid articles (in the form <session_id>-<article_name>), so we
# don't always have to ask the backend / DB, and so we don't have to store
# variable-size cookies on the client.
try:
    import uwsgi
    paid_articles_cache = UWSGICache(0, "paid_articles")
except ImportError:
    paid_articles_cache = SimpleCache()


# Triggers the refund by serving /refund/test?order_id=XY.
# Will be triggered by a "refund button".
@app.route("/refund/<order_id>", methods=["POST"])
def refund(order_id):
    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)
    if not order_id:
        return flask.jsonify(dict(error="Aborting refund: article not payed")), 401
    refund_spec = dict(
        instance=INSTANCE,
        order_id=order_id,
        reason="Demo reimbursement",
        refund=ARTICLE_AMOUNT,
    )
    resp = backend_post("refund", refund_spec)
    try:
        # delete from paid article cache
        article_name = resp["contract_terms"]["extra"]["article_name"]
        session_id = flask.session.get("session_id", "")
        paid_articles_cache.delete(session_id + "-" + article_name)
        return flask.redirect(resp["refund_redirect_url"])
    except KeyError:
        err_abort(500, message="Response from backend incomplete",
                json=resp, stack=traceback.format_exc())


def render_article(article_name, data, order_id):
    article_info = ARTICLES.get(article_name)
    if article_info is None:
        m = "Internal error: Files for article ({}) not found.".format(article_name)
        err_abort(500, message=m)
    if data is not None:
        if data in article_info.extra_files:
            return flask.send_file(get_image_file(data))
        m = "Supplemental file ({}) for article ({}) not found.".format(
                data, article_name)
        err_abort(404, message=m)
    # the order_id is needed for refunds
    return flask.render_template("templates/article_frame.html",
                                 article_file=get_article_file(article_info),
                                 article_name=article_name,
                                 order_id=order_id)


@app.route("/essay/<article_name>")
@app.route("/essay/<article_name>/data/<data>")
def article(article_name, data=None):

    # We use an explicit session ID so that each payment (or payment replay) is
    # bound to a browser.  This forces re-play and prevents sharing the article
    # by just sharing the URL.
    session_id = flask.session.get("session_id")
    order_id = flask.request.args.get("order_id")
    session_sig = flask.request.args.get("session_sig")

    if not session_id:
        session_id = flask.session["session_id"] = str(uuid.uuid4())

    cached_order_id = paid_articles_cache.get(session_id + "-" + article_name)
    if cached_order_id:
        return render_article(article_name, data, cached_order_id)

    if order_id and not session_sig:
        # If there was an order_id but no session_sig, either the user played
        # around with the URL or the wallet is old/broken.
        err_abort(400, message=("Bad request (session_sig missing). "
                                "Your wallet might be broken or outdated"))

    if not order_id:
        order = dict(
            amount=ARTICLE_AMOUNT,
            extra=dict(article_name=article_name),
            fulfillment_url=flask.request.base_url,
            instance=INSTANCE,
            summary="Essay: " + article_name.replace("_", " "),
        )
        order_resp = backend_post("order", dict(order=order))
        order_id = order_resp["order_id"]

    pay_params = dict(
        instance=INSTANCE,
        order_id=order_id,
        resource_url=flask.request.base_url,
        session_id=session_id,
        session_sig=session_sig,
    )

    pay_status = backend_get("check-payment", pay_params)

    if pay_status.get("paid"):
        if pay_status["contract_terms"]["extra"]["article_name"] != article_name:
            err_abort(402, message="You did not pay for this article (nice try!)", json=pay_status)
        if pay_status.get("refunded"):
            return flask.render_template("templates/article_refunded.html",
                                         article_name=article_name)
        paid_articles_cache.set(session_id + "-" + article_name, order_id)
        return render_article(article_name, data, order_id)
    else:
        if pay_status.get("payment_redirect_url"):
            return flask.redirect(pay_status["payment_redirect_url"])

    # no pay_redirect but article not paid, this should never happen!
    err_abort(500, message="Internal error, invariant failed", json=pay_status)