Skip to content
This repository has been archived by the owner on Jan 2, 2024. It is now read-only.

Commit

Permalink
style refactor before publishing
Browse files Browse the repository at this point in the history
  • Loading branch information
pedroburon committed Jul 17, 2018
1 parent 58a92b5 commit 4ad478a
Show file tree
Hide file tree
Showing 21 changed files with 267 additions and 578 deletions.
2 changes: 1 addition & 1 deletion LICENSE.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Copyright (c) 2017 Cornershop
Copyright (c) 2018 Cornershop

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

Expand Down
6 changes: 4 additions & 2 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ ipython = "*"
nose = "*"
flask = "*"
docutils = "*"
suds-jurko = "*"


[packages]

xmlsec = "*"
suds-jurko = "*"
zeep = ">=3.0.0"
xmlsec = ">=1.3.3"
lxml = ">=4.1.1"
318 changes: 187 additions & 131 deletions Pipfile.lock

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ Specific service logger are defined by class name::

tbk.services.WebpayService

Specific soap requester logger is also defined by class name::
Soap requests logging is defined in::

tbk.soap.client.SudsSoapClient
tbk.soap



Expand Down Expand Up @@ -156,7 +156,7 @@ El logger específico de un servicio está definido por su nombre de clase::

tbk.services.WebpayService

El logger específico de soap está también definido por su nombre de clase::
El logger específico para soap es el siguiente::

tbk.soap.client.SudsSoapClient
tbk.soap

5 changes: 1 addition & 4 deletions examples/normal.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,7 @@
environment=tbk.INTEGRACION)


from tbk.soap.zeep_client import ZeepSoapClient


webpay_service = tbk.services.WebpayService.init_for_commerce(commerce, ZeepSoapClient)
webpay_service = tbk.services.WebpayService.init_for_commerce(commerce)


@app.route("/")
Expand Down
4 changes: 4 additions & 0 deletions examples/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
width: 0;
min-width: 500px;
border-radius: 0.5em;
margin: 2em 0;
}
form label {
display: block;
Expand Down Expand Up @@ -51,6 +52,9 @@
font-weight: 500;
margin: 0;
}
figure {
margin: 2em 0;
}
</style>
{% endblock style %}
</head>
Expand Down
11 changes: 9 additions & 2 deletions examples/templates/normal/init.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,12 @@ <h2>initTransaction</h2>
<button type="submit">Send to TBK</button>
</fieldset>
</form>
<code>{{transaction.envelope_received}}</code>
{% endblock content%}
<figure>
<caption>Received XML</caption>
<code>{{ transaction.envelope_received }}</code>
</figure>
<figure>
<caption>Sent XML</caption>
<code>{{ transaction.envelope_sent }}</code>
</figure>
{% endblock content %}
2 changes: 1 addition & 1 deletion tbk/__about__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '0.1dev1'
__version__ = '0.2'
17 changes: 9 additions & 8 deletions tbk/soap/requestor.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ def __getitem__(self, key):
return self.result[key]

def __str__(self):
return str(self.result)
import json
return json.dumps(self.result, indent=2)


class SoapRequestor(object):
Expand Down Expand Up @@ -100,9 +101,9 @@ def request(self, method_name, *args, **kwargs):


class SoapClient(AbstractBaseClass):
def __init__(self, wsdl_url, key_data, cert_data, tbk_cert_data):
def __init__(self, wsdl_url, key_data, cert_data, tbk_cert_data, password=None):
self.logger = logging.getLogger('tbk.soap.client.{}'.format(self.__class__.__name__))
self.logger.info("Initializing soap client with url %s", wsdl_url)
self.logger.info("Initializing soap client for wsdl: '%s'", wsdl_url)

@abc.abstractmethod
def get_enum_value(self, enum_name, value):
Expand All @@ -113,12 +114,12 @@ def create_object(self, type_name, **kwargs):
pass

@abc.abstractmethod
def request(self, method_name, method_input):
def request(self, method_name, *args, **kwargs):
pass


