Example #1
0
File: app.py Project: anna-0/cs50
def mysubscription():

    client = gocardless_pro.Client(access_token=access_token,
                                   environment='sandbox')

    # Gets record lists from GC
    customers = client.customers.list().records
    mandates = client.mandates.list().records
    subscrips = client.subscriptions.list().records

    mysubs = 0
    dict = {'email': '', 'amount': ''}

    # Loops through subscriptions on GC to count up monthly total of subscription donations, skipping if cancelled
    for subscrip in subscrips:
        if subscrip.status == 'cancelled':
            continue
        dict['amount'] = (format(subscrip.amount))
        # Connects via subscriptions to mandates using their IDs, and then to customers via mandates using customer IDs
        for mandate in mandates:
            if mandate.id != subscrip.links.mandate:
                continue
            for customer in customers:
                if mandate.links.customer != customer.id:
                    continue
                # Pulls out names and plugs into name array
                dict['email'] = customer.email

                if dict['email'] == session["email"]:
                    mysubs = int(int(dict['amount']) / 100)

    return render_template("mysubscription.html", mysubs=mysubs)
def Handle_Payment(request):
    client = gocardless_pro.Client(
    access_token= "sandbox_B0pUDWsTgiJ-jK-jo4-M8KUp7xxS0-I_pgnc4-vr", 
    environment='sandbox'
    )
    redirect_flow = client.redirect_flows.create(
    params={
        "description" : "EBENEZER CHURCH Subscription Setup", # This will be shown on the payment pages
        "session_token" : "Jl0--Klnzjdlw30fjallZKo", # Not the access token
        "success_redirect_url" : "https://developer.gocardless.com/example-redirect-uri/",
        # "prefilled_customer": { # Optionally, prefill customer details on the payment page
        #     "given_name": "Tim",
        #     "family_name": "Rogers",
        #     "email": "*****@*****.**",
        #     "address_line1": "338-346 Goswell Road",
        #     "city": "London",
        #     "postal_code": "EC1V 7LQ"
        #     }
        }
    )

    # Hold on to this ID - we'll need it when we
    # "confirm" the redirect flow later
    print("ID: {} ".format(redirect_flow.id))
    print("URL: {} ".format(redirect_flow.redirect_url))
    ru = redirect_flow.redirect_url
    return redirect(ru)
Example #3
0
 def initialize_client(self):
     self.environment = self.get_environment()
     try:
         self.client = gocardless_pro.Client(access_token=self.access_token,
                                             environment=self.environment)
         return self.client
     except Exception as e:
         frappe.throw(e)
Example #4
0
def get_gocardless_client():
    if not getattr(settings, "GOCARDLESS_ACCESS_TOKEN", None) or not getattr(
            settings, "GOCARDLESS_ENVIRONMENT", None):
        raise Exception("No GoCardless credentials configured")
    return gocardless_pro.Client(
        access_token=settings.GOCARDLESS_ACCESS_TOKEN,
        environment=settings.GOCARDLESS_ENVIRONMENT,
    )
Example #5
0
    def client_from_settings(access_token=None, environment=None):
        """Get GoCardless Client from token and environment.

        Uses access_token and environment by default if nothing was given.
        """
        access_token = settings.GOCARDLESS['access_token'] \
            if access_token is None else access_token

        environment = settings.GOCARDLESS['environment'] \
            if environment is None else environment

        return gocardless_pro.Client(access_token=access_token,
                                     environment=environment)
Example #6
0
File: app.py Project: anna-0/cs50
def loggedin():

    client = gocardless_pro.Client(access_token=access_token,
                                   environment='sandbox')

    # Gets record lists from GC
    customers = client.customers.list().records
    mandates = client.mandates.list().records
    subscrips = client.subscriptions.list().records

    # Initialises variables to plug into page
    total = 0
    donors = 0
    names = []
    GCemails = []

    # Loops through subscriptions on GC to count up monthly total of subscription donations, skipping if cancelled
    for subscrip in subscrips:
        if subscrip.status == 'cancelled':
            continue
        donors += 1
        monthlyamount = (format(subscrip.amount))
        total += int(monthlyamount)

        # Connects via subscriptions to mandates using their IDs, and then to customers via mandates using customer IDs
        for mandate in mandates:
            if mandate.id != subscrip.links.mandate:
                continue
            for customer in customers:
                if mandate.links.customer != customer.id:
                    continue

                # Pulls out names and plugs into name array
                firstname = customer.given_name
                lastname = customer.family_name
                name = firstname + ' ' + lastname[0]
                names.append(name)
                GCemails.append(customer.email)

    if session["email"] in GCemails:
        db.execute("UPDATE users SET ispatron = 1 WHERE id=:user_id",
                   user_id=session["user_id"])
        session["ispatron"] = 1

    # Formats monthly total back to float from GC int
    monthlytotal = total / 100

    return render_template("index.html",
                           donors=donors,
                           names=names,
                           monthlytotal=monthlytotal)
