Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nonces everywhere #34

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions donate/app.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
from flask import Flask, Response
import prometheus_client
from donate.extensions import db, migrate
Expand All @@ -7,8 +6,6 @@
Account,
Currency,
Project,
StripeDonation,
StripePlan,
Transaction,
User,
)
Expand All @@ -33,7 +30,8 @@ def create_app(config_object=ProdConfig):
# Handle metrics requests.
@app.route("/metrics")
def metrics():
return Response(prometheus_client.generate_latest(), mimetype=prometheus_client.CONTENT_TYPE_LATEST)
return Response(prometheus_client.generate_latest(),
mimetype=prometheus_client.CONTENT_TYPE_LATEST)

return(app)

Expand All @@ -51,6 +49,7 @@ def register_blueprints(app):
app.register_blueprint(routes.new_project_page)
app.register_blueprint(routes.thanks_page)
app.register_blueprint(routes.donation_charges)
app.register_blueprint(routes.nonce_page)


def register_shellcontext(app):
Expand Down
2 changes: 1 addition & 1 deletion donate/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,6 @@ class DonateConfiguration(db.Model, TimestampMixin):
__tablename__ = 'donate_configuration'

id = db.Column(db.Integer, primary_key=True)
key = db.Column(db.String(32), nullable=False, unique=True)
key = db.Column(db.String(64), nullable=False, unique=True)
type = db.Column(db.String(10), nullable=False)
value = db.Column(db.String(32), nullable=False)
90 changes: 66 additions & 24 deletions donate/routes.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
import os
import git
import json
import random
import string
from datetime import datetime
from flask import (
current_app as app,
flash,
make_response,
redirect,
render_template,
request,
url_for,
Blueprint,
)
from sqlalchemy.orm.exc import (
NoResultFound,
MultipleResultsFound,
)
from donate.util import get_one
from donate.database import db
from donate.models import (
Account,
Donation,
DonateConfiguration,
Project,
Currency,
Transaction,
Expand All @@ -28,14 +27,11 @@
)
from donate.vendor.stripe import (
create_charge,
get_customer
)

import stripe
from stripe import error as se

#FIXME: git_sha = git.Repo(search_parent_directories=True).head.object.hexsha
git_sha="whatever"
# FIXME: git_sha = git.Repo(search_parent_directories=True).head.object.hexsha
git_sha = "whatever"
repo_path = "https://github.com/noisebridge/python-nb-donate/tree/"

donation_page = Blueprint('donation', __name__, template_folder="templates")
Expand All @@ -49,6 +45,49 @@
__name__, template_folder="templates")
donation_charges = Blueprint('new_charge',
__name__, template_folder="templates")
nonce_page = Blueprint('denonce', __name__, template_folder="templates")


def create_nonce():
nonce = ''.join(random.choice(string.ascii_letters + string.digits)
for n in range(256))
db.session.add(DonateConfiguration(key=nonce, type="nonce", value="true"))
db.session.commit()
return nonce


def consume_nonce(nonce):

nonces = db.session.query(DonateConfiguration).filter_by(
key=nonce,
type="nonce",
value="true").all()

if len(nonces) == 0:
return None

if len(nonces) == 1:
nonce = nonces[0]
if (datetime.now() - nonce.created_at).total_seconds() <= 60:
key = app.get_stripe_key('PUBLIC')
for nonce in nonces:
db.session.delete(nonce)
db.session.commit()
return key

if len(nonces) > 1:
for nonce in nonces:
db.session.delete(nonce)
db.session.commit()
return None


@nonce_page.route('/nonce/<nonce>', methods=['GET'])
def denonce(nonce):
data = {'value': consume_nonce(nonce)}
resp = make_response(render_template('nonce.html', data=data))
resp.headers['Content-type'] = 'application/json'
return resp


def get_donation_params(form):
Expand Down Expand Up @@ -158,7 +197,7 @@ def donation():
app.logger.error("CardError: {}".format(error))
flash(msg)
return redirect('/index#form')
except se.RateLimitError as error:
except se.RateLimitError:
app.logger.warning("RateLimitError hit!")
flash("Rate limit hit, please try again in a few seconds")
return redirect('/index#form')
Expand Down Expand Up @@ -189,14 +228,14 @@ def donation():
except NoResultFound:
app.logger.debug("Creating plan {}".format(plan_name))
stripe_plan = StripePlan(name=plan_name,
amount=amt,
interval="M",
desc="{}/{}".format(amt, "M"))
stripe_plan.subscriptions=[stripe_sub]
amount=amt,
interval="M",
desc="{}/{}".format(amt, "M"))
stripe_plan.subscriptions = [stripe_sub]
try:
stripe_plan
except NameError:
app.logging.error("Something went horribly wrong with StripePlan")
app.logger.error("Something went horribly wrong with StripePlan")

app.logger.debug("Adding Subscription to "
"plan {} for user {}"
Expand All @@ -214,11 +253,13 @@ def donation():
app.logger.debug("Creating Transaction")
tx = model_stripe_data(req_data=params)

app.logger.debug("Creating StripeDonation - anon: {}, card_id: {}, "
"charge_id: {}, email: {}".format(params['anonymous'],
params['stripe_token'],
charge_data['charge_id'],
charge_data['customer_id']))
app.logger.debug(
"Creating StripeDonation - anon: {}, card_id: {}, "
"charge_id: {}, email: {}".format(
params['anonymous'],
params['stripe_token'],
charge_data['charge_id'],
charge_data['customer_id']))
sd = StripeDonation(
anonymous=params['anonymous'],
card_id=params['stripe_token'],
Expand Down Expand Up @@ -250,15 +291,16 @@ def index():

# donations = db.session.query(Donation).limit(10)
donations = []
STRIPE_KEY = app.get_stripe_key('PUBLIC')

nonce = create_nonce()

return render_template('main.html',
data={
'git_sha': git_sha,
'repo_path': repo_path,
'recent_donations': donations,
'projects': sorted_projects,
'stripe_pk': STRIPE_KEY
'nonce': nonce
})


Expand Down
19 changes: 19 additions & 0 deletions donate/static/js/helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@


function donateHttpGetAsync(value, cback)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cback(this);
}
}
xhttp.open("GET", "nonce/"+value, true);
xhttp.send();
}

function initStripe(xhttp) {
// var data = document.getElementById('special-thing');
var data = JSON.parse(xhttp.responseText);
stripe = Stripe.setPublishableKey(data);
}
2 changes: 1 addition & 1 deletion donate/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
{% block head_css_page %}{% endblock head_css_page %}
{% endblock head_css %}
{% block head_script_section %}
<script src="{{ url_for('static', filename='js/helper.js') }}"></script>
<script src="https://js.stripe.com/v2/"></script>
<!-- script>
var stripe = Stripe.setPublishableKey({# {{ data.stripe_pk }}) #}
Expand Down Expand Up @@ -59,7 +60,6 @@
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

<!-- Internal scripts -->
<!-- script>Stripe.setPublishableKey("{{ data.stripe_pk }}");</script -->
<script src="{{ url_for('static', filename='js/donate.js') }}"></script>

</body>
Expand Down
3 changes: 2 additions & 1 deletion donate/templates/main.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
{% block head_script_section %}
{{ super() }}
<script>
var stripe = Stripe.setPublishableKey("{{ data.stripe_pk }}")
var stripe = "asdf";
donateHttpGetAsync("{{ data.nonce }}", initStripe, stripe)
</script>
{% endblock %}
{% block content %}
Expand Down
3 changes: 3 additions & 0 deletions donate/templates/nonce.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{% block content %}
{{ data.value | tojson }}
{% endblock %}