def create_soap_client(wsdl_url, key_data, cert_data, tbk_cert_data, client_class=None):
def create_soap_client(wsdl_url, key_data, cert_data, tbk_cert_data, password=None, client_class=None):
if client_class is None:
from .suds_client import SudsSoapClient
client_class = SudsSoapClient
return client_class(wsdl_url, key_data, cert_data, tbk_cert_data)
from .zeep_client import ZeepSoapClient
client_class = ZeepSoapClient
return client_class(wsdl_url, key_data, cert_data, tbk_cert_data, password)
10 changes: 5 additions & 5 deletions tbk/soap/suds_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ def __init__(self, wsdl_url, key_data, cert_data, tbk_cert_data):
cert_data=cert_data,
tbk_cert_data=tbk_cert_data,
)
self.register_request_plugin = SudsRegisterRequestPlugin()
self.history = SudsHistoryPlugin()
self.client = suds.client.Client(
url=wsdl_url,
transport=self.transport,
wsse=wsse,
plugins=[wsse_plugin, self.register_request_plugin],
plugins=[wsse_plugin, self.history],
)

def get_instance(self, type_name):
Expand Down Expand Up @@ -76,13 +76,13 @@ def request(self, method_name, *args, **kwargs):
return result, sent_envelope, received_envelope

def get_last_sent_envelope(self):
return self.register_request_plugin.last_sent
return self.history.last_sent

def get_last_received_envelope(self):
return self.register_request_plugin.last_received
return self.history.last_received


class SudsRegisterRequestPlugin(suds.plugin.MessagePlugin):
class SudsHistoryPlugin(suds.plugin.MessagePlugin):

def __init__(self):
self.last_sent = None
Expand Down
42 changes: 28 additions & 14 deletions tbk/soap/wsse.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
# -*- coding: utf-8 -*-
"""
Custom implementation of wsse (without Timestamp) for Transbank Webpay Webservices.based.
Custom implementation of wsse (without Timestamp) for Transbank Webpay Webservices.
based on py-wsse suds
"""
from __future__ import unicode_literals

from uuid import uuid4

import xmlsec

from lxml import etree
import lxml.etree
import lxml.builder


SOAP_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
Expand All @@ -25,9 +22,9 @@


def sign_envelope_data(envelope_data, key):
envelope = etree.fromstring(envelope_data)
envelope = lxml.etree.fromstring(envelope_data)
sign_envelope(envelope, key)
return etree.tostring(envelope)
return lxml.etree.tostring(envelope)


def sign_envelope(envelope, key):
Expand Down Expand Up @@ -123,8 +120,7 @@ def sign_envelope(envelope, key):
xmlsec.template.x509_data_add_certificate(x509_data)

# Insert the Signature node in the wsse:Security header.
header = envelope.find(ns(SOAP_NS, 'Header'))
security = header.find(ns(WSSE_NS, 'Security'))
security = get_or_create_security_header(envelope)
security.insert(0, signature)

# Perform the actual signing.
Expand All @@ -137,12 +133,12 @@ def sign_envelope(envelope, key):
# KeyInfo. The recipient expects this structure, but we can't rearrange
# like this until after signing, because otherwise xmlsec won't populate
# the X509 data (because it doesn't understand WSSE).
sec_token_ref = etree.SubElement(key_info, ns(WSSE_NS, 'SecurityTokenReference'))
sec_token_ref = lxml.etree.SubElement(key_info, ns(WSSE_NS, 'SecurityTokenReference'))
sec_token_ref.append(x509_data)


def verify_envelope_data(envelope_data, key):
envelope = etree.fromstring(envelope_data)
envelope = lxml.etree.fromstring(envelope_data)
return verify_envelope(envelope, key)


Expand All @@ -162,8 +158,7 @@ def verify_envelope(envelope, key):
ctx = xmlsec.SignatureContext()