Example #7
0
    def __init__(self, request):
        self.request = request
        # We need the session to be saved before it gets a session_key
        # This is because the code is called from a middleware
        self.request.session.save()

        if getattr(settings, 'GOCARDLESS_USE_SANDBOX', False):
            gc_environment = "sandbox"
        else:
            gc_environment = "live"

        self.client = gocardless_pro.Client(
            access_token=settings.GOCARDLESS_ACCESS_TOKEN,
            environment=gc_environment)
Example #8
0
    def __init__(self, request):
        self.request = request
        # We need the session to be saved before it gets a session_key
        # This is because the code is called from a middleware
        self.request.session.save()

        if not self.request.session.get("GC_SESSION_KEY"):
            self.request.session["GC_SESSION_KEY"] = get_random_string(
                length=50)

        if getattr(settings, "GOCARDLESS_USE_SANDBOX", False):
            gc_environment = "sandbox"
        else:
            gc_environment = "live"

        self.client = gocardless_pro.Client(
            access_token=settings.GOCARDLESS_ACCESS_TOKEN,
            environment=gc_environment,
        )
Example #9
0
def direct_debit_callback():

    if not session.get('commitment', False):
        return redirect(url_for('condition'))

    try:
        #save the commitment (double check not a duplicate)
        commitment = models.Commitment()
        commitment.name = session['commitment']['name']
        commitment.mobile_number = session['commitment']['mobile_number']
        commitment.rate = session['commitment']['rate']
        commitment = commitment.save()

        #complete the direct debit mandate
        client = gocardless_pro.Client(
            access_token=app.config['GOCARDLESS_ACCESS_TOKEN'],
            environment=app.config['GOCARDLESS_ENVIRONMENT'])
        redirect_flow_id = request.args.get('redirect_flow_id')
        redirect_flow = client.redirect_flows.complete(
            redirect_flow_id,
            params={'session_token': session['gocardless_session_token']})

        #save the mandate
        commitment.gocardless_mandate_id = redirect_flow.links.mandate
        commitment.save()

    except NotUniqueError:
        flash('Someone has already signed up with that phone number', 'error')
        return redirect(url_for('condition'))
    except gocardless_pro.errors.GoCardlessProError:
        flash(
            'Sorry, something went wrong, the direct debit mandate has not been created',
            'error')
        commitment.delete()
        return redirect(url_for('condition'))

    #clear session
    session.pop('gocardless_session_token', None)
    session.pop('commitment', None)

    #off to the final page
    return redirect(url_for('committed'))
Example #10
0
    def __init__(self, construct):
        try:
            access_token = construct["access_token"]
        except KeyError:
            access_token = None

        try:
            environment = construct["environment"]
        except KeyError:
            environment = 'live'

        self.transactions = []
        self.partners = []
        # We recommend storing your access token in an
        # environment variable for security
        if access_token is None:
            access_token = os.getenv('gocardless')
        self.gcclient = gocardless_pro.Client(
            # Change this to 'live' when you are ready to go live.
            access_token,
            environment=environment)
Example #11
0
def direct_debit():

    if not session.get('commitment', False):
        return redirect(url_for('condition'))

    if request.method == 'POST':
        client = gocardless_pro.Client(
            access_token=app.config['GOCARDLESS_ACCESS_TOKEN'],
            environment=app.config['GOCARDLESS_ENVIRONMENT'])
        flow = client.redirect_flows.create(
            params={
                'scheme':
                'bacs',
                'session_token':
                session['gocardless_session_token'],
                'description':
                'No payments will be taken unless the target is reached',
                'success_redirect_url':
                url_for('direct_debit_callback', _external=True)
            })
        return redirect(flow.redirect_url)
    return render_template('direct-debit.html')
Example #12
0
def create_subscriptions():
  if len(models.Milestone.objects(name='subscriptions-created')) == 0:
      commitment_count = models.Commitment.objects.count()
      if float(commitment_count) >= (float(app.config['BECKTON_TARGET'])):
          milestone = models.Milestone(name='subscriptions-created')
          if milestone.save():

              for commitment in models.Commitment.objects():
                  
                  client = gocardless_pro.Client(access_token=app.config['GOCARDLESS_ACCESS_TOKEN'], environment=app.config['GOCARDLESS_ENVIRONMENT'])
                  
                  client.subscriptions.create(params={
                    "amount": str(commitment.rate),
                    "currency": app.config['BECKTON_DIRECT_DEBIT_CURRENCY'],
                    "name": app.config['BECKTON_DIRECT_DEBIT_NAME'],
                    "interval_unit": "monthly",
                    "day_of_month":  "1",
                    "links": {
                      "mandate": commitment.gocardless_mandate_id
                    }
                  })

                  time.sleep(1)
