def process_request(self, req, resp): req.context['app_name'] = self.app_name middleware_signals.process_request_start.send(self, req=req, resp=resp) if settings.ALLOW_ORIGINS and req.headers.get( 'ORIGIN') in settings.ALLOW_ORIGINS: # pragma: no cover resp.append_header('Access-Control-Allow-Origin', req.headers['ORIGIN']) resp.append_header('Access-Control-Allow-Headers', 'Authorization, Content-Type, X-Auth-Token') resp.append_header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE') req.data = {} if not req.content_type or 'application/json' in req.content_type: body = req.stream.read() if body: try: req.data = json.loads(body.decode('utf-8')) except (ValueError, UnicodeDecodeError) as e: resource = BaseResource() resource.set_response( resp, responses.MalformedJsonResponse( data=responses.errors.CommonErrors.MalformedJson. set_message(str(e)))) raise falcon.HTTPError(falcon.HTTP_753) elif 'multipart/form-data' in req.content_type: werkzeug_req = Request(req.env) req.data = {k: v for k, v in werkzeug_req.form.items()} req.files = werkzeug_req.files log_msg = '{} {} from {} ({}), data: {}'.format( req.method, req.path, req.user_agent, req.remote_addr, req.data) if hasattr(req, 'files'): log_msg += ', FILES: {}'.format(dict(req.files)) log.debug(log_msg) middleware_signals.process_request_end.send(self, req=req, resp=resp)
def get_objects_query_list(cls, query=None, filtering=None, paging=None, ordering=None): from sqlalchemy import alias, cast, String qs = query or cls.query() if hasattr(cls, '_tab'): tab = cls._tab else: tab = alias(qs, cls.__tablename__) if filtering: for k, v in filtering.items(): if type(v) == type('') and '*' in v: # pragma: no cover v = v.upper() qs = qs.filter( func.upper(cast(getattr(tab.c, k), String)).like(v.replace('*', '%'))) else: qs = qs.filter(getattr(tab.c, k) == v) if ordering: # pragma: no cover order_by = getattr(tab.c, ordering['by']) if ordering['dir'] == 'desc': order_by = order_by.desc().nullslast() qs = qs.order_by(order_by) try: cnt = get_count(qs) #cnt = qs.count() except Exception as e: cnt = len(qs.all()) if paging: if 'from' in paging: qs = qs.offset(paging['from']) if 'till' in paging: qs = qs.limit(paging['till'] - paging.get('from', 0)) try: log.debug(_q_str(qs)) except: log.debug(str(qs)) return qs.all(), cnt
def process_response(self, req, resp, resource, req_succeeded): middleware_signals.process_response_start.send( self, req=req, resp=resp, resource=resource, req_succeeded=req_succeeded) log_body = '<cut>' if 'swagger.' in req.path else resp.body MAX_LOG_RESPONSE = 1024 if resp.body: if len(resp.body) > MAX_LOG_RESPONSE: cut = resp.body[0:MAX_LOG_RESPONSE] if type(cut) == type(b''): cut = cut.decode('utf-8') log_body = cut + '....<too long response for logging>' log.debug('Responding with {}: {}'.format(resp.status, log_body)) middleware_signals.process_response_end.send( self, req=req, resp=resp, resource=resource, req_succeeded=req_succeeded)
def send(self, src, dest, message, buffer=False): # if this message should be bufferred, # then stash it until self.flush is called if buffer: self.buffer.append((src, dest, message)) return True # strip any junk from the destination -- the exact # characters allowed vary wildy between installations # and networks, so we'll play it safe here dest = re.compile('\D').sub("", dest) # urlencode to make special chars # safe to embed in the kannel url msg_enc = quote_plus(message) # send the sms to kannel via a very # unpleasent-looking HTTP GET request # (which is a flagrant violation of the # HTTP spec - this should be POST!) try: url = '{}?username={}&password={}&charset={}&coding={}&to={}&' \ 'from={}&text={}'.format(self.send_url, self.un, self.pw, self.charset, self.coding, dest, src, msg_enc) log.debug('kannel send {}'.format(url)) response = requests.get(url, timeout=(2, 4)) if response.status_code != 202: raise KannelException(response.content.decode('utf-8')) except Exception as e: raise KannelException(e) # for now, just return a boolean to show whether # kannel accepted the sms or not. todo: raise an # exception with the error message upon failure return response.content.decode('utf-8').startswith("0: Accepted")
def on_process_request_start(req, resp): if hasattr(settings, 'ALLOW_ORIGIN') and ('*' in settings.ALLOW_ORIGIN or req.headers.get('ORIGIN') in settings.ALLOW_ORIGIN): if 'ORIGIN' in req.headers: resp.append_header('Access-Control-Allow-Origin', req.headers['ORIGIN']) resp.append_header( 'Access-Control-Allow-Headers', 'Authorization, Content-Type, X-Auth-Token,Cache-Control,X-Requested-With' ) resp.append_header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE') log.debug('CORS headers to {}'.format(req.headers.get('ORIGIN'))) else: log.debug('CORS headers not send: no ORIGIN') else: log.debug('CORS headers not send: not ALLOW')
def proceed(self, req, resp, **kwargs): req_ip = get_request_ip(req) l = model.TransactionLog(transaction_src=req.data, from_ip=req_ip, type='paypal') try: conf = model.ConfigPayment.get(1) stripe.api_key = conf.stripe_skey log.debug('webhook called request data {} kwargs {}'.format(req.data, kwargs)) except Exception as e: l.result = 'bad stripe configuration:{}'.format(e) l.save() self.set_response(resp, OperationalError(e)) return False data = req.data if "type" in data: l.transaction_type = data["type"] if data["type"] == 'charge.succeeded': try: charge_id = data['data']['object']['id'] charge = stripe.Charge.retrieve(charge_id) l.transaction_id = charge_id l.transaction_src = charge description = charge['description'] li = description.split(',') lrn_license_uuid = li[0] l.license_lrn_uuid = lrn_license_uuid switch_license = None switch_license_uuid = None if len(li) > 1: switch_license_uuid = li[1] switch_license = model.LicenseSwitch.get(switch_license_uuid) l.license_switch_uuid = switch_license_uuid lrn_license = model.LicenseLrn.get(lrn_license_uuid) amount_lrn = 0.0 if not lrn_license: lrn_license_uuid = None else: amount_lrn = lrn_license.amount l.amount_lrn = amount_lrn hist = lrn_license.add_history('stripe') if hist: l.session().add(hist) amount_switch = 0.0 if not switch_license: switch_license_uuid = None else: amount_switch = switch_license.amount l.amount_switch = amount_lrn hist = switch_license.add_history('stripe') if hist: l.session().add(hist) amount = charge['amount'] / 100 l.amount_total = amount ucls = model.User u = ucls.filter(ucls.email == charge['source']['customer']).first() if not u and lrn_license: u = lrn_license.user if not u and switch_license: u = switch_license.user if u: if not lrn_license_uuid and not switch_license: u.total_amount = amount u.payment_type = 'stripe' u.apply_mail('payment_failed') return True if amount < amount_lrn + amount_switch: u.total_amount = amount u.payment_type = 'stripe' u.apply_mail('payment_failed') return True pay = model.Payment(user_uuid=u.user_uuid, license_lrn_uuid=lrn_license_uuid, license_switch_uuid=switch_license_uuid, amount_lrn=amount_lrn, amount_switch=amount_switch, type='stripe', description=charge_id ) pay_uuid = pay.save() l.user_uuid=u.user_uuid l.payment_uuid = pay_uuid l.result = 'ok' l.status = 'success' l.save() try: charge.update(dict(metadata=dict(payment_uuid=pay_uuid))) except: pass ret = None if u.alert_payment_received: ret = pay.apply_mail('payment_received') if ret: l.result = 'ok, but email notification not sent: {}'.format(str(ret)) l.save() except Exception as e: l.result = 'stripe transaction error:{}'.format(str(e)) l.save() self.set_response(resp, OperationalError(e)) return False else: log.debug('---event {}'.format(data["type"])) l.result = 'paypal transaction error: wrong stripe event' l.save() self.set_response(resp, responses.ObjectNotFoundErrorResponse()) else: l.result = 'paypal transaction error: wrong stripe data' l.save() self.set_response(resp, responses.ObjectNotFoundErrorResponse()) return False return True
def proceed(self, req, resp, **kwargs): req_ip = get_request_ip(req) l = model.TransactionLog(transaction_src=req.data, from_ip=req_ip, type='paypal') try: conf = model.ConfigPayment.get(1) settings.PAYPAL['client_id'] = conf.paypal_pkey settings.PAYPAL['client_secret'] = conf.paypal_skey if conf.paypal_test_mode: settings.PAYPAL['mode'] = 'sandbox' else: settings.PAYPAL['mode'] = 'live' paypalrestsdk.configure(settings.PAYPAL) except Exception as e: l.result = 'bad paypal configuration:{}'.format(e) l.save() self.set_response(resp, OperationalError(e)) return False try: log.debug('webhook called request data {} kwargs {}'.format(req.data, kwargs)) data = req.data if 'event_type' in data: l.transaction_type = data['event_type'] if data["event_type"] == 'PAYMENT.SALE.COMPLETED': pay_id = data['resource']['parent_payment'] l.transaction_id = pay_id pay = paypalrestsdk.Payment.find(pay_id) # l.transaction_src = pay if 'transactions' in pay and pay['transactions']: tr = pay['transactions'][0] try: l.transaction_fee = float(tr['related_resources'][0]['sale']['transaction_fee']['value']) except: pass if 'amount' in tr and 'total' in tr['amount']: l.amount_total = tr['amount']['total'] items = tr['item_list']['items'] license_lrn = None license_switch = None for item in items: if 'LRN' in item['name'].upper(): l.amount_lrn = float(item['price']) l.license_lrn_uuid = item['sku'] license_lrn = model.LicenseLrn.get(l.license_lrn_uuid); lic = license_lrn if not license_lrn: raise Exception('wrong license lrn uuid - must be in "sku" field') if item['quantity'] != 1: raise Exception('wrong license lrn quantity - must be 1') hist = license_lrn.add_history('paypal') if hist: l.session().add(hist) if 'SWITCH' in item['name'].upper(): l.amount_switch = float(item['price']) l.license_switch_uuid = item['sku'] license_switch = model.LicenseSwitch.get(l.license_switch_uuid) lic = license_switch if not license_switch: raise Exception('wrong license switch uuid - must be in "sku" field') if item['quantity'] != 1: raise Exception('wrong license switch quantity - must be 1') hist = license_switch.add_history('paypal') if hist: l.session().add(hist) if l.license_lrn_uuid or l.license_switch_uuid: if license_lrn: u = license_lrn.user if license_switch: u1 = license_switch.user if u.user_uuid != u1.user_uuid: raise Exception( 'LRN license and SWITCH licence from different users: {} and {}'.format( u.name, u1.name)) else: u = license_switch.user pay = model.Payment(user_uuid=u.user_uuid, license_lrn_uuid=l.license_lrn_uuid, license_switch_uuid=l.license_switch_uuid, amount_lrn=l.amount_lrn, amount_switch=l.amount_switch, type='paypal', description=pay_id ) pay_uuid = pay.save() l.user_uuid = u.user_uuid l.payment_uuid = pay_uuid l.result = 'ok' l.status = 'success' l.save() ret = None if u.alert_payment_received: ret = pay.apply_mail('payment_received') if ret: l.result = 'ok, but email notification not sent: {}'.format(str(ret)) l.save() else: l.result = 'paypal transaction error: empty transaction' l.status = 'fail' log.debug('pay {}'.format(pay)) l.save() else: log.debug('---event {}'.format(data["event_type"])) else: l.result = 'paypal transaction error: wrong paypal event' l.save() self.set_response(resp, responses.ObjectNotFoundErrorResponse()) return False except Exception as e: try: l.result = 'paypal transaction error:{}'.format(str(e)) l.save() self.set_response(resp, OperationalError(e)) return False except Exception as e1: from traceback import format_exc log.debug('paypal accept failure:{}'.format(format_exc())) l.session().rollback() self.set_response(resp, OperationalError(e1)) return False return True