# Find each signed element and register its ID with the signing context.
refs = signature.xpath(
'ds:SignedInfo/ds:Reference', namespaces={'ds': DS_NS})
refs = signature.xpath('ds:SignedInfo/ds:Reference', namespaces={'ds': DS_NS})
for ref in refs:
# Get the reference URI and cut off the initial '#'
referenced_id = ref.get('URI')[1:]
Expand Down Expand Up @@ -232,3 +227,22 @@ def ensure_id(node):
id_val = get_unique_id()
node.set(id_attr, id_val)
return id_val


def get_or_create_header(envelope):
header = envelope.find(ns(SOAP_NS, 'Header'))
if header is None:
soap_factory = lxml.builder.ElementMaker(namespace=SOAP_NS, nsmap={'wsse': SOAP_NS})
header = soap_factory.Header()
envelope.insert(0, header)
return header


def get_or_create_security_header(envelope):
header = get_or_create_header(envelope)
security = header.find(ns(WSSE_NS, 'Security'))
if security is None:
wsse_factory = lxml.builder.ElementMaker(namespace=WSSE_NS, nsmap={'wsse': WSSE_NS})
security = wsse_factory.Security()
header.append(security)
return security
23 changes: 14 additions & 9 deletions tbk/soap/zeep_client.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@

import zeep
import zeep.plugins
import zeep.wsse.utils
import zeep.helpers
import xmlsec
import lxml.etree

from .requestor import SoapClient
from .wsse import sign_envelope, verify_envelope
Expand All @@ -14,9 +14,9 @@

class ZeepSoapClient(SoapClient):

def __init__(self, wsdl_url, key_data, cert_data, tbk_cert_data):
def __init__(self, wsdl_url, key_data, cert_data, tbk_cert_data, password=None):
super(ZeepSoapClient, self).__init__(wsdl_url, key_data, cert_data, tbk_cert_data)
wsse = ZeepWsseSignature.init_from_data(key_data, cert_data, tbk_cert_data)
wsse = ZeepWsseSignature.init_from_data(key_data, cert_data, tbk_cert_data, password=password)
self.history = zeep.plugins.HistoryPlugin()
self.client = zeep.Client(wsdl_url, wsse=wsse, plugins=[self.history])

Expand All @@ -32,27 +32,33 @@ def get_enum_value(self, enum_name, value):
return self.create_object(enum_name, value)

def request(self, method_name, *args, **kwargs):
method = self.get_method(method_name)
try:
method = getattr(self.client.service, method_name)
method = self.get_method(method_name)
result = method(*args, **kwargs)
except zeep.exceptions.Fault as fault:
self.logger.exception("Suds WebFault")
self.logger.exception("Fault")
error, code = parse_tbk_error_message(fault.message)
raise SoapServerException(error, code)
else:
serialized = zeep.helpers.serialize_object(result)
return serialized, self.history.last_sent, self.history.last_received
last_sent = self.get_last_sent_envelope()
last_received = self.get_last_received_envelope()
return serialized, last_sent, last_received

def get_method(self, method_name):
try:
return getattr(self.client.service, method_name)
except AttributeError:
raise MethodDoesNotExist(method_name)

def get_last_sent_envelope(self):
return lxml.etree.tostring(self.history.last_sent['envelope'])

def get_last_received_envelope(self):
return lxml.etree.tostring(self.history.last_received['envelope'])


class ZeepWsseSignature(object):
"""Sign given SOAP envelope with WSSE sig using given key and cert."""

def __init__(self, key, tbk_cert):
self.key = key
Expand All @@ -65,7 +71,6 @@ def init_from_data(cls, key_data, cert_data, tbk_cert_data, password=None):
return cls(key, tbk_cert)

def apply(self, envelope, headers):
zeep.wsse.utils.get_security_header(envelope) # create security header
sign_envelope(envelope, self.key)
return envelope, headers

Expand Down
Empty file removed tests/__init__.py
Empty file.
22 changes: 0 additions & 22 deletions tests/data/597020000541.crt

This file was deleted.

27 changes: 0 additions & 27 deletions tests/data/597020000541.key

This file was deleted.

22 changes: 0 additions & 22 deletions tests/data/597020000547.crt

This file was deleted.

Loading

0 comments on commit 4ad478a

Please sign in to comment.