def create(self, form, bank_account_form): listing_id = form.listing_id.data email = form.email.data name = form.name.data merchant_data = form.data.copy() password = merchant_data.pop('password', None) month = merchant_data.pop('dob_month') year = merchant_data.pop('dob_year') merchant_data['dob_month'] = month merchant_data['dob_year'] = year merchant_data.pop('listing_id') if not merchant_data.get('email', None): merchant_data.pop('email', None) if request.user.is_authenticated: user = request.user else: user = User.create_guest_user(email, name, password) # do this password check as a guest user should not be able to take # over an existing account without authentication # flush to ensure password gets hashed Session.flush() if user.has_password and not user.check_password(password): raise Exception('Password mismatch') if not user.account_href: self.create_balanced_customer(user, merchant_data=merchant_data) else: user.add_merchant(merchant_data) if bank_account_form.bank_account_href.data: bank_account = balanced.BankAccount.fetch( bank_account_form.bank_account_href.data) bank_account.associate_to_customer(user.balanced_customer.href) return listing_id
def verify(): # user cancelled out of authentication process if 'email_address' not in request.args: return redirect('/') email_address = request.args['email_address'] listing_id = request.args['listing_id'] merchant_uri = request.args['merchant_uri'] marketplace = balanced.Marketplace.my_marketplace try: account = marketplace.create_merchant(email_address=email_address, merchant_uri=merchant_uri) except balanced.exc.HTTPError as ex: # shit, that sucked if getattr(ex, 'category_code', None) == 'duplicate-email-address': account = marketplace.accounts.filter( email_address=email_address).one() else: raise if account: user = User.create_guest_user(email_address=email_address) user.associate_balanced_account(account.uri) Session.commit() session['email_address'] = email_address return redirect(url_for('listing.complete', listing=listing_id))
def create(self, form, bank_account_form): listing_id = form.listing_id.data email_address = form.email_address.data name = form.name.data merchant_data = form.data.copy() password = merchant_data.pop('password', None) month = merchant_data.pop('date_of_birth_month') year = merchant_data.pop('date_of_birth_year') merchant_data['dob'] = '{}-{}'.format(year, month) merchant_data.pop('listing_id') if not merchant_data.get('email_address', None): merchant_data.pop('email_address', None) if request.user.is_authenticated: user = request.user else: user = User.create_guest_user(email_address, name, password) # do this password check as a guest user should not be able to take # over an existing account without authentication # flush to ensure password gets hashed Session.flush() if user.has_password and not user.check_password(password): raise Exception('Password mismatch') if not user.account_uri: self.create_balanced_account(user, merchant_data=merchant_data) else: user.add_merchant(merchant_data) if bank_account_form.bank_account_uri.data: user.balanced_account.add_bank_account( bank_account_form.bank_account_uri.data) return listing_id
def create(self, form, bank_account_form): listing_id = form.listing_id.data email = form.email.data name = form.name.data merchant_data = form.data.copy() password = merchant_data.pop("password", None) month = merchant_data.pop("dob_month") year = merchant_data.pop("dob_year") merchant_data["dob_month"] = month merchant_data["dob_year"] = year merchant_data.pop("listing_id") if not merchant_data.get("email", None): merchant_data.pop("email", None) if request.user.is_authenticated: user = request.user else: user = User.create_guest_user(email, name, password) # do this password check as a guest user should not be able to take # over an existing account without authentication # flush to ensure password gets hashed Session.flush() if user.has_password and not user.check_password(password): raise Exception("Password mismatch") if not user.account_href: self.create_balanced_customer(user, merchant_data=merchant_data) else: user.add_merchant(merchant_data) if bank_account_form.bank_account_href.data: bank_account = balanced.BankAccount.fetch(bank_account_form.bank_account_href.data) bank_account.associate_to_customer(user.balanced_customer.href) return listing_id
def index(): account_href = request.user.account_href if not account_href: try: account = balanced.Customer.query.filter( email=self.request.user.email).one() except balanced.exc.NoResultFound: return redirect( url_for('accounts.index', reason='no-balanced-account')) else: request.user.account_href = account_href = account.href Session.commit() # let's create a login token for this user token_uri = 'https://dashboard.balancedpayments.com/v1/logins' data = { 'account_href': account_href, 'redirect_uri': config['DOMAIN_URI'], } result = requests.post(token_uri, data=json.dumps(data), auth=HTTPBasicAuth(balanced.config.api_key_secret, ''), headers={'content-type': 'application/json'}) data = json.loads(result.content) return 'transactions/interstitial.mako', { 'redirect_to': data['token_uri'], }
def verify(): # user cancelled out of authentication process if 'email' not in request.args: return redirect('/') email = request.args['email'] listing_id = request.args['listing_id'] merchant_href = request.args['merchant_href'] marketplace = balanced.Marketplace.my_marketplace try: account = balanced.Customer( email=email, merchant_href=merchant_href).save() except balanced.exc.HTTPError as ex: # shit, that sucked if getattr(ex, 'category_code', None) == 'duplicate-email-address': account = marketplace.accounts.filter( email=email).one() else: raise if account: user = User.create_guest_user(email=email) user.associate_balanced_customer(account.href) Session.commit() session['email'] = email return redirect(url_for('listing.complete', listing=listing_id))
def index(): account_uri = request.user.account_uri if not account_uri: try: account = balanced.Account.query.filter( email_address=self.request.user.email_address).one() except balanced.exc.NoResultFound: return redirect(url_for('accounts.index', reason='no-balanced-account')) else: request.user.account_uri = account_uri = account.uri Session.commit() # let's create a login token for this user token_uri = 'https://dashboard.balancedpayments.com/v1/logins' data = { 'account_uri': account_uri, 'redirect_uri': config['DOMAIN_URI'], } result = requests.post(token_uri, data=json.dumps(data), auth=HTTPBasicAuth(balanced.config.api_key_secret, ''), headers={'content-type': 'application/json'}) data = json.loads(result.content) return 'transactions/interstitial.mako', { 'redirect_to': data['token_uri'], }
def create(**kwargs): manager = ListingManager(request) forms = kwargs.pop("forms") listing_form = find_form(forms, ListingForm) guest_listing_form = find_form(forms, GuestListingForm) bank_account_form = find_form(forms, BankAccountForm) if request.user.is_authenticated: form = listing_form else: form = guest_listing_form session["email"] = form.email.data if not form.validate(): return index(**kwargs) try: listing_id = manager.create(form, bank_account_form) except balanced.exc.HTTPError as ex: if ex.status_code == 300: # we've created the user locally, persist this information Session.commit() return redirect( url_for( "redirect.show", listing=form.listing_id.data, redirect_uri=ex.response.headers["location"], email=session.get("email"), ) ) elif ex.status_code == 400: if "merchant.postal_code" in ex.description: form["postal_code"].errors.append(ex.description) return index(**kwargs) elif "merchant.phone" in ex.description: form["phone"].errors.append(ex.description) return index(**kwargs) raise except Exception as ex: if ex.message == "Password mismatch": flash( "Sorry, this email address is already assigned to an " "account and your password does not match, please try " "again.", "error", ) return self.index(**kwargs) raise Session.commit() return redirect(url_for("listing.complete", listing=listing_id))
def rent_to(self, user, card_href=None): # Fetch the buyer buyer = user.balanced_customer # Fetch the buyers card to debit if card_href: card = balanced.Card.fetch(card_href) else: if not buyer.cards.count(): raise Exception('No card on file') if not user.has_password: raise Exception('Anonymous users must specify a card') else: card = buyer.cards.first() # Fetch the merchant owner_user = User.query.get(self.owner_guid) owner = owner_user.balanced_customer # create an Order order = owner.create_order(desciption=self.bike_type) # debit the buyer for the amount of the listing debit = order.debit_from( source=card, amount=(self.price * 100), appears_on_statement_as=self.bike_type, ) # credit the owner of bicycle for the amount of listing # # since this is an example, we're showing how to issue a credit # immediately. normally you should wait for order fulfillment # before crediting. # First, fetch the onwer's bank account to credit bank_account = owner.bank_accounts.first() if not bank_account: raise Exception('No bank account on file') bank_account.credit( amount=(self.price * 100) ) order.credit_to( destination=bank_account, amount=(self.price * 100), ) rental = Rental(buyer_guid=user.guid, order_href=order.href, listing_guid=self.id, owner_guid=owner_user.guid) Session.add(rental) return rental
def rent_to(self, user, card_href=None): # Fetch the buyer buyer = user.balanced_customer # Fetch the buyers card to debit if card_href: card = balanced.Card.fetch(card_href) else: if not buyer.cards.count(): raise Exception('No card on file') if not user.has_password: raise Exception('Anonymous users must specify a card') else: card = buyer.cards.first() # Fetch the merchant owner_user = User.query.get(self.owner_guid) owner = owner_user.balanced_customer # create an Order order = owner.create_order(desciption=self.bike_type) # debit the buyer for the amount of the listing debit = order.debit_from( source=card, amount=(self.price * 100), appears_on_statement_as=self.bike_type, ) # credit the owner of bicycle for the amount of listing # # since this is an example, we're showing how to issue a credit # immediately. normally you should wait for order fulfillment # before crediting. # First, fetch the onwer's bank account to credit bank_account = owner.bank_accounts.first() if not bank_account: raise Exception('No bank account on file') bank_account.credit(amount=(self.price * 100)) order.credit_to( destination=bank_account, amount=(self.price * 100), ) rental = Rental(buyer_guid=user.guid, order_href=order.href, listing_guid=self.id, owner_guid=owner_user.guid) Session.add(rental) return rental
def _associate_email_and_account(self, email_address, account_uri): if request.user.is_authenticated: user = request.user else: # we're creating an account as they list, create a guest user. user = User.create_guest_user(email_address) # flush to db, to force guid creation as we're about to log them # in. Session.flush() session['user_guid'] = user.guid user.associate_account_uri(account_uri) return user
def create(**kwargs): manager = ListingManager(request) forms = kwargs.pop('forms') listing_form = find_form(forms, ListingForm) guest_listing_form = find_form(forms, GuestListingForm) bank_account_form = find_form(forms, BankAccountForm) if request.user.is_authenticated: form = listing_form else: form = guest_listing_form session['email_address'] = form.email_address.data if not form.validate(): return index(**kwargs) try: listing_id = manager.create(form, bank_account_form) except balanced.exc.HTTPError as ex: if ex.status_code == 300: # we've created the user locally, persist this information Session.commit() return redirect( url_for('redirect.show', listing=form.listing_id.data, redirect_uri=ex.response.headers['location'], email_address=session.get('email_address'))) elif ex.status_code == 400: if 'merchant.postal_code' in ex.description: form['postal_code'].errors.append(ex.description) return index(**kwargs) elif 'merchant.phone_number' in ex.description: form['phone_number'].errors.append(ex.description) return index(**kwargs) raise except Exception as ex: if ex.message == 'Password mismatch': flash( 'Sorry, this email address is already assigned to an ' 'account and your password does not match, please try ' 'again.', 'error') return self.index(**kwargs) raise Session.commit() return redirect(url_for('listing.complete', listing=listing_id))
def error_handler(self, ex): try: Session.rollback() except InterfaceError as ex: if not ex.connection_invalidated: logger.exception(ex) raise logger.exception(ex) ex_type = sys.exc_info()[0] ex_tb = sys.exc_info()[2] fmt_tb = traceback.format_exception(ex_type, ex, ex_tb) encoded_tb = [unicode(l, 'utf-8') for l in fmt_tb] tb = ''.join(encoded_tb) ex.traceback = tb response = render('error.mako', request, exception=ex, status_code=500) return response
def create(**kwargs): manager = ListingManager(request) forms = kwargs.pop('forms') listing_form = find_form(forms, ListingForm) guest_listing_form = find_form(forms, GuestListingForm) bank_account_form = find_form(forms, BankAccountForm) if request.user.is_authenticated: form = listing_form else: form = guest_listing_form session['email_address'] = form.email_address.data if not form.validate(): return index(**kwargs) try: listing_id = manager.create(form, bank_account_form) except balanced.exc.HTTPError as ex: if ex.status_code == 300: # we've created the user locally, persist this information Session.commit() return redirect(url_for('redirect.show', listing=form.listing_id.data, redirect_uri=ex.response.headers['location'], email_address=session.get('email_address'))) elif ex.status_code == 400: if 'merchant.postal_code' in ex.description: form['postal_code'].errors.append(ex.description) return index(**kwargs) elif 'merchant.phone_number' in ex.description: form['phone_number'].errors.append(ex.description) return index(**kwargs) raise except Exception as ex: if ex.message == 'Password mismatch': flash('Sorry, this email address is already assigned to an ' 'account and your password does not match, please try ' 'again.', 'error') return self.index(**kwargs) raise Session.commit() return redirect(url_for('listing.complete', listing=listing_id))
def session_cleanup(self, ex): try: Session.rollback() Session.expunge_all() Session.remove() except InterfaceError as ex: if not ex.connection_invalidated: logger.exception(ex) raise Session.close()
def login(**kwargs): login_form = kwargs.pop("forms")[0] if login_form.validate(): try: user = login_form.login() except Exception as ex: if ex.message == "No password": flash("There is no password associated with this account.") return index(login_form) raise if not user: flash("Wrong email address or password", "error") return login_show(login_form) user.lookup_balanced_account() Session.commit() session["user_guid"] = user.guid return redirect(request.args.get("redirect_uri", url_for("accounts.index"))) return login_show(login_form)
def rent_to(self, user, card_uri=None): account = user.balanced_account if not card_uri: if not account.cards.count(): raise Exception('No card on file') if not user.has_password: raise Exception('Anonymous users must specify a card') # this will throw balanced.exc.HTTPError if it fails debit = account.hold(self.price * 100, source_uri=card_uri) rental = Rental(buyer_guid=user.guid, debit_uri=debit.uri, bike_guid=self.id) Session.add(rental) return rental
def login(**kwargs): login_form = kwargs.pop('forms')[0] if login_form.validate(): try: user = login_form.login() except Exception as ex: if ex.message == 'No password': flash('There is no password associated with this account.') return index(login_form) raise if not user: flash('Wrong email address or password', 'error') return login_show(login_form) user.lookup_balanced_customer() Session.commit() session['user_guid'] = user.guid return redirect( request.args.get('redirect_uri', url_for('accounts.index'))) return login_show(login_form)
def login(**kwargs): login_form = kwargs.pop('forms')[0] if login_form.validate(): try: user = login_form.login() except Exception as ex: if ex.message == 'No password': flash('There is no password associated with this account.') return index(login_form) raise if not user: flash('Wrong email address or password', 'error') return login_show(login_form) user.lookup_balanced_customer() Session.commit() session['user_guid'] = user.guid return redirect(request.args.get('redirect_uri', url_for('accounts.index')) ) return login_show(login_form)
def update(listing, **kwargs): manager = RentalManager(request) forms = kwargs.pop('forms') purchase_form = find_form(forms, PurchaseForm) guest_purchase_form = find_form(forms, GuestPurchaseForm) card_href = request.form.get('card_href', None) name = None if request.user.is_authenticated: email_address = request.user.email else: email_address = guest_purchase_form.email.data name = guest_purchase_form.name.data try: rental = manager.rent(listing, email_address, card_href, name) except balanced.exc.HTTPError as ex: msg = 'Error debiting account, your card has not been charged "{}"' flash(msg.format(ex.message), 'error') Session.rollback() except Exception as ex: if ex.message == 'No card on file': return show(listing, purchase_form, guest_purchase_form, True) raise else: Session.commit() email.send_email(rental.buyer.email, 'Rental Receipt', 'receipt.mako', name=rental.buyer.email, listing=listing, charge=balanced.Order.fetch(rental.order_href)) session['rental_user_guid'] = rental.buyer.guid session['rental_email'] = rental.buyer.email return redirect( url_for('rent.confirmed', listing=listing, rental=rental)) return show(listing, purchase_form, guest_purchase_form)
def update(listing, **kwargs): manager = RentalManager(request) forms = kwargs.pop('forms') purchase_form = find_form(forms, PurchaseForm) guest_purchase_form = find_form(forms, GuestPurchaseForm) card_uri = request.form.get('card_uri', None) name = None if request.user.is_authenticated: email_address = request.user.email_address else: email_address = guest_purchase_form.email_address.data name = guest_purchase_form.name.data try: rental = manager.rent(listing, email_address, card_uri, name) except balanced.exc.HTTPError as ex: msg = 'Error debiting account, your card has not been charged "{}"' flash(msg.format(ex.message), 'error') Session.rollback() except Exception as ex: if ex.message == 'No card on file': return show(listing, purchase_form, guest_purchase_form, True) raise else: Session.commit() email.send_email(rental.buyer.email_address, 'Rental Receipt', 'receipt.mako', name=rental.buyer.email_address, listing=listing, charge=balanced.Transaction.find(rental.debit_uri) ) session['rental_user_guid'] = rental.buyer.guid session['rental_email_address'] = rental.buyer.email_address return redirect(url_for('rent.confirmed', listing=listing, rental=rental)) return show(listing, purchase_form, guest_purchase_form)
def verify(): # user cancelled out of authentication process if "email_address" not in request.args: return redirect("/") email_address = request.args["email_address"] listing_id = request.args["listing_id"] merchant_uri = request.args["merchant_uri"] marketplace = balanced.Marketplace.my_marketplace try: account = marketplace.create_merchant(email_address=email_address, merchant_uri=merchant_uri) except balanced.exc.HTTPError as ex: # shit, that sucked if getattr(ex, "category_code", None) == "duplicate-email-address": account = marketplace.accounts.filter(email_address=email_address).one() else: raise if account: user = User.create_guest_user(email_address=email_address) user.associate_balanced_account(account.uri) Session.commit() session["email_address"] = email_address return redirect(url_for("listing.complete", listing=listing_id))
def create(**kwargs): account_form = kwargs.pop('forms')[0] if account_form.validate(): user = account_form.create_user() Session.add(user) try: Session.commit() except IntegrityError: flash('This account already exists!', 'warning') Session.rollback() else: user.lookup_balanced_customer() Session.commit() session['user_guid'] = user.guid return redirect(url_for('accounts.index')) return new(account_form)
def create(**kwargs): account_form = kwargs.pop("forms")[0] if account_form.validate(): user = account_form.create_user() Session.add(user) try: Session.commit() except IntegrityError: flash("This account already exists!", "warning") Session.rollback() else: user.lookup_balanced_account() Session.commit() session["user_guid"] = user.guid return redirect(url_for("accounts.index")) return new(account_form)
def add_dummy_data(self): for name, email, password in config['DEFAULT_USERS']: user = User.query.filter(User.email_address == email).count() if not user: user = User(name=name, email_address=email, password=password) Session.add(user) for i in range(4): listing = Listing.query.filter(Listing.id == i + 1).count() if not listing: listing = Listing(id=i + 1) Session.add(listing) Session.commit()
def add_dummy_data(self): user = User( name='Dummy User', email=self.dummy_email_generator(), password='******') Session.add(user) user.create_balanced_customer() for i in range(4): owner = User.fetch_one_at_random() if not user.balanced_customer.bank_accounts.count(): self.dummy_bank_account_generator(owner) listing = Listing.query.filter(Listing.id == i + 1).count() if not listing: listing = Listing(id=i + 1, owner_guid=owner.guid) Session.add(listing) Session.commit()
def rent(self, listing, email_address, card_uri, name=None): Session.flush() if request.user.is_authenticated: user = request.user else: user = User.create_guest_user(email_address, name) # this user has not authenticated with their email/password combo # we cannot allow them to charge an existing card if it exists if not card_uri: raise Exception('Non-authenticated user must supply card data') Session.flush() # ensure there is no db inconsistency if not user.account_uri: self.create_balanced_account(user, card_uri) else: if card_uri: user.add_card(card_uri) Session.flush() # ensure there is no db inconsistency return listing.rent_to(user, card_uri)
def rent(self, listing, email, card_href, name=None): Session.flush() if request.user.is_authenticated: user = request.user else: user = User.create_guest_user(email, name) # this user has not authenticated with their email/password combo # we cannot allow them to charge an existing card if it exists if not card_href: raise Exception('Non-authenticated user must supply card data') Session.flush() # ensure there is no db inconsistency if not user.account_href: self.create_balanced_customer(user, card_href) else: if card_href: user.add_card(card_href) Session.flush() # ensure there is no db inconsistency return listing.rent_to(user, card_href)
class Model(object): def __init__(self, **kwargs): """ Initializes a model by invoking the _declarative_constructor in SQLAlchemy. We do this for full control over construction of an object """ _declarative_constructor(self, **kwargs) def __repr__(self): try: cols = self.__mapper__.c.keys() class_name = self.__class__.__name__ items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col in cols]) return '%s(%s)' % (class_name, items) except Exception, ex: return 'poop' Base = declarative_base(cls=Model, constructor=None) Base.query = Session.query_property() if config['DB_URI']: Base.metadata.bind = db_engine from users import User from listings import Listing, Rental
def create_guest_user(email_address, name=None, password=None): try: user = User.query.filter( User.email_address == email_address).one() except NoResultFound: Session.flush() user = User(email_address=email_address, name=name, password=password) Session.add(user) try: Session.flush() except: Session.rollback() Session.commit() Session.add(user) Session.commit() return user
def __init__(self, password=None, **kwargs): if password: self.password_hash = generate_password_hash(password) self.has_password = True super(User, self).__init__(**kwargs) Session.add(self)
def create_guest_user(email_address, name=None, password=None): try: user = User.query.filter(User.email_address == email_address).one() except NoResultFound: Session.flush() user = User(email_address=email_address, name=name, password=password) Session.add(user) try: Session.flush() except: Session.rollback() Session.commit() Session.add(user) Session.commit() return user