Example #13
0
def create_app(dev_server=False, config_override=None):
    app = Flask(__name__)
    app.config.from_envvar("SETTINGS_FILE")
    if config_override:
        app.config.from_mapping(config_override)
    app.jinja_options["extensions"].append("jinja2.ext.do")

    if install_logging:
        create_logging_manager(app)
        # Flask has now kindly installed its own log handler which we will summarily remove.
        app.logger.propagate = 1
        app.logger.handlers = []
        if not app.debug:
            logging.root.setLevel(logging.INFO)
        else:
            logging.root.setLevel(logging.DEBUG)

    from apps.metrics import request_duration, request_total

    # Must be run before crsf.init_app
    @app.before_request
    def before_request():
        request._start_time = time.time()

    @app.after_request
    def after_request(response):
        try:
            request_duration.labels(
                request.endpoint,
                request.method).observe(time.time() - request._start_time)
        except AttributeError:
            logging.exception(
                "Request without _start_time - check app.before_request ordering"
            )
        request_total.labels(request.endpoint, request.method,
                             response.status_code).inc()
        return response

    for extension in (csrf, cache, db, mail, static_digest, toolbar):
        extension.init_app(app)

    def log_email(message, app):
        app.logger.info("Emailing %s: %r", message.recipients, message.subject)

    email_dispatched.connect(log_email)

    cors_origins = ["https://map.emfcamp.org", "https://wiki.emfcamp.org"]
    if app.config.get("DEBUG"):
        cors_origins = ["http://localhost:8080", "https://maputnik.github.io"]
    CORS(app,
         resources={r"/api/*": {
             "origins": cors_origins
         }},
         supports_credentials=True)

    migrate.init_app(app, db)

    login_manager.init_app(app, add_context_processor=True)
    app.login_manager.login_view = "users.login"

    from models.user import User, load_anonymous_user
    from models import site_state, feature_flag

    @login_manager.user_loader
    def load_user(userid):
        user = User.query.filter_by(id=userid).first()
        if user:
            set_user_id(user.email)
        return user

    login_manager.anonymous_user = load_anonymous_user

    global gocardless_client
    gocardless_client = gocardless_pro.Client(
        access_token=app.config["GOCARDLESS_ACCESS_TOKEN"],
        environment=app.config["GOCARDLESS_ENVIRONMENT"],
    )
    stripe.api_key = app.config["STRIPE_SECRET_KEY"]
    pytransferwise.environment = app.config["TRANSFERWISE_ENVIRONMENT"]
    pytransferwise.api_key = app.config["TRANSFERWISE_API_TOKEN"]

    @app.before_request
    def load_per_request_state():
        site_state.get_states()
        feature_flag.get_db_flags()

    if app.config.get("NO_INDEX"):
        # Prevent staging site from being displayed on Google
        @app.after_request
        def send_noindex_header(response):
            response.headers["X-Robots-Tag"] = "noindex, nofollow"
            return response

    @app.before_request
    def simple_cache_warning():
        if not dev_server and app.config.get("CACHE_TYPE", "null") == "simple":
            logging.warning(
                "Per-process cache being used outside dev server - refreshing will not work"
            )

    @app.context_processor
    def add_csp_nonce():
        g.csp_nonce = secrets.token_urlsafe(16)
        return {"csp_nonce": g.csp_nonce}

    @app.after_request
    def send_security_headers(response):
        use_hsts = app.config.get("HSTS", False)
        if use_hsts:
            max_age = app.config.get("HSTS_MAX_AGE", 3600 * 24 * 30 * 6)
            response.headers[
                "Strict-Transport-Security"] = "max-age=%s" % max_age

        response.headers["X-Frame-Options"] = "deny"
        response.headers["X-Content-Type-Options"] = "nosniff"
        response.headers["X-XSS-Protection"] = "1; mode=block"
        response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"

        csp = {
            "script-src": ["'self'", "https://js.stripe.com"],
            "style-src":
            ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
            # Note: the below is more strict as it only allows inline styles in style=
            # attributes, however it's unsupported by Safari at this time...
            #  "style-src-attr": ["'unsafe-inline'"],
            "font-src": ["'self'", "https://fonts.gstatic.com"],
            "frame-src": [
                "https://js.stripe.com/",
                "https://media.ccc.de",
                "https://www.youtube.com",
                "https://archive.org",
            ],
        }

        # Edit record hash to support the modal dialogues in flask-admin
        csp["script-src"].append(
            "'sha256-Jxve8bBSodQplIZw4Y1walBJ0hFTx8sZ5xr+Pjr/78Y='")

        # View record hash to support the modal dialogues in flask-admin
        csp["script-src"].append(
            "'sha256-XOlW2U5UiDeV2S/HgKqbp++Fo1I5uiUT2thFRUeFW/g='")

        if app.config.get("DEBUG_TB_ENABLED"):
            # This hash is for the flask debug toolbar. It may break once they upgrade it.
            csp["script-src"].append(
                "'sha256-zWl5GfUhAzM8qz2mveQVnvu/VPnCS6QL7Niu6uLmoWU='")

        if "csp_nonce" in g:
            csp["script-src"].append(f"'nonce-{g.csp_nonce}'")

        value = "; ".join(k + " " + " ".join(v) for k, v in csp.items())

        if app.config.get("DEBUG"):
            response.headers["Content-Security-Policy"] = value
        else:
            response.headers["Content-Security-Policy-Report-Only"] = (
                value +
                "; report-uri https://emfcamp.report-uri.com/r/d/csp/reportOnly"
            )
            response.headers[
                "Report-To"] = '{"group":"default","max_age":31536000,"endpoints":[{"url":"https://emfcamp.report-uri.com/a/d/g"}],"include_subdomains":false}'

            # Disable Network Error Logging.
            # This doesn't seem to be very useful and it's using up our report-uri quota.
            response.headers["NEL"] = '{"max_age":0}'
        return response

    if not app.debug:

        @app.errorhandler(Exception)
        def handle_exception(e):
            """ Generic exception handler to catch and log unhandled exceptions in production. """
            if isinstance(e, HTTPException):
                # HTTPException is used to implement flask's HTTP errors so pass it through.
                return e

            app.logger.exception("Unhandled exception in request: %s", request)
            return render_template("errors/500.html"), 500

    @app.errorhandler(404)
    def handle_404(e):
        return render_template("errors/404.html"), 404

    @app.errorhandler(500)
    def handle_500(e):
        return render_template("errors/500.html"), 500

    @app.shell_context_processor
    def shell_imports():
        ctx = {}

        # Import models and constants
        import models

        for attr in dir(models):
            if attr[0].isupper():
                ctx[attr] = getattr(models, attr)

        # And just for convenience
        ctx["db"] = db

        return ctx

    from apps.common import load_utility_functions

    load_utility_functions(app)

    from apps.base import base
    from apps.metrics import metrics
    from apps.users import users
    from apps.tickets import tickets
    from apps.payments import payments
    from apps.cfp import cfp
    from apps.cfp_review import cfp_review
    from apps.schedule import schedule
    from apps.arrivals import arrivals
    from apps.api import api_bp
    from apps.villages import villages

    app.register_blueprint(base)
    app.register_blueprint(users)
    app.register_blueprint(metrics)
    app.register_blueprint(tickets)
    app.register_blueprint(payments)
    app.register_blueprint(cfp)
    app.register_blueprint(cfp_review, url_prefix="/cfp-review")
    app.register_blueprint(schedule)
    app.register_blueprint(arrivals, url_prefix="/arrivals")
    app.register_blueprint(api_bp, url_prefix="/api")
    app.register_blueprint(villages, url_prefix="/villages")

    if app.config.get("VOLUNTEERS"):
        from apps.volunteer import volunteer

        app.register_blueprint(volunteer, url_prefix="/volunteer")

        from flask_admin import Admin
        from apps.volunteer.flask_admin_base import VolunteerAdminIndexView

        global volunteer_admin
        volunteer_admin = Admin(
            url="/volunteer/admin",
            name="EMF Volunteers",
            template_mode="bootstrap3",
            index_view=VolunteerAdminIndexView(url="/volunteer/admin"),
            base_template="volunteer/admin/flask-admin-base.html",
        )
        volunteer_admin.endpoint_prefix = "volunteer_admin"
        volunteer_admin.init_app(app)

        import apps.volunteer.admin  # noqa: F401

    from apps.admin import admin

    app.register_blueprint(admin, url_prefix="/admin")

    from apps.notification import notify

    app.register_blueprint(notify, url_prefix="/notify")

    return app
