def on_get(self, req, resp, **kwargs): # pragma: no cover self.init_req(req) kw = user_context(self, req, resp, **kwargs) try: ret = super(Resource, self).on_get(req, resp, **kw) except NoResultFound: self.set_response(resp, responses.ObjectNotFoundErrorResponse()) return None
def get_spec(self): return specify.get_spec( method='post', description='Authenticate', body_parameters=('Credentials', self.credentials_scheme_class), responses=(responses.SuccessResponse(scheme=AuthTokenExtScheme), responses.ValidationErrorResponse(), responses.UnAuthorizedErrorResponse(), responses.ObjectNotFoundErrorResponse()), security=self.security)
def on_patch(self, req, resp, **kwargs): self.init_req(req) kwargs = user_context(self, req, resp, **kwargs) if not self.has_modify_operation: # pragma: no cover return self.method_not_allowed_response(resp, 'PATCH') if not check_permission( self, req, 'modify', self.get_object(resp, self.model_class, **kwargs)): self.set_response( resp, responses.ForbiddenErrorResponse( data=errors.AuthErrors.Forbidden)) return try: scheme = self.scheme_class_modify( ) if self.scheme_class_modify else self.scheme_class() if self.check_request_data(req, resp, scheme): if self.update_object( req, resp, self.model_class, self.scheme_class_modify if self.scheme_class_modify else self.scheme_class, **kwargs): data = self.get_object_data(resp, self.model_class, self.scheme_class_get, **kwargs) if data: self.set_response( resp, responses.SuccessResponseObjectInfo(data=data)) else: self.set_response(resp, responses.SuccessResponseJustOk()) except IntegrityError as e: try: msg = str(e).split('\n')[1].split(':')[1] except: msg = str(e) self.set_response(resp, AlreadyExistsResponse(self.entity, msg)) except FkConstraintViolation as e: self.set_response( resp, responses.FkConstraintViolationResponse( data=errors.CommonErrors.get_fk_violation_error( e.table_name, e.column_name, e.value))) except ValidationError as e: self.set_response( resp, responses.ValidationErrorResponse(data=e.messages)) except NoResultFound: self.set_response(resp, responses.ObjectNotFoundErrorResponse()) except Exception as e: log.error(e) #self.set_response(resp, responses.OperationErrorResponse(data=errors.CommonErrors.DataError)) self.set_response(resp, OperationalError(e))
def get_spec(self): return swagger.specify.get_spec( method=self.method, description=self.description, path_parameters=self.path_parameters, query_parameters=self.query_parameters, body_parameters=self.body_parameters, responses=(responses.SuccessResponseJustOk(), responses.ObjectNotFoundErrorResponse()) + self.additional_responses, security=self.get_security(method=self.method))
def get_spec(self): return swagger.specify.get_spec( method='post', description='Restores object to the specified revision', path_parameters=({ 'name': 'id', 'description': 'ID of revision to restore to' }, ), responses=(responses.SuccessResponseJustOk(), responses.ObjectNotFoundErrorResponse()), security=self.security)
def get_spec_delete(self): return swagger.specify.get_spec( method='delete', description='Deletes multiple found {}'.format( self.entity.lower()), path_parameters=self.get_path_parameters(), query_parameters=List.get_all_fields_from_scheme( self.scheme_class)[1], responses=(responses.SuccessResponseObjectInfo( payload_scheme=self.scheme_class_get), responses.ObjectNotFoundErrorResponse()) + self.get_additional_responses(method='delete'), security=self.get_security(method='delete', action='delete'))
def on_get(self, req, resp, **kwargs): # pragma: no cover self.init_req(req) kwargs = user_context(self, req, resp, **kwargs) try: #ret = super(IcxList,self).on_get(req, resp, **kwargs) ret = self._on_get(req, resp, **kwargs) except NoResultFound: self.set_response(resp, responses.ObjectNotFoundErrorResponse()) return None if req.headers['ACCEPT'] == 'application/xml' or req.headers[ 'ACCEPT'] == 'text/xml': data = json.loads(resp.body) result = bf(xml_tostring=xml_tostring).etree( data=data, root=Element('xml', attrib={ 'entity': self.model_class.__name__, 'api_version': VERSION, 'timestamp': str(datetime.utcnow()) })) rough_string = tostring(result, 'utf-8') reparsed = minidom.parseString(rough_string) resp.body = reparsed.toprettyxml(indent='\t') resp.content_type = 'text/xml' if req.headers['ACCEPT'] == 'text/csv': data = json.loads(resp.body) csvfile = io.StringIO() items = data['payload']['items'] if len(items): fieldnames = data['payload']['items'][0].keys() writer = DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(items) resp.body = str.encode(csvfile.getvalue()) else: resp.body = '' resp.content_type = 'text/csv' return ret
def on_delete(self, req, resp, **kwargs): self.init_req(req) if not self.has_delete_operation: # pragma: no cover return self.method_not_allowed_response(resp, 'DELETE') obj = self.get_object(resp, self.model_class, **kwargs) if not check_permission(self, req, 'delete', obj): self.set_response( resp, responses.ForbiddenErrorResponse( data=errors.AuthErrors.Forbidden)) return kw = user_context(self, req, resp, **kwargs) try: self.before_delete(obj, req, resp, **kwargs) except Exception as e: self.set_response(resp, OperationalError(e)) return try: if self.delete_object(req, resp, self.model_class, **kwargs): self.set_response(resp, responses.SuccessResponseJustOk()) except NoResultFound: self.set_response(resp, responses.ObjectNotFoundErrorResponse())
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