Пример #1
0
def auth_callback():
    # Put together params for token request
    code = flask.request.args['code']
    context = flask.request.args['context']
    scope = flask.request.args['scope']
    store_hash = context.split('/')[1]
    redirect = app.config['APP_URL'] + flask.url_for('auth_callback')

    # Fetch a permanent oauth token. This will throw an exception on error,
    # which will get caught by our error handler above.
    client = BigcommerceApi(client_id=client_id(), store_hash=store_hash)
    token = client.oauth_fetch_token(client_secret(), code, context, scope,
                                     redirect)
    bc_user_id = token['user']['id']
    email = token['user']['email']
    access_token = token['access_token']

    # Create or update store
    store = Store.query.filter_by(store_hash=store_hash).first()
    if store is None:
        store = Store(store_hash, access_token, scope)
        db.session.add(store)
        db.session.commit()
    else:
        store.access_token = access_token
        store.scope = scope
        db.session.add(store)
        db.session.commit()
        # If the app was installed before, make sure the old admin user is no longer marked as the admin
        oldadminuser = StoreUser.query.filter_by(store_id=store.id,
                                                 admin=True).first()
        if oldadminuser:
            oldadminuser.admin = False
            db.session.add(oldadminuser)

    # Create or update global BC user
    user = User.query.filter_by(bc_id=bc_user_id).first()
    if user is None:
        user = User(bc_user_id, email)
        db.session.add(user)
    elif user.email != email:
        user.email = email
        db.session.add(user)

    # Create or update store user
    storeuser = StoreUser.query.filter_by(user_id=user.id,
                                          store_id=store.id).first()
    if not storeuser:
        storeuser = StoreUser(store, user, admin=True)
    else:
        storeuser.admin = True
    db.session.add(storeuser)
    db.session.commit()

    # Log user in and redirect to app home
    flask.session['storeuserid'] = storeuser.id
    return flask.redirect(app.config['APP_URL'])
def auth_callback():
    # Put together params for token request
    code = flask.request.args['code']
    context = flask.request.args['context']
    scope = flask.request.args['scope']
    store_hash = context.split('/')[1]
    redirect = app.config['APP_URL'] + flask.url_for('auth_callback')

    # Fetch a permanent oauth token. This will throw an exception on error,
    # which will get caught by our error handler above.
    client = BigcommerceApi(client_id=client_id(), store_hash=store_hash)
    token = client.oauth_fetch_token(client_secret(), code, context, scope, redirect)
    bc_user_id = token['user']['id']
    email = token['user']['email']
    access_token = token['access_token']

    # Create or update store
    store = Store.query.filter_by(store_hash=store_hash).first()
    if store is None:
        store = Store(store_hash, access_token, scope)
        db.session.add(store)
        db.session.commit()
    else:
        store.access_token = access_token
        store.scope = scope
        db.session.add(store)
        db.session.commit()
        # If the app was installed before, make sure the old admin user is no longer marked as the admin
        oldadminuser = StoreUser.query.filter_by(store_id=store.id, admin=True).first()
        if oldadminuser:
            oldadminuser.admin = False
            db.session.add(oldadminuser)

    # Create or update global BC user
    user = User.query.filter_by(bc_id=bc_user_id).first()
    if user is None:
        user = User(bc_user_id, email)
        db.session.add(user)
    elif user.email != email:
        user.email = email
        db.session.add(user)

    # Create or update store user
    storeuser = StoreUser.query.filter_by(user_id=user.id, store_id=store.id).first()
    if not storeuser:
        storeuser = StoreUser(store, user, admin=True)
    else:
        storeuser.admin = True
    db.session.add(storeuser)
    db.session.commit()

    # Log user in and redirect to app home
    flask.session['storeuserid'] = storeuser.id
    return flask.redirect(app.config['APP_URL'])
