def put_investment_agreement(agreement_id, agreement, admin_user): admin_app_user = create_app_user_by_email( admin_user.email(), get_config(NAMESPACE).rogerthat.app_id) # type: (long, InvestmentAgreement, users.User) -> InvestmentAgreement agreement_model = InvestmentAgreement.get_by_id( agreement_id) # type: InvestmentAgreement if not agreement_model: raise HttpNotFoundException('investment_agreement_not_found') if agreement_model.status == InvestmentAgreement.STATUS_CANCELED: raise HttpBadRequestException('order_canceled') if agreement.status not in (InvestmentAgreement.STATUS_SIGNED, InvestmentAgreement.STATUS_CANCELED): raise HttpBadRequestException('invalid_status') # Only support updating the status for now agreement_model.status = agreement.status if agreement_model.status == InvestmentAgreement.STATUS_CANCELED: agreement_model.cancel_time = now() elif agreement_model.status == InvestmentAgreement.STATUS_SIGNED: agreement_model.paid_time = now() if agreement.currency == 'BTC': _set_token_count(agreement_model, agreement.token_count_float) deferred.defer(_send_ito_agreement_to_admin, agreement_model.key, admin_app_user) agreement_model.put() return agreement_model
def validate_session(secret): session = Session.create_key(secret).get() if not session: return None, None if session.timeout < now(): session.key.delete() return None, None if session.timeout < now() + (SESSION_TIMEOUT / 2): deferred.defer(_update_session_timeout, secret) return session, session.user_id
def investment_agreement_signed(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag, result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params): try: user_detail = user_details[0] tag_dict = json.loads(tag) agreement = InvestmentAgreement.create_key(tag_dict['agreement_id']).get() # type: InvestmentAgreement last_step = steps[-1] assert isinstance(last_step, FormFlowStepTO) if last_step.answer_id != FormTO.POSITIVE: logging.info('Investment agreement was canceled') agreement.status = InvestmentAgreement.STATUS_CANCELED agreement.cancel_time = now() agreement.put() return None logging.info('Received signature for Investment Agreement') sign_result = last_step.form_result.result.get_value() assert isinstance(sign_result, SignWidgetResultTO) iyo_username = get_iyo_username(user_detail) sign_see_document(iyo_username, agreement.iyo_see_id, sign_result, user_detail) logging.debug('Storing signature in DB') agreement.populate(status=InvestmentAgreement.STATUS_SIGNED, signature=sign_result.payload_signature, sign_time=now()) agreement.put_async() deferred.defer(add_user_to_role, user_detail, RogerthatRoles.INVESTOR) intercom_tags = get_intercom_tags_for_investment(agreement) if intercom_tags: for i_tag in intercom_tags: deferred.defer(intercom_helpers.tag_intercom_users, i_tag, [iyo_username]) deferred.defer(update_investor_progress, user_detail.email, user_detail.app_id, INVESTMENT_TODO_MAPPING[agreement.status]) deferred.defer(_inform_support_of_new_investment, iyo_username, agreement.id, agreement.token_count_float) if needs_utility_bill(agreement): logging.debug('Sending "utility bill received" message') deferred.defer(_send_utility_bill_received, agreement.app_user) else: logging.debug('Sending confirmation message') deferred.defer(send_payment_instructions, agreement.app_user, agreement.id, '') deferred.defer(send_hoster_reminder, agreement.app_user, _countdown=1) result = FlowCallbackResultTypeTO(flow=FLOW_INVESTMENT_CONFIRMED, tag=None, force_language=None, flow_params=json.dumps({'reference': agreement.reference})) return FlowMemberResultCallbackResultTO(type=TYPE_FLOW, value=result) except: logging.exception('An unexpected error occurred') return create_error_message()
def put_node_order(order_id, order): # type: (long, NodeOrderTO) -> NodeOrder order_model = get_node_order(order_id) if order_model.status == NodeOrderStatus.CANCELED: raise HttpBadRequestException('order_canceled') if order.status not in (NodeOrderStatus.CANCELED, NodeOrderStatus.SENT, NodeOrderStatus.APPROVED, NodeOrderStatus.PAID): raise HttpBadRequestException('invalid_status') # Only support updating the status for now if order_model.status != order.status: if not _can_change_status(order_model.status, order.status): raise HttpBadRequestException( 'cannot_change_status', { 'from': order_model.status, 'to': order.status, 'allowed_new_statuses': _get_allowed_status( order_model.status) }) order_model.status = order.status human_user, app_id = get_app_user_tuple(order_model.app_user) if order_model.status == NodeOrderStatus.CANCELED: order_model.cancel_time = now() if order_model.odoo_sale_order_id: deferred.defer(update_odoo_quotation, order_model.odoo_sale_order_id, {'state': QuotationState.CANCEL.value}) deferred.defer(update_hoster_progress, human_user.email(), app_id, HosterSteps.NODE_POWERED) # nuke todo list deferred.defer(set_hoster_status_in_user_data, order_model.app_user, _countdown=2) elif order_model.status == NodeOrderStatus.SENT: if not order_model.odoo_sale_order_id or not get_nodes_from_odoo( order_model.odoo_sale_order_id): raise HttpBadRequestException( 'cannot_mark_sent_no_serial_number_configured_yet', {'sale_order': order_model.odoo_sale_order_id}) order_model.send_time = now() deferred.defer(update_hoster_progress, human_user.email(), app_id, HosterSteps.NODE_SENT) deferred.defer(_send_node_order_sent_message, order_id) elif order_model.status == NodeOrderStatus.APPROVED: deferred.defer(_create_node_order_pdf, order_id) elif order_model.status == NodeOrderStatus.PAID: deferred.defer(confirm_odoo_quotation, order_model.odoo_sale_order_id) else: logging.debug('Status was already %s, not doing anything', order_model.status) order_model.put() return order_model
def check_if_node_comes_online(order_key): order = order_key.get() # type: NodeOrder order_id = order.id if not order.odoo_sale_order_id: raise BusinessException( 'Cannot check status of node order without odoo_sale_order_id') node_id = get_node_id_from_odoo(order.odoo_sale_order_id) if not node_id: raise BusinessException( 'Could not find node id for sale order %s on odoo' % order_id) status = get_node_status(node_id) if status == u'running': logging.info('Marking node from node order %s as arrived', order_id) human_user, app_id = get_app_user_tuple(order.app_user) order.populate(arrival_time=now(), status=NodeOrderStatus.ARRIVED) order.put() deferred.defer(set_node_id_on_profile, order.app_user, node_id, _transactional=True) deferred.defer(update_hoster_progress, human_user.email(), app_id, HosterSteps.NODE_POWERED, _transactional=True) else: logging.info('Node from order %s is not online yet', order_id)
def trans(): agreement = InvestmentAgreement.create_key( tag_dict['agreement_id']).get() # type: InvestmentAgreement if answer_id != FormTO.POSITIVE: logging.info('Investment agreement sign aborted') return if agreement.status == InvestmentAgreement.STATUS_PAID: logging.warn( 'Ignoring request to set InvestmentAgreement %s as paid because it is already paid', agreement.id) return agreement.status = InvestmentAgreement.STATUS_PAID agreement.paid_time = now() agreement.put() user_email, app_id, = get_app_user_tuple(agreement.app_user) deferred.defer(transfer_genesis_coins_to_user, agreement.app_user, TokenType.I, long(agreement.token_count_float * 100), _transactional=True) deferred.defer(update_investor_progress, user_email.email(), app_id, INVESTMENT_TODO_MAPPING[agreement.status], _transactional=True) deferred.defer(_send_tokens_assigned_message, agreement.app_user, _transactional=True)
def trans(): node_order = get_node_order(order_id) if node_order.odoo_sale_order_id: update_odoo_quotation(node_order.odoo_sale_order_id, {'state': QuotationState.CANCEL.value}) node_order.populate(status=NodeOrderStatus.CANCELED, cancel_time=now()) node_order.put()
def trans_finish(): bh = ThreeFoldBlockHeight.get_block_height() if not bh.updating: return bh.timestamp = now() bh.updating = False bh.put()
def sync_wallet_for_user(app_user): wallet = ThreeFoldWallet.create_key(app_user).get() if not wallet: return now_ = now() next_unlock_timestamp = 0 for token in wallet.tokens: for t in ThreeFoldTransaction.list_with_amount_left_by_token( app_user, token): for unlock_timestamp in t.unlock_timestamps: if unlock_timestamp > now_: if not next_unlock_timestamp: next_unlock_timestamp = unlock_timestamp elif next_unlock_timestamp > unlock_timestamp: next_unlock_timestamp = unlock_timestamp wallet.next_unlock_timestamp = next_unlock_timestamp wallet.put() for token in wallet.tokens: deferred.defer(sync_payment_asset, app_user, get_asset_id_from_token(app_user, token), _countdown=5)
def _create_investment_agreement(amount, currency, token, token_count_float, username, version, app_user, **kwargs): tff_profile = get_tff_profile(username) if tff_profile.kyc.status != KYCStatus.VERIFIED: raise HttpBadRequestException('cannot_invest_not_kyc_verified') applicant = get_applicant(tff_profile.kyc.applicant_id) name = '%s %s ' % (applicant.first_name, applicant.last_name) address = '%s %s' % (applicant.addresses[0].street, applicant.addresses[0].building_number) address += '\n%s %s' % (applicant.addresses[0].postcode, applicant.addresses[0].town) country = filter(lambda c: c['value'] == applicant.addresses[0].country, country_choices)[0]['label'] address += '\n%s' % country precision = 2 reference = user_code(username) agreement = InvestmentAgreement(creation_time=now(), app_user=app_user, token=token, amount=amount, token_count=long(token_count_float * pow(10, precision)), token_precision=precision, currency=currency, name=name, address=address, version=version, reference=reference, **kwargs) return agreement
def trans(): logging.debug('Storing order in the database') order = NodeOrder(key=order_key, app_user=app_user, tos_iyo_see_id=None, billing_info=billing_info, shipping_info=shipping_info, order_time=now(), status=NodeOrderStatus.APPROVED if can_host else NodeOrderStatus.WAITING_APPROVAL, socket=socket) order.put() if can_host: logging.info( 'User has invested more than %s tokens, immediately creating node order PDF.', REQUIRED_TOKEN_COUNT_TO_HOST) deferred.defer(_create_node_order_pdf, order_key.id(), _transactional=True) else: logging.info( 'User has not invested more than %s tokens, an admin needs to approve this order manually.', REQUIRED_TOKEN_COUNT_TO_HOST) deferred.defer(_inform_support_of_new_node_order, order_key.id(), _transactional=True) deferred.defer(set_hoster_status_in_user_data, order.app_user, False, _transactional=True) if updated_user_data: deferred.defer(put_user_data, app_user, updated_user_data, _transactional=True)
def send_update(method, data=None, user_id=None): if not user_id: user_id = get_current_user_id() update_data = { 'method': method, 'data': data, 'ts': now() } send_firebase_update(user_id, update_data)
def create_session(user_id, scopes, jwt, secret=None): secret = secret or guid().replace('-', '') timeout = now() + SESSION_TIMEOUT session = Session(key=Session.create_key(secret), user_id=user_id, timeout=timeout, scopes=scopes, jwt=jwt) session.put() return secret, session
def get_spendable_amount_of_transaction(transaction): amount_spent = transaction.amount - transaction.amount_left unlocked_amount = 0 now_ = now() for unlock_timestamp, unlock_amount in zip(transaction.unlock_timestamps, transaction.unlock_amounts): if unlock_timestamp <= now_: unlocked_amount += unlock_amount return unlocked_amount - amount_spent
def _get_balance_from_transactions(transactions, token): # type: (list[ThreeFoldTransaction], unicode) -> WalletBalanceTO available_balance = 0 total_balance = 0 total_description_details = [] # TODO set to minimum precision of all transactions when transactions have the 'precision' property # (and multiply available / total amount depending on precision) precision = 2 # for transaction in transactions: # precision = max(transaction.precision, precision) for transaction in transactions: if transaction.token != token: raise BusinessException( 'Invalid transaction supplied to _get_balance_from_transactions. ' 'All transactions must have %s as token', token) amount_spent = transaction.amount - transaction.amount_left unlocked_amount = 0 now_ = now() for unlock_timestamp, unlock_amount in zip( transaction.unlock_timestamps, transaction.unlock_amounts): if unlock_timestamp <= now_: unlocked_amount += unlock_amount else: total_description_details.append( (unlock_timestamp, unlock_amount)) spendable_amount = unlocked_amount - amount_spent available_balance += spendable_amount total_balance += transaction.amount_left if total_description_details: total_description = u"""## %(token)s Unlock times' |Date|#%(token)s| |---|---:| """ % { 'token': token } for unlock_timestamp, unlock_amount in sorted( total_description_details, key=lambda tup: tup[0]): date = time.strftime('%a %d %b %Y %H:%M:%S GMT', time.localtime(unlock_timestamp)) amount = u'{:0,.2f}'.format(unlock_amount / 100.0) total_description += u'\n|%s|%s|' % (date, amount) else: total_description = None return WalletBalanceTO(available=available_balance, total=total_balance, description=total_description, token=token, precision=precision)
def _get_currency_conversions(currencies, dollar_value): # type: (list[CurrencyValueTO | CurrencyValue], int) -> list[CurrencyValue] currency_result = _get_current_currency_rates() result_list = [] invalid_currencies = [c.currency for c in currencies if c.currency not in currency_result] if invalid_currencies: raise HttpBadRequestException('invalid_currencies', {'currencies': invalid_currencies}) for currency in currencies: if currency.auto_update: value_of_one_usd = currency_result.get(currency.currency) currency.value = dollar_value / value_of_one_usd currency.timestamp = now() result_list.append(CurrencyValue(currency=currency.currency, value=currency.value, timestamp=currency.timestamp, auto_update=currency.auto_update)) return result_list
def _worker_locations(ul_key): ul = ul_key.get() now_ = now() tomorrow = now_ + 86400 if ul.next_collection > tomorrow: logging.error("broadcast collection message failed double run") return straat_naam = ul.address.rstrip("1234567890 ") collections = get_api_collections(ul.sik, straat_naam, ul.house_number, ul.house_bus, today()) names = [] for collection in collections: if now_ > collection.epoch: pass elif collection.epoch == ul.next_collection: if collection.activity.number in ul.notifications: names.append(collection.activity.name) elif collection.epoch > ul.next_collection: next_collection = collection.epoch break cd = datetime.datetime.fromtimestamp(ul.next_collection) d = format_date(cd, locale="nl_BE", format='d MMM') def trans(): user_location = ul_key.get() # user_data was more than 7 days old, update collections (maybe outdated) if now_ >= (user_location.user_data_epoch + 7 * 86400): user_location.user_data_epoch = now_ update_user_data(ul.sik, user_location.service_identity, user_location.email, user_location.app_id, user_location.address, user_location.notifications, collections) if names: message = translate_key(u"nl", u"collection_broadcast", date=d, collections="\n-".join(names)) send_collection_message(ul.sik, user_location.service_identity, user_location.email, user_location.app_id, message) user_location.next_collection = next_collection user_location.put() ndb.transaction(trans)
def _set_node_status_arrived(order_key, iyo_username, nodes): order = order_key.get() logging.info('Marking nodes %s from node order %s as arrived', nodes, order_key) human_user, app_id = get_app_user_tuple(order.app_user) order.populate(arrival_time=now(), status=NodeOrderStatus.ARRIVED) order.put() deferred.defer(add_nodes_to_profile, iyo_username, nodes, _transactional=True) deferred.defer(update_hoster_progress, human_user.email(), app_id, HosterSteps.NODE_POWERED, _transactional=True)
def order_node_signed(message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag, result_key, flush_id, flush_message_flow_id, service_identity, user_details, flow_params): try: user_detail = user_details[0] tag_dict = json.loads(tag) order = get_node_order(tag_dict['order_id']) last_step = steps[-1] if last_step.answer_id != FormTO.POSITIVE: logging.info('Zero-Node order was canceled') deferred.defer(_cancel_quotation, order.id) return None logging.info('Received signature for Zero-Node order') sign_result = last_step.form_result.result.get_value() assert isinstance(sign_result, SignWidgetResultTO) iyo_username = get_iyo_username(user_detail) sign_see_document(iyo_username, order.tos_iyo_see_id, sign_result, user_detail) logging.debug('Storing signature in DB') order.populate(status=NodeOrderStatus.SIGNED, signature=sign_result.payload_signature, sign_time=now()) order.put() # TODO: send mail to TF support deferred.defer(add_user_to_role, user_detail, RogerthatRoles.HOSTERS) deferred.defer(update_hoster_progress, user_detail.email, user_detail.app_id, HosterSteps.FLOW_SIGN) intercom_tags = get_intercom_tags_for_node_order(order) for intercom_tag in intercom_tags: deferred.defer(tag_intercom_users, intercom_tag, [iyo_username]) logging.debug('Sending confirmation message') result = FlowCallbackResultTypeTO( flow=FLOW_HOSTER_SIGNATURE_RECEIVED, tag=None, force_language=None, flow_params=json.dumps({'orderId': order.human_readable_id})) return FlowMemberResultCallbackResultTO(type=TYPE_FLOW, value=result) except: logging.exception('An unexpected error occurred') return create_error_message()
def set_cookie(response, name, value, domain=None, path='/', expires=None): '''Generates and signs a cookie for the give name/value''' if not isinstance(name, str): name = name.encode('utf8') timestamp = unicode(now()) value = base64.b64encode(value) signature = cookie_signature(value, timestamp) cookie = Cookie.BaseCookie() cookie[name] = '|'.join([value, timestamp, signature]) cookie[name]['path'] = path if not DEBUG: cookie[name]['secure'] = True if domain: cookie[name]['domain'] = domain if expires: cookie[name]['expires'] = email.utils.formatdate(expires, localtime=False, usegmt=True) response.headers['Set-Cookie'] = cookie.output()[12:] + '; httponly'
def parse_cookie(value): '''Parses and verifies a cookie value from set_cookie''' if not value: return None parts = value.split('|') if len(parts) != 3: return None if cookie_signature(parts[0], parts[1]) != parts[2]: logging.warning('Invalid cookie signature %r', value) return None timestamp = int(parts[1]) if timestamp < now() - SESSION_TIMEOUT: logging.warning('Expired cookie %r', value) return None try: return base64.b64decode(parts[0]).strip() except: return None
def get(self): app_redirect_uri = self.request.GET.get('app_redirect_uri', None) try: if not app_redirect_uri: logging.debug('app_redirect_uri is missing') raise HttpBadRequestException() except HttpException as e: render_error_page(self.response, e.http_code, e.error) return auth_plugin = get_auth_plugin() assert isinstance(auth_plugin, ItsYouOnlineAuthPlugin) config = auth_plugin.configuration if config.required_scopes and config.required_scopes is not MISSING: scope = config.required_scopes else: scope = '' organization_id = config.root_organization.name params = { 'response_type': 'code', 'client_id': config.root_organization.name, 'redirect_uri': '%s/refresh/callback' % get_server_url(), 'scope': scope, 'state': str(uuid.uuid4()) } refresh_state = OauthState(key=OauthState.create_key(params['state'])) refresh_state.populate(timestamp=now(), organization_id=organization_id, source=SOURCE_APP, app_redirect_uri=app_redirect_uri, completed=False) refresh_state.put() oauth_url = '%s/authorize?%s' % (auth_plugin.oauth_base_url, urllib.urlencode(params)) logging.info('Redirecting to %s', oauth_url) self.redirect(str(oauth_url))
def trans(): pt_key = ThreeFoldPendingTransaction.create_key(data.id) pt = pt_key.get() if not pt: pt = ThreeFoldPendingTransaction(key=pt_key, timestamp=now()) elif pt.synced: return pt.synced_status pt.unlock_timestamps = [0] pt.unlock_amounts = [data.amount] pt.token = token pt.token_type = token_type pt.amount = data.amount pt.memo = data.memo pt.app_users = [from_user, to_user] pt.from_user = from_user pt.to_user = to_user pt.synced = False pt.synced_status = ThreeFoldPendingTransaction.STATUS_PENDING pt.put() return pt.synced_status
def _worker_settings(settings): tomorrow = now() + 86400 run_job(_query_locations, [settings.sik, tomorrow], _worker_locations, [])
def today(): n = now() return n - n % 86400
def transfer_genesis_coins_to_user(app_user, token_type, amount, memo=None, epoch=0): validate_token_type(token_type) if amount <= 0: raise HttpBadRequestException('invalid_amount') # Validate that this user has a profile get_profile(get_iyo_username(app_user)) if epoch > 0: date_signed = datetime.utcfromtimestamp(epoch) else: date_signed = datetime.now() if TokenType.A == token_type: token = TOKEN_TFT unlock_timestamps = [0] unlock_amounts = [amount] elif TokenType.B == token_type: token = TOKEN_TFT d = date_signed + relativedelta(months=6) unlock_timestamps = [get_epoch_from_datetime(d)] unlock_amounts = [amount] elif TokenType.C == token_type: token = TOKEN_TFT unlock_timestamps = [] unlock_amounts = [] a = amount / 48 for i in xrange(0, 39): d = date_signed + relativedelta(months=48 - i) unlock_timestamps = [get_epoch_from_datetime(d) ] + unlock_timestamps unlock_amounts = [a] + unlock_amounts d = date_signed + relativedelta(months=9) unlock_timestamps = [get_epoch_from_datetime(d)] + unlock_timestamps unlock_amounts = [amount - sum(unlock_amounts)] + unlock_amounts elif TokenType.D == token_type: token = TOKEN_TFT_CONTRIBUTOR unlock_timestamps = [0] unlock_amounts = [amount] elif TokenType.I == token_type: token = TOKEN_ITFT unlock_timestamps = [0] unlock_amounts = [amount] else: raise Exception(u"Unknown token type") key = ThreeFoldWallet.create_key(app_user) wallet = key.get() if not wallet: wallet = ThreeFoldWallet(key=key, tokens=[]) if token not in wallet.tokens: wallet.tokens.append(token) if unlock_timestamps[0] > 0 and ( not wallet.next_unlock_timestamp or unlock_timestamps[0] < wallet.next_unlock_timestamp): wallet.next_unlock_timestamp = unlock_timestamps[0] wallet.put() transaction_id = unicode(uuid.uuid4()) pt = ThreeFoldPendingTransaction( key=ThreeFoldPendingTransaction.create_key(transaction_id), timestamp=now(), unlock_timestamps=unlock_timestamps, unlock_amounts=unlock_amounts, token=token, token_type=token_type, amount=amount, memo=memo, app_users=[app_user], from_user=None, to_user=app_user, synced=False, synced_status=ThreeFoldPendingTransaction.STATUS_PENDING) pt.put() return pt
def sync_wallets(): now_ = now() for wallet in ThreeFoldWallet.list_update_needed(now_): deferred.defer(sync_wallet_for_user, wallet.app_user)
def list_check_online(cls): two_days_ago = now() - (DAY * 2) return cls.list_by_status(NodeOrderStatus.SENT).filter(cls.send_time < two_days_ago)
def is_valid_session(session): return session and session.timeout > now()
def trans(keys): bh = ThreeFoldBlockHeight.get_block_height() if not bh.updating: logging.debug('Blockheight already syncing') return pt_key = keys.pop() if len(keys) == 0: deferred.defer(_sync_transactions, _countdown=1, _transactional=True) else: deferred.defer(_migrate_pending_transactions, keys, _transactional=True) pt = pt_key.get() if not pt: logging.debug('Pending transaction not found') return pt.synced = True height = bh.height + 1 funding_transactions_to_put = [] if pt.from_user: funding_transactions_keys = list_transactions_with_amount_left( pt.from_user, pt.token) funding_transactions = ndb.get_multi(funding_transactions_keys) amount_left = pt.amount for ft in funding_transactions: funding_transactions_to_put.append(ft) spendable_amount = get_spendable_amount_of_transaction(ft) if (amount_left - spendable_amount) >= 0: amount_left -= spendable_amount ft.amount_left -= spendable_amount if ft.amount_left == 0: ft.fully_spent = True else: ft.amount_left -= amount_left break else: logging.debug('Insufficient funds') pt.synced_status = ThreeFoldPendingTransaction.STATUS_FAILED pt.put() return # not enough money ... ndb.put_multi(funding_transactions_to_put) else: logging.info("Genesis payout to %s at height %s", pt.to_user, height) pt.synced_status = ThreeFoldPendingTransaction.STATUS_CONFIRMED pt.put() bh.timestamp = now() bh.height = height bh.put() new_transaction = ThreeFoldTransaction.create_new() new_transaction.timestamp = now() new_transaction.height = height new_transaction.unlock_timestamps = pt.unlock_timestamps new_transaction.unlock_amounts = pt.unlock_amounts new_transaction.token = pt.token new_transaction.token_type = pt.token_type new_transaction.amount = pt.amount new_transaction.amount_left = pt.amount new_transaction.fully_spent = False new_transaction.app_users = [] if pt.from_user: new_transaction.app_users.append(pt.from_user) deferred.defer(sync_payment_asset, pt.from_user, get_asset_id_from_token(pt.from_user, pt.token), _countdown=5, _transactional=True) if pt.to_user: new_transaction.app_users.append(pt.to_user) deferred.defer(sync_payment_asset, pt.to_user, get_asset_id_from_token(pt.to_user, pt.token), _countdown=5, _transactional=True) new_transaction.from_user = pt.from_user new_transaction.to_user = pt.to_user new_transaction.put() key = ThreeFoldWallet.create_key(pt.to_user) wallet = key.get() if not wallet: wallet = ThreeFoldWallet(key=key, tokens=[]) wallet.put() if pt.token not in wallet.tokens: wallet.tokens.append(pt.token) wallet.put() deferred.defer(_save_transaction_to_backlog, new_transaction.id, 'git', _transactional=True) deferred.defer(_save_transaction_to_backlog, new_transaction.id, 'tierion', _transactional=True)
house_bus, today()) except Exception, ex: return {"result": None, "error": ex.message} ul_key = UserLocation.create_key(sik, email, app_id) ul = ul_key.get() if not ul: ul = UserLocation(key=ul_key) ul.notifications = [] ul.service_identity = service_identity ul.address = u"%s %s%s" % (street_name, house_number, house_bus) ul.street_number = street_number ul.house_number = house_number ul.house_bus = house_bus ul.user_data_epoch = now() ul.next_collection = collections[0].epoch ul.put() update_user_data(sik, service_identity, email, app_id, ul.address, ul.notifications, collections) return {"result": u"Location was set", "error": None} def update_user_data(sik, service_identity, email, app_id, address, notifications, collections): deferred.defer(_update_user_data, sik, service_identity, email, app_id,
def _pre_put_hook(self): self.modification_time = now()
def _update_session_timeout(secret): session = Session.create_key(secret).get() if session and session.timeout < now() + (SESSION_TIMEOUT / 2): session.timeout = now() + SESSION_TIMEOUT session.put()
def login_user(response, user_id, scopes, jwt=None): secret, session = create_session(user_id, scopes, jwt) set_cookie(response, get_auth_plugin().get_cookie_name(), secret, expires=now() + SESSION_TIMEOUT) return secret, session
def order_node_signed(status, form_result, answer_id, member, message_key, tag, received_timestamp, acked_timestamp, parent_message_key, result_key, service_identity, user_details): """ Args: status (int) form_result (FormResultTO) answer_id (unicode) member (unicode) message_key (unicode) tag (unicode) received_timestamp (int) acked_timestamp (int) parent_message_key (unicode) result_key (unicode) service_identity (unicode) user_details(list[UserDetailsTO]) Returns: FormAcknowledgedCallbackResultTO """ try: user_detail = user_details[0] tag_dict = json.loads(tag) order = get_node_order(tag_dict['order_id']) if answer_id != FormTO.POSITIVE: logging.info('Zero-Node order was canceled') deferred.defer(_cancel_quotation, order.id) return None logging.info('Received signature for Zero-Node order') sign_result = form_result.result.get_value() assert isinstance(sign_result, SignWidgetResultTO) payload_signature = sign_result.payload_signature iyo_organization_id = get_iyo_organization_id() iyo_username = get_iyo_username(user_detail) logging.debug('Getting IYO SEE document %s', order.tos_iyo_see_id) doc = get_see_document(iyo_organization_id, iyo_username, order.tos_iyo_see_id) doc_view = IYOSeeDocumentView(username=doc.username, globalid=doc.globalid, uniqueid=doc.uniqueid, **serialize_complex_value(doc.versions[-1], IYOSeeDocumenVersion, False)) doc_view.signature = payload_signature keystore_label = get_publickey_label(sign_result.public_key.public_key, user_detail) if not keystore_label: return create_error_message(FormAcknowledgedCallbackResultTO()) doc_view.keystore_label = keystore_label logging.debug('Signing IYO SEE document') sign_see_document(iyo_organization_id, iyo_username, doc_view) logging.debug('Storing signature in DB') order.populate(status=NodeOrderStatus.SIGNED, signature=payload_signature, sign_time=now()) order.put() # TODO: send mail to TF support deferred.defer(add_user_to_role, user_detail, RogerthatRoles.HOSTERS) deferred.defer(update_hoster_progress, user_detail.email, user_detail.app_id, HosterSteps.FLOW_SIGN) intercom_tags = get_intercom_tags_for_node_order(order) for intercom_tag in intercom_tags: deferred.defer(tag_intercom_users, intercom_tag, [iyo_username]) logging.debug('Sending confirmation message') message = MessageCallbackResultTypeTO() message.alert_flags = Message.ALERT_FLAG_VIBRATE message.answers = [] message.branding = get_main_branding_hash() message.dismiss_button_ui_flags = 0 message.flags = Message.FLAG_ALLOW_DISMISS | Message.FLAG_AUTO_LOCK message.message = u'Thank you. We successfully received your digital signature.' \ u' We have stored a copy of this agreement in your ThreeFold Documents.\n\n' \ u'Your order with ID "%s" has been placed successfully.\n' % order.human_readable_id message.step_id = u'order_completed' message.tag = None result = FormAcknowledgedCallbackResultTO() result.type = TYPE_MESSAGE result.value = message return result except: logging.exception('An unexpected error occurred') return create_error_message(FormAcknowledgedCallbackResultTO())
def get(self): organization_id = self.request.GET.get('organization_id', None) source = self.request.GET.get('source', SOURCE_WEB) extra_scopes = self.request.GET.get('scope', '').lstrip(',') register = self.request.GET.get('register', False) config = get_config(NAMESPACE) assert isinstance(config, ItsYouOnlineConfiguration) if not organization_id and config.login_with_organization: self.redirect('/login/organization') return if config.login_with_organization: if organization_id != config.root_organization.name: try: get_organization(organization_id) except OrganizationNotFoundException as e: render_error_page(self.response, httplib.BAD_REQUEST, e.message) return if source not in [SOURCE_WEB, SOURCE_APP]: render_error_page(self.response, httplib.BAD_REQUEST, 'Bad Request') return if config.login_with_organization: if organization_id == config.root_organization.name: if source == SOURCE_APP: render_error_page(self.response, httplib.BAD_REQUEST, 'Bad Request') return else: sub_org = organization_id else: sub_org = get_users_organization(config, organization_id) scope = 'user:memberof:%s' % sub_org elif config.require_memberof: scope = 'user:memberof:%s' % config.root_organization.name else: scope = '' if scope: scope += ',' scope += extra_scopes params = { 'response_type': 'code', 'client_id': config.root_organization.name, 'redirect_uri': get_redirect_uri(config, source), 'scope': scope, 'state': str(uuid.uuid4()) } login_state = OauthState(key=OauthState.create_key(params['state'])) login_state.timestamp = now() login_state.organization_id = organization_id login_state.source = source login_state.completed = False login_state.put() if register: params['register'] = 1 oauth_url = '%s/authorize?%s' % (get_auth_plugin().oauth_base_url, urllib.urlencode(params)) logging.info('Redirecting to %s', oauth_url) self.redirect(str(oauth_url))
def investment_agreement_signed(status, form_result, answer_id, member, message_key, tag, received_timestamp, acked_timestamp, parent_message_key, result_key, service_identity, user_details): """ Args: status (int) form_result (FormResultTO) answer_id (unicode) member (unicode) message_key (unicode) tag (unicode) received_timestamp (int) acked_timestamp (int) parent_message_key (unicode) result_key (unicode) service_identity (unicode) user_details(list[UserDetailsTO]) Returns: FormAcknowledgedCallbackResultTO """ try: user_detail = user_details[0] tag_dict = json.loads(tag) agreement = InvestmentAgreement.create_key( tag_dict['agreement_id']).get() # type: InvestmentAgreement if answer_id != FormTO.POSITIVE: logging.info('Investment agreement was canceled') agreement.status = InvestmentAgreement.STATUS_CANCELED agreement.cancel_time = now() agreement.put() return None logging.info('Received signature for Investment Agreement') sign_result = form_result.result.get_value() assert isinstance(sign_result, SignWidgetResultTO) payload_signature = sign_result.payload_signature iyo_organization_id = get_iyo_organization_id() iyo_username = get_iyo_username(user_detail) logging.debug('Getting IYO SEE document %s', agreement.iyo_see_id) doc = get_see_document(iyo_organization_id, iyo_username, agreement.iyo_see_id) doc_view = IYOSeeDocumentView(username=doc.username, globalid=doc.globalid, uniqueid=doc.uniqueid, **serialize_complex_value( doc.versions[-1], IYOSeeDocumenVersion, False)) doc_view.signature = payload_signature keystore_label = get_publickey_label(sign_result.public_key.public_key, user_detail) if not keystore_label: return create_error_message(FormAcknowledgedCallbackResultTO()) doc_view.keystore_label = keystore_label logging.debug('Signing IYO SEE document') sign_see_document(iyo_organization_id, iyo_username, doc_view) logging.debug('Storing signature in DB') agreement.populate(status=InvestmentAgreement.STATUS_SIGNED, signature=payload_signature, sign_time=now()) agreement.put_async() deferred.defer(add_user_to_role, user_detail, RogerthatRoles.INVESTOR) intercom_tags = get_intercom_tags_for_investment(agreement) if intercom_tags: for i_tag in intercom_tags: deferred.defer(intercom_helpers.tag_intercom_users, i_tag, [iyo_username]) deferred.defer(update_investor_progress, user_detail.email, user_detail.app_id, INVESTMENT_TODO_MAPPING[agreement.status]) deferred.defer(_inform_support_of_new_investment, iyo_username, agreement.id, agreement.token_count_float) logging.debug('Sending confirmation message') prefix_message = u'Thank you. We successfully received your digital signature.' \ u' We have stored a copy of this agreement in your ThreeFold Documents.' \ u' We will contact you again when we have received your payment.' \ u' Thanks again for your purchase and your support of the ThreeFold Foundation!' \ u'\n\nWe would like to take this opportunity to remind you once again to keep a back-up of' \ u' your wallet in a safe place, by writing down the 29 words that can be used to restore it' \ u' to a different device.' \ u' As usual, if you have any questions, don\'t hesitate to contact us.\n\n' msg = u'%sReference: %s' % (prefix_message, agreement.reference) deferred.defer(send_payment_instructions, agreement.app_user, agreement.id, prefix_message) message = MessageCallbackResultTypeTO() message.alert_flags = Message.ALERT_FLAG_VIBRATE message.answers = [] message.branding = get_main_branding_hash() message.dismiss_button_ui_flags = 0 message.flags = Message.FLAG_ALLOW_DISMISS | Message.FLAG_AUTO_LOCK message.message = msg message.step_id = u'investment_agreement_accepted' message.tag = None result = FormAcknowledgedCallbackResultTO() result.type = TYPE_MESSAGE result.value = message return result except: logging.exception('An unexpected error occurred') return create_error_message(FormAcknowledgedCallbackResultTO())