Example #14
0
# WARNING: Do not edit by hand, this file was generated by Crank:
#
#   https://github.com/gocardless/crank
#

import os
import re
import json

import responses

import gocardless_pro


def load_fixture(resource):
    fixtures_path = os.path.join(os.path.dirname(__file__), 'fixtures')
    fixture_filename = '{0}.json'.format(resource)
    fixture_path = os.path.join(fixtures_path, fixture_filename)
    return json.load(open(fixture_path))


def stub_response(resource_fixture):
    path = re.sub(r':(\w+)', r'\w+', resource_fixture['path_template'])
    url_pattern = re.compile('http://example.com' + path)
    json_body = json.dumps(resource_fixture['body'])
    responses.add(resource_fixture['method'], url_pattern, body=json_body)


client = gocardless_pro.Client(access_token='secret',
                               base_url='http://example.com')
Example #15
0
def create_app(dev_server=False):
    app = Flask(__name__)
    app.config.from_envvar('SETTINGS_FILE')
    app.jinja_options['extensions'].append('jinja2.ext.do')

    if install_logging:
        create_logging_manager(app)
        # Flask has now kindly installed its own log handler which we will summarily remove.
        app.logger.propagate = 1
        app.logger.handlers = []
        if not app.debug:
            logging.root.setLevel(logging.INFO)
        else:
            logging.root.setLevel(logging.DEBUG)

    for extension in (cdn, csrf, cache, db, mail, assets, toolbar):
        extension.init_app(app)

    migrate.init_app(app, db)

    login_manager.setup_app(app, add_context_processor=True)
    app.login_manager.login_view = 'users.login'

    from models.user import User, load_anonymous_user
    from models import site_state, feature_flag

    @login_manager.user_loader
    def load_user(userid):
        user = User.query.filter_by(id=userid).first()
        if user:
            set_user_id(user.email)
        return user

    login_manager.anonymous_user = load_anonymous_user

    if app.config.get('TICKETS_SITE'):
        global gocardless_client
        gocardless_client = gocardless_pro.Client(
            access_token=app.config['GOCARDLESS_ACCESS_TOKEN'],
            environment=app.config['GOCARDLESS_ENVIRONMENT'])
        stripe.api_key = app.config['STRIPE_SECRET_KEY']

        @app.before_request
        def load_per_request_state():
            site_state.get_states()
            feature_flag.get_db_flags()

    if app.config.get('NO_INDEX'):
        # Prevent staging site from being displayed on Google
        @app.after_request
        def send_noindex_header(response):
            response.headers['X-Robots-Tag'] = 'noindex, nofollow'
            return response

    @app.before_request
    def simple_cache_warning():
        if not dev_server and app.config.get('CACHE_TYPE', 'null') == 'simple':
            logging.warn(
                'Per-process cache being used outside dev server - refreshing will not work'
            )

    @app.after_request
    def send_security_headers(response):
        use_hsts = app.config.get('HSTS', False)
        if use_hsts:
            max_age = app.config.get('HSTS_MAX_AGE', 3600 * 24 * 7 * 4)
            response.headers[
                'Strict-Transport-Security'] = 'max-age=%s' % max_age

        response.headers['X-Frame-Options'] = 'deny'
        response.headers['X-Content-Type-Options'] = 'nosniff'

        return response

    from apps.metrics import request_duration, request_total

    @app.before_request
    def before_request():
        request._start_time = time.time()

    @app.after_request
    def after_request(response):
        try:
            request_duration.labels(
                request.endpoint,
                request.method).observe(time.time() - request._start_time)
        except AttributeError:
            # In some cases this isn't present?
            logging.exception("Request without _start_time")
        request_total.labels(request.endpoint, request.method,
                             response.status_code).inc()
        return response

    @app.errorhandler(404)
    def handle_404(e):
        return render_template('errors/404.html'), 404

    @app.errorhandler(500)
    def handle_500(e):
        return render_template('errors/500.html'), 500

    from apps.common import load_utility_functions
    load_utility_functions(app)

    from apps.base import base
    from apps.metrics import metrics
    from apps.users import users
    from apps.tickets import tickets
    from apps.payments import payments
    from apps.cfp import cfp
    from apps.cfp_review import cfp_review
    from apps.schedule import schedule
    from apps.arrivals import arrivals
    app.register_blueprint(base)
    app.register_blueprint(users)
    app.register_blueprint(metrics)
    app.register_blueprint(tickets)
    app.register_blueprint(payments)
    app.register_blueprint(cfp)
    app.register_blueprint(cfp_review, url_prefix='/cfp-review')
    app.register_blueprint(schedule)
    app.register_blueprint(arrivals, url_prefix='/arrivals')

    if app.config.get('VOLUNTEERS'):
        from apps.volunteering import volunteering
        app.register_blueprint(volunteering, url_prefix='/volunteering')
        from apps.volunteers import volunteers
        app.register_blueprint(volunteers, url_prefix='/volunteers')

    from apps.admin import admin
    app.register_blueprint(admin, url_prefix='/admin')

    return app