Пример #3
0
def index():
    # Lookup user
    storeuser = StoreUser.query.filter_by(
        id=flask.session['storeuserid']).first()
    if storeuser is None:
        return "Not logged in!", 401
    store = storeuser.store
    user = storeuser.user

    # Construct api client
    client = BigcommerceApi(client_id=client_id(),
                            store_hash=store.store_hash,
                            access_token=store.access_token)

    # Fetch a few products
    products = client.Products.all(limit=10)

    # Render page
    context = dict()
    context['products'] = products
    context['user'] = user
    context['store'] = store
    context['client_id'] = client_id()
    context['api_url'] = client.connection.host
    return render('index.html', context)
Пример #4
0
def load():
    # Decode and verify payload
    payload = flask.request.args['signed_payload']
    user_data = BigcommerceApi.oauth_verify_payload(payload, client_secret())
    if user_data is False:
        return "Payload verification failed!", 401

    bc_user_id = user_data['user']['id']
    email = user_data['user']['email']
    store_hash = user_data['store_hash']

    # Lookup store
    store = Store.query.filter_by(store_hash=store_hash).first()
    if store is None:
        return "Store not found!", 401

    # Lookup user and create if doesn't exist (this can happen if you enable multi-user
    # when registering your app)
    user = User.query.filter_by(bc_id=bc_user_id).first()
    if user is None:
        user = User(bc_user_id, email)
        db.session.add(user)
        db.session.commit()
    storeuser = StoreUser.query.filter_by(user_id=user.id,
                                          store_id=store.id).first()
    if storeuser is None:
        storeuser = StoreUser(store, user)
        db.session.add(storeuser)
        db.session.commit()

    # Log user in and redirect to app interface
    flask.session['storeuserid'] = storeuser.id
    return flask.redirect(app.config['APP_URL'])
Пример #5
0
def load():
    # Decode and verify payload
    payload = flask.request.args['signed_payload']
    user_data = BigcommerceApi.oauth_verify_payload(payload, client_secret())
    if user_data is False:
        return "Payload verification failed!", 401

    bc_user_id = user_data['user']['id']
    email = user_data['user']['email']
    store_hash = user_data['store_hash']

    # Lookup store
    store = Store.query.filter_by(store_hash=store_hash).first()
    if store is None:
        return "Store not found!", 401

    # Lookup user and create if doesn't exist (this can happen if you enable multi-user
    # when registering your app)
    user = User.query.filter_by(bc_id=bc_user_id).first()
    if user is None:
        user = User(bc_user_id, email, store)
        db.session.add(user)
        db.session.commit()

    # Log user in and redirect to app interface
    flask.session['userid'] = user.id
    return flask.redirect(flask.url_for('index'))
Пример #6
0
def auth_callback():
    # Put together params for token request
    code = flask.request.args['code']
    context = flask.request.args['context']
    scope = flask.request.args['scope']
    store_hash = context.split('/')[1]
    redirect = app.config['APP_URL'] + flask.url_for('auth_callback')

    # Fetch a permanent oauth token. This will throw an exception on error,
    # which will get caught by our error handler above.
    client = BigcommerceApi(client_id=client_id(), store_hash=store_hash)
    token = client.oauth_fetch_token(client_secret(), code, context, scope,
                                     redirect)
    bc_user_id = token['user']['id']
    email = token['user']['email']
    access_token = token['access_token']

    # Create or update store
    store = Store.query.filter_by(store_hash=store_hash).first()
    if store is None:
        store = Store(store_hash, access_token)
    else:
        store.access_token = access_token

    db.session.add(store)
    db.session.commit()

    # Create or update user
    user = User.query.filter_by(bc_id=bc_user_id).first()
    if user is None:
        user = User(bc_user_id, email, store, True)
    else:
        user.email = email
        user.store = store
        user.admin = True

    db.session.add(user)
    db.session.commit()

    # Log user in and redirect to app home
    flask.session['userid'] = user.id
    return flask.redirect(flask.url_for('index'))
