# 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 # # @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 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) 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): try: resp = requests.get(urljoin(BACKEND_URL, endpoint), params=params) 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): try: resp = requests.post(urljoin(BACKEND_URL, endpoint), json=json) 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") # Triggers the refund by serving /refund/test?order_id=XY. # Will be triggered by a "refund button". @app.route("/refund/", 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( order_id=order_id, refund=ARTICLE_AMOUNT, reason="Demo reimbursement", instance=INSTANCE, ) resp = backend_post("refund", refund_spec) if resp.get("refund_redirect_url"): return flask.redirect(pay_status["refund_redirect_url"]) flask.abort(500) @app.route("/essay/") @app.route("/essay//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("uid") order_id = flask.request.args.get("order_id") session_sig = flask.request.args.get("session_sig") if not session_id: session_id = flask.session["uid"] = uuid.uuid4() 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( summary="Essay: " + article_name.replace("_", " "), fulfillment_url=flask.request.base_url, amount=ARTICLE_AMOUNT, instance=INSTANCE, ) proposal_resp = backend_post("proposal", dict(order=order)) order_id = proposal_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("payment_redirect_url"): return flask.redirect(pay_status["payment_redirect_url"]) if pay_status.get("refunded"): return flask.render_template("templates/article_refunded.html", article_name=article_name) if pay_status.get("paid"): article_info = ARTICLES.get(article_name) if article_info is None: flask.abort(500) if data is not None: if data in article_info.extra_files: return flask.send_file(get_image_file(data)) return "permission denied", 403 return flask.render_template("templates/article_frame.html", article_file=get_article_file(article_info), article_name=article_name, order_id=order_id) # no pay_redirect but article not paid, this should never happen! flask.abort(500)