Example #16
0
def get_gocardless_client():
    return gocardless_pro.Client(
        access_token=getattr(settings, "GOCARDLESS_ACCESS_TOKEN", None),
        environment=getattr(settings, "GOCARDLESS_ENVIRONMENT", None)
    )
Example #17
0
def create_app(dev_server=False):
    app = Flask(__name__)
    app.config.from_envvar("SETTINGS_FILE")
    app.jinja_options["extensions"].append("jinja2.ext.do")

    if install_logging:
        create_logging_manager(app)
        # Flask has now kindly installed its own log handler which we will summarily remove.
        app.logger.propagate = 1
        app.logger.handlers = []
        if not app.debug:
            logging.root.setLevel(logging.INFO)
        else:
            logging.root.setLevel(logging.DEBUG)

    from apps.metrics import request_duration, request_total

    # Must be run before crsf.init_app
    @app.before_request
    def before_request():
        request._start_time = time.time()

    @app.after_request
    def after_request(response):
        try:
            request_duration.labels(
                request.endpoint,
                request.method).observe(time.time() - request._start_time)
        except AttributeError:
            logging.exception(
                "Request without _start_time - check app.before_request ordering"
            )
        request_total.labels(request.endpoint, request.method,
                             response.status_code).inc()
        return response

    for extension in (csrf, cache, db, mail, static_digest, toolbar):
        extension.init_app(app)

    def log_email(message, app):
        app.logger.info("Emailing %s: %r", message.recipients, message.subject)

    email_dispatched.connect(log_email)

    cors_origins = ["https://map.emfcamp.org", "https://wiki.emfcamp.org"]
    if app.config.get("DEBUG"):
        cors_origins = ["http://localhost:8080", "https://maputnik.github.io"]
    CORS(app,
         resources={r"/api/*": {
             "origins": cors_origins
         }},
         supports_credentials=True)

    migrate.init_app(app, db)

    login_manager.init_app(app, add_context_processor=True)
    app.login_manager.login_view = "users.login"

    from models.user import User, load_anonymous_user
    from models import site_state, feature_flag

    @login_manager.user_loader
    def load_user(userid):
        user = User.query.filter_by(id=userid).first()
        if user:
            set_user_id(user.email)
        return user

    login_manager.anonymous_user = load_anonymous_user

    global gocardless_client
    gocardless_client = gocardless_pro.Client(
        access_token=app.config["GOCARDLESS_ACCESS_TOKEN"],
        environment=app.config["GOCARDLESS_ENVIRONMENT"],
    )
    stripe.api_key = app.config["STRIPE_SECRET_KEY"]

    @app.before_request
    def load_per_request_state():
        site_state.get_states()
        feature_flag.get_db_flags()

    if app.config.get("NO_INDEX"):
        # Prevent staging site from being displayed on Google
        @app.after_request
        def send_noindex_header(response):
            response.headers["X-Robots-Tag"] = "noindex, nofollow"
            return response

    @app.before_request
    def simple_cache_warning():
        if not dev_server and app.config.get("CACHE_TYPE", "null") == "simple":
            logging.warn(
                "Per-process cache being used outside dev server - refreshing will not work"
            )

    @app.after_request
    def send_security_headers(response):
        use_hsts = app.config.get("HSTS", False)
        if use_hsts:
            max_age = app.config.get("HSTS_MAX_AGE", 3600 * 24 * 30 * 6)
            response.headers[
                "Strict-Transport-Security"] = "max-age=%s" % max_age

        response.headers["X-Frame-Options"] = "deny"
        response.headers["X-Content-Type-Options"] = "nosniff"

        return response

    if not app.debug:

        @app.errorhandler(Exception)
        def handle_exception(e):
            """ Generic exception handler to catch and log unhandled exceptions in production. """
            if isinstance(e, HTTPException):
                # HTTPException is used to implement flask's HTTP errors so pass it through.
                return e

            app.logger.exception("Unhandled exception in request: %s", request)
            return render_template("errors/500.html"), 500

    @app.errorhandler(404)
    def handle_404(e):
        return render_template("errors/404.html"), 404

    @app.errorhandler(500)
    def handle_500(e):
        return render_template("errors/500.html"), 500

    @app.shell_context_processor
    def shell_imports():
        ctx = {}

        # Import models and constants
        import models

        for attr in dir(models):
            if attr[0].isupper():
                ctx[attr] = getattr(models, attr)

        # And just for convenience
        ctx["db"] = db

        return ctx

    from apps.common import load_utility_functions

    load_utility_functions(app)

    from apps.base import base
    from apps.metrics import metrics
    from apps.users import users
    from apps.tickets import tickets
    from apps.payments import payments
    from apps.cfp import cfp
    from apps.cfp_review import cfp_review
    from apps.schedule import schedule
    from apps.arrivals import arrivals
    from apps.api import api_bp

    app.register_blueprint(base)
    app.register_blueprint(users)
    app.register_blueprint(metrics)
    app.register_blueprint(tickets)
    app.register_blueprint(payments)
    app.register_blueprint(cfp)
    app.register_blueprint(cfp_review, url_prefix="/cfp-review")
    app.register_blueprint(schedule)
    app.register_blueprint(arrivals, url_prefix="/arrivals")
    app.register_blueprint(api_bp, url_prefix="/api")

    if app.config.get("VOLUNTEERS"):
        from apps.volunteer import volunteer

        app.register_blueprint(volunteer, url_prefix="/volunteer")

        from flask_admin import Admin
        from apps.volunteer.flask_admin_base import VolunteerAdminIndexView

        global volunteer_admin
        volunteer_admin = Admin(
            url="/volunteer/admin",
            name="EMF Volunteers",
            template_mode="bootstrap3",
            index_view=VolunteerAdminIndexView(url="/volunteer/admin"),
            base_template="volunteer/admin/flask-admin-base.html",
        )
        volunteer_admin.endpoint_prefix = "volunteer_admin"
        volunteer_admin.init_app(app)

        import apps.volunteer.admin  # noqa: F401

    from apps.admin import admin

    app.register_blueprint(admin, url_prefix="/admin")

    from apps.notification import notify

    app.register_blueprint(notify, url_prefix="/notify")

    return app