Пример #7
0
def auth_callback():
    # Put together params for token request
    code = flask.request.args['code']
    context = flask.request.args['context']
    scope = flask.request.args['scope']
    store_hash = context.split('/')[1]
    redirect = app.config['APP_URL'] + flask.url_for('auth_callback')

    # Fetch a permanent oauth token. This will throw an exception on error,
    # which will get caught by our error handler above.
    client = BigcommerceApi(client_id=client_id(), store_hash=store_hash)
    token = client.oauth_fetch_token(client_secret(), code, context, scope, redirect)
    bc_user_id = token['user']['id']
    email = token['user']['email']
    access_token = token['access_token']

    # Create or update store
    store = Store.query.filter_by(store_hash=store_hash).first()
    if store is None:
        store = Store(store_hash, access_token)
    else:
        store.access_token = access_token

    db.session.add(store)
    db.session.commit()

    # Create or update user
    user = User.query.filter_by(bc_id=bc_user_id).first()
    if user is None:
        user = User(bc_user_id, email, store, True)
    else:
        user.email = email
        user.store = store
        user.admin = True

    db.session.add(user)
    db.session.commit()

    # Log user in and redirect to app home
    flask.session['userid'] = user.id
    return flask.redirect(flask.url_for('index'))
Пример #8
0
    def validate_basic_auth(self):

        host = self.host
        token = self.token
        app_name = self.app_name
        basic_auth = (app_name, token)

        if not host or not token or not app_name:
            raise BcommerceSetupError(_("Invalid credentials"))
        try:
            api = BigcommerceApi(host, basic_auth=basic_auth)
            store = api.Store.all()
            sync_store(store, False, self)
            frappe.msgprint(
                _("Success! You're using Basic Authorization Method"))
        except BcommerceSetupError, e:
            throw(_(e.message))
Пример #9
0
    def validate_oauth(self):

        if not self.client_id or not self.access_token or not self.store_hash:
            throw(
                _("Client ID, Client Secret and Access Token, all the mandatory field"
                  ))

        try:
            api = BigcommerceApi(client_id=self.client_id,
                                 access_token=self.access_token,
                                 store_hash=self.store_hash)
            store = api.Store.all()
            sync_store(store, False, self)

            frappe.msgprint(
                _("Success!  You're using OAuth Authorization Method"))

        except Exception as e:
            throw(_(e.message))
Пример #10
0
def remove_user():
    # Decode and verify payload
    payload = flask.request.args['signed_payload']
    user_data = BigcommerceApi.oauth_verify_payload(payload, client_secret())
    if user_data is False:
        return "Payload verification failed!", 401

    # Lookup store
    store_hash = user_data['store_hash']
    store = Store.query.filter_by(store_hash=store_hash).first()
    if store is None:
        return "Store not found!", 401

    # Lookup user and delete it
    bc_user_id = user_data['user']['id']
    user = User.query.filter_by(bc_id=bc_user_id).first()
    if user is not None:
        db.session.delete(user)
        db.session.commit()

    return flask.Response('Deleted', status=204)
Пример #11
0
def uninstall():
    # Decode and verify payload
    payload = flask.request.args['signed_payload']
    user_data = BigcommerceApi.oauth_verify_payload(payload, client_secret())
    if user_data is False:
        return "Payload verification failed!", 401

    # Lookup store
    store_hash = user_data['store_hash']
    store = Store.query.filter_by(store_hash=store_hash).first()
    if store is None:
        return "Store not found!", 401

    # Clean up: delete store associated users. This logic is up to you.
    # You may decide to keep these records around in case the user installs
    # your app again.
    User.query.filter_by(store_id=store.id).delete()
    db.session.delete(store)
    db.session.commit()

    return flask.Response('Deleted', status=204)
Пример #12
0
def remove_user():
    # Decode and verify payload
    payload = flask.request.args['signed_payload']
    user_data = BigcommerceApi.oauth_verify_payload(payload, client_secret())
    if user_data is False:
        return "Payload verification failed!", 401

    # Lookup store
    store_hash = user_data['store_hash']
    store = Store.query.filter_by(store_hash=store_hash).first()
    if store is None:
        return "Store not found!", 401

    # Lookup user and delete it
    bc_user_id = user_data['user']['id']
    user = User.query.filter_by(bc_id=bc_user_id).first()
    if user is not None:
        db.session.delete(user)
        db.session.commit()

    return flask.Response('Deleted', status=204)
Пример #13
0
def uninstall():
    # Decode and verify payload
    payload = flask.request.args['signed_payload']
    user_data = BigcommerceApi.oauth_verify_payload(payload, client_secret())
    if user_data is False:
        return "Payload verification failed!", 401

    # Lookup store
    store_hash = user_data['store_hash']
    store = Store.query.filter_by(store_hash=store_hash).first()
    if store is None:
        return "Store not found!", 401

    # Clean up: delete store associated users. This logic is up to you.
    # You may decide to keep these records around in case the user installs
    # your app again.
    User.query.filter_by(store_id=store.id).delete()
    db.session.delete(store)
    db.session.commit()

    return flask.Response('Deleted', status=204)
Пример #14
0
    def get(self, request):
        payload = request.GET['signed_payload']
        print("payload========>", payload)
        user_data = BigcommerceApi.oauth_verify_payload(
            payload, settings.APP_CLIENT_SECRET)
        print("userdata======>", user_data)
        if user_data is False:
            return "Payload verification failed!"

        bc_user_id = user_data['user']['id']
        print("bc id=========>", bc_user_id)
        email = user_data['user']['email']
        print("email =========>", email)
        store_hash = user_data['store_hash']
        print("store has=========>", store_hash)

        store = Store.objects.filter(store_hash=store_hash).first()
        if store is None:
            return "Store not found!"

        user = User.objects.filter(bc_id=bc_user_id).first()
        if user is None:
            user = User.objects.create(
                bc_id=bc_user_id,
                email=email,
            )
            print("============>>Create new user")

        storeuser = StoreUser.objects.filter(user_id=user.id,
                                             store_id=store.id).first()
        if storeuser is None:
            storeuser = StoreUser.objects.create(
                store_id=store,
                user_id=user,
            )
            print("============>>Create new userstore")

        print("====>Load redirect APP_URL", settings.APP_URL)
        return HttpResponseRedirect(settings.APP_URL)
Пример #15
0
    def get(self, request):
        code = request.GET['code']
        print("code=====> ", code)
        context = request.GET['context']
        print("context=====> ", context)
        scope = request.GET['scope']
        print("scope=====> ", scope)
        store_hash = context.split('/')[1]
        print("store has=====> ", store_hash)
        redirect = settings.APP_URL + 'bigcommerce/callback'
        print("redirect=====> ", redirect)
        client = BigcommerceApi(client_id=settings.APP_CLIENT_ID,
                                store_hash=store_hash)
        token = client.oauth_fetch_token(settings.APP_CLIENT_SECRET, code,
                                         context, scope, redirect)
        bc_user_id = token['user']['id']
        email = token['user']['email']
        print("email===>", email)
        access_token = token['access_token']
        print("access_tocken====>", access_token)

        store = Store.objects.filter(store_hash=store_hash).first()
        if store is None:
            store = Store.objects.create(
                store_hash=store_hash,
                access_token=access_token,
                scope=scope,
            )
            print("============>>Create new store")
        else:
            Store.objects.update(
                access_token=access_token,
                scope=scope,
            )
            print("============>>Update new store")

        user = User.objects.filter(bc_id=bc_user_id).first()
        if user is None:
            user = User.objects.create(
                bc_id=bc_user_id,
                email=email,
            )
            print("============>>Create new user")
        elif user.email != email:
            User.update(email=email, )
            print("============>>update new user")

        storeuser = StoreUser.objects.filter(
            user_id=user.id,
            store_id=store.id,
        ).first()

        if not storeuser:
            storeuser = StoreUser.objects.create(
                store_id=store,
                user_id=user,
                admin=True,
            )
            print("============>>Create new storeuser")
        else:
            StoreUser.objects.update(admin=True)
            print("============>>Update new storeuser")

        print("====>Auth redirect APP_URL", settings.APP_URL)
        return HttpResponseRedirect(settings.APP_URL)