Example #18
0
import gocardless_pro
import csv

token = os.environ['ACCESS_TOKEN']
client = gocardless_pro.Client(access_token=token, environment='sandbox')

#Create empty array
array = []

#Setup the search query, we are using created from
mandates = client.mandates.list(
    params={"created_at[gte]": "2021-04-14T00:00:00.123Z"})

for mandate in mandates.records:
    customer = client.customers.get(mandate.links.customer)
    bankaccount = client.customer_bank_accounts.get(
        mandate.links.customer_bank_account)
    array.append([
        mandate.id, customer.id, customer.given_name, customer.family_name,
        customer.company_name, customer.email, bankaccount.currency
    ])

while mandates.after:
    mandates = client.mandates.list(params={
        "created_at[gte]": "2021-04-14T00:00:00.123Z",
        "after": mandates.after
    })

    for mandate in mandates.records:
        customer = client.customers.get(mandate.links.customer)
        bankaccount = client.customer_bank_accounts.get(
 def __init__(self):
     # gocardless are changing there api, not sure if we can switch yet
     self.client = gocardless_pro.Client(
         access_token=payment_providers['gocardless']['credentials']
         ['access_token'],
         environment=payment_providers['gocardless']['environment'])
Example #20
0
def create_app(dev_server=False):
    app = Flask(__name__)
    app.config.from_envvar('SETTINGS_FILE')
    app.jinja_options['extensions'].append('jinja2.ext.do')

    if install_logging:
        create_logging_manager(app)
        # Flask has now kindly installed its own log handler which we will summarily remove.
        app.logger.propagate = 1
        app.logger.handlers = []
        if not app.debug:
            logging.root.setLevel(logging.INFO)
        else:
            logging.root.setLevel(logging.DEBUG)

    from apps.metrics import request_duration, request_total

    # Must be run before crsf.init_app
    @app.before_request
    def before_request():
        request._start_time = time.time()

    @app.after_request
    def after_request(response):
        try:
            request_duration.labels(
                request.endpoint,
                request.method).observe(time.time() - request._start_time)
        except AttributeError:
            logging.exception(
                "Request without _start_time - check app.before_request ordering"
            )
        request_total.labels(request.endpoint, request.method,
                             response.status_code).inc()
        return response

    for extension in (cdn, csrf, cache, db, mail, assets, toolbar):
        extension.init_app(app)

    cors_origins = ['https://map.emfcamp.org', 'https://wiki.emfcamp.org']
    if app.config.get('DEBUG'):
        cors_origins = ['http://localhost:8080', 'https://maputnik.github.io']
    CORS(app,
         resources={r"/api/*": {
             "origins": cors_origins
         }},
         supports_credentials=True)

    migrate.init_app(app, db)

    login_manager.setup_app(app, add_context_processor=True)
    app.login_manager.login_view = 'users.login'

    from models.user import User, load_anonymous_user
    from models import site_state, feature_flag

    @login_manager.user_loader
    def load_user(userid):
        user = User.query.filter_by(id=userid).first()
        if user:
            set_user_id(user.email)
        return user

    login_manager.anonymous_user = load_anonymous_user

    if app.config.get('TICKETS_SITE'):
        global gocardless_client
        gocardless_client = gocardless_pro.Client(
            access_token=app.config['GOCARDLESS_ACCESS_TOKEN'],
            environment=app.config['GOCARDLESS_ENVIRONMENT'])
        stripe.api_key = app.config['STRIPE_SECRET_KEY']

        @app.before_request
        def load_per_request_state():
            site_state.get_states()
            feature_flag.get_db_flags()

    if app.config.get('NO_INDEX'):
        # Prevent staging site from being displayed on Google
        @app.after_request
        def send_noindex_header(response):
            response.headers['X-Robots-Tag'] = 'noindex, nofollow'
            return response

    @app.before_request
    def simple_cache_warning():
        if not dev_server and app.config.get('CACHE_TYPE', 'null') == 'simple':
            logging.warn(
                'Per-process cache being used outside dev server - refreshing will not work'
            )

    @app.after_request
    def send_security_headers(response):
        use_hsts = app.config.get('HSTS', False)
        if use_hsts:
            max_age = app.config.get('HSTS_MAX_AGE', 3600 * 24 * 7 * 4)
            response.headers[
                'Strict-Transport-Security'] = 'max-age=%s' % max_age

        response.headers['X-Frame-Options'] = 'deny'
        response.headers['X-Content-Type-Options'] = 'nosniff'

        return response

    @app.errorhandler(404)
    def handle_404(e):
        return render_template('errors/404.html'), 404

    @app.errorhandler(500)
    def handle_500(e):
        return render_template('errors/500.html'), 500

    @app.shell_context_processor
    def shell_imports():
        ctx = {}

        # Import models and constants
        import models
        for attr in dir(models):
            if attr[0].isupper():
                ctx[attr] = getattr(models, attr)

        # And just for convenience
        ctx['db'] = db

        return ctx

    from apps.common import load_utility_functions
    load_utility_functions(app)

    from apps.base import base
    from apps.metrics import metrics
    from apps.users import users
    from apps.tickets import tickets
    from apps.payments import payments
    from apps.cfp import cfp
    from apps.cfp_review import cfp_review
    from apps.schedule import schedule
    from apps.arrivals import arrivals
    from apps.api import api_bp
    app.register_blueprint(base)
    app.register_blueprint(users)
    app.register_blueprint(metrics)
    app.register_blueprint(tickets)
    app.register_blueprint(payments)
    app.register_blueprint(cfp)
    app.register_blueprint(cfp_review, url_prefix='/cfp-review')
    app.register_blueprint(schedule)
    app.register_blueprint(arrivals, url_prefix='/arrivals')
    app.register_blueprint(api_bp, url_prefix='/api')

    if app.config.get('VOLUNTEERS'):
        from apps.volunteer import volunteer
        app.register_blueprint(volunteer, url_prefix='/volunteer')

        from flask_admin import Admin
        from apps.volunteer.flask_admin_base import VolunteerAdminIndexView

        global volunteer_admin
        volunteer_admin = Admin(
            url='/volunteer/admin',
            name='EMF Volunteers',
            template_mode='bootstrap3',
            index_view=VolunteerAdminIndexView(url='/volunteer/admin'),
            base_template='volunteer/admin/flask-admin-base.html')
        volunteer_admin.endpoint_prefix = 'volunteer_admin'
        volunteer_admin.init_app(app)

        import apps.volunteer.admin  # noqa: F401

    from apps.admin import admin
    app.register_blueprint(admin, url_prefix='/admin')

    return app
Example #21
0
from django.shortcuts import redirect
from django.http import HttpResponse
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.urls import reverse as url_reverse

import gocardless_pro as gocardless
from gocardless_pro.errors import InvalidApiUsageError, InvalidStateError

from .models import Customer, Subscription
from lhspayments.models import Payment

from lhspayments import membershiptools

gc_client = gocardless.Client(
    access_token=settings.GOCARDLESS_CREDENTIALS['access_token'],
    environment=settings.GOCARDLESS_ENV)


# Helpers
def require_gocardless_user(f):
    @wraps(f)
    def decorator(request):
        if not request.user.gocardless_user:
            # User isn't a gocardless user, send them to the main mambers page
            return redirect("/members/")
        return f(request)

    return login_required(decorator)