Пример #16
0
def order_placed():
    print("REQUEST RULE::")
    print(flask.request.url_rule)

    # Lookup user
    data = flask.request.get_json()
    order_data = data['data']

    store_hash = "4atxht2sgv"
    store = db.session.query(Store).filter_by(store_hash=store_hash).first()
    # for key, value in data.items():

    # Construct api client
    client = BigcommerceApi(client_id=client_id(),
                            store_hash=store_hash,
                            access_token=store.access_token)

    # Fetch a few orders
    order = client.Orders.get(order_data['id'])
    customer = client.Customers.get(order['customer_id'])
    print(order)
    print(customer)
    order_products = client.OrderProducts.all(parentid=order['id'])  # todo: iterate
    order_shipping_address = client.OrderShippingAddresses.all(parentid=order['id'])[0]
    print(order_products)
    print(order_shipping_address)

    billing_address = order['billing_address']
    datetime_created = datetime.strptime(order['date_created'], '%a, %d %b %Y %X +%f')
    order_date = datetime_created.strftime('%Y%m%d')
    order_due = (datetime_created + timedelta(days=1)).strftime('%Y%m%d')

    # todo: mapper un sku à une table

    sl_values_array = []

    line_number = 1
    for product in order_products:
        billing_address_street = ' '.join([billing_address['street_1'], billing_address['street_2']])
        shipping_address_street = ' '.join([order_shipping_address['street_1'], order_shipping_address['street_2']])

        sl_values = [
            "BeerMyGuest",
            "Logistique",
            str(order['id']),
            order_date,
            order_due,
            (billing_address['last_name'] + ' ' + billing_address['first_name'])[:20],
            billing_address['company'][:40] if len(billing_address['company']) > 0 else "particulier",
            billing_address_street[:20],
            billing_address_street[20:40],
            billing_address_street[40:60],
            str(billing_address['zip'])[:15],
            billing_address['city'][:40],
            billing_address['state'][:40],
            billing_address['country'][:40],
            (billing_address['last_name'] + ' ' + billing_address['first_name'])[:40],
            str(billing_address['phone'])[:25],
            '',
            billing_address['email'][:100],
            (order_shipping_address['last_name'] + ' ' + order_shipping_address['first_name'])[:20],
            order_shipping_address['company'][:40] if len(order_shipping_address['company']) > 0 else "particulier",
            shipping_address_street[:20],
            shipping_address_street[20:40],
            shipping_address_street[40:60],
            str(order_shipping_address['zip'])[:15],
            order_shipping_address['city'][:40],
            order_shipping_address['state'][:40],
            order_shipping_address['country'][:40],
            (order_shipping_address['last_name'] + ' ' + order_shipping_address['first_name'])[:40],
            str(order_shipping_address['phone'])[:25],
            '',
            order_shipping_address['email'][:100],
            'DPD',
            'PREDICT',
            order['customer_message'][:100],
            str(line_number),  # str(product['order_address_id'])[:20],
            str(product['sku'])[:20],
            str(product['quantity'])[:5],
            '',  # unavailable in bigcommerce
            'BigCommerce'
        ]
        sl_values_array.append(sl_values)
        line_number = line_number + 1

    keys_string = '\t'.join(sl_keys())
    values_strings_array = map(lambda values: '\t'.join(values), sl_values_array)
    values_string = '\n'.join(values_strings_array)

    file_data = '\n'.join([keys_string, values_string])

    print(file_data)

    # send emails
    server = smtplib.SMTP('mail.infomaniak.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login("*****@*****.**", "Premium_Beer_2018")

    send_from = "*****@*****.**"
    send_to = ['*****@*****.**']

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = "[StarLogistiqueManager] New Order " + str(order['id'])

    attachment_filename = "PREPBEERMYGUEST" + datetime_created.strftime('%Y%m%d%H%M') + ".txt"
    msg.attach(MIMEText("Veuillez trouver ci-joint la commande BeerMyGuest #" + str(order['id']) + " à traiter."))

    part = MIMEApplication(
       file_data,
       Name=attachment_filename
    )
    part['Content-Disposition'] = 'attachment; filename="%s"' % attachment_filename
    msg.attach(part)

    server.sendmail(send_from, send_to, msg.as_string())
    server.close()

    #  todo: fix double call
    return flask.Response('OK', status=200)
Пример #17
0
def get_bc_client(user, config):
    bc_client = BigcommerceApi(client_id=get_bc_client_id(config),
                               store_hash=user.bc_store_hash,
                               access_token=user.bc_access_token)

    return bc_client