Commit d511fe8f authored by Arnaud Fontaine's avatar Arnaud Fontaine

fixup! py2/py3: Make Products code compatible with both python2 and python3.

parent 735600e2
...@@ -1050,7 +1050,7 @@ class ERP5ImageProcessor(ObjectProcessor): ...@@ -1050,7 +1050,7 @@ class ERP5ImageProcessor(ObjectProcessor):
def process(self): def process(self):
from base64 import b64encode from base64 import b64encode
figure_data = b64encode(self.subject.getData()) figure_data = b64encode(self.subject.getData()).decode()
mime_type = self.subject.getContentType() mime_type = self.subject.getContentType()
return '<img src="data:%s;base64,%s" /><br />' % (mime_type, figure_data), 'text/html' return '<img src="data:%s;base64,%s" /><br />' % (mime_type, figure_data), 'text/html'
...@@ -1193,7 +1193,7 @@ def erp5PivotTableUI(self, df): ...@@ -1193,7 +1193,7 @@ def erp5PivotTableUI(self, df):
""" """
html_string = template % df.to_csv() html_string = template % df.to_csv()
from hashlib import sha512 from hashlib import sha512
key = sha512(html_string).hexdigest() key = sha512(str2bytes(html_string)).hexdigest()
storeIFrame(self, html_string, key) storeIFrame(self, html_string, key)
iframe_host = self.REQUEST['HTTP_X_FORWARDED_HOST'].split(',')[0] iframe_host = self.REQUEST['HTTP_X_FORWARDED_HOST'].split(',')[0]
url = "https://%s/erp5/Base_displayPivotTableFrame?key=%s" % (iframe_host, key) url = "https://%s/erp5/Base_displayPivotTableFrame?key=%s" % (iframe_host, key)
......
...@@ -26,6 +26,11 @@ ...@@ -26,6 +26,11 @@
############################################################################## ##############################################################################
from __future__ import print_function from __future__ import print_function
import base64 import base64
import six
if six.PY2:
from base64 import encodestring as base64_encodebytes
else:
from base64 import encodebytes as base64_encodebytes
from collections import defaultdict from collections import defaultdict
from functools import partial, wraps from functools import partial, wraps
import hashlib import hashlib
...@@ -41,6 +46,7 @@ from six.moves.urllib.parse import parse_qsl, quote, urlencode, urlsplit, urluns ...@@ -41,6 +46,7 @@ from six.moves.urllib.parse import parse_qsl, quote, urlencode, urlsplit, urluns
from AccessControl.SecurityManagement import getSecurityManager, setSecurityManager from AccessControl.SecurityManagement import getSecurityManager, setSecurityManager
from DateTime import DateTime from DateTime import DateTime
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.Utils import bytes2str, str2bytes, unicode2str
from Products.ERP5.ERP5Site import ( from Products.ERP5.ERP5Site import (
ERP5_AUTHORISATION_EXTRACTOR_USERNAME_NAME, ERP5_AUTHORISATION_EXTRACTOR_USERNAME_NAME,
ERP5_AUTHORISATION_EXTRACTOR_PASSWORD_NAME, ERP5_AUTHORISATION_EXTRACTOR_PASSWORD_NAME,
...@@ -76,7 +82,7 @@ class FormExtractor(HTMLParser): ...@@ -76,7 +82,7 @@ class FormExtractor(HTMLParser):
elif self.__in_form and tag in _HTML_FIELD_TAG_SET: elif self.__in_form and tag in _HTML_FIELD_TAG_SET:
self.form_list[-1][1].append(( self.form_list[-1][1].append((
attr_dict['name'], attr_dict['name'],
attr_dict.get('value', '').encode('utf-8'), unicode2str(attr_dict.get('value', ''))
)) ))
def handle_endtag(self, tag): def handle_endtag(self, tag):
...@@ -814,9 +820,9 @@ class TestOAuth2(ERP5TypeTestCase): ...@@ -814,9 +820,9 @@ class TestOAuth2(ERP5TypeTestCase):
'client_id': client_id, 'client_id': client_id,
'state': reference_state, 'state': reference_state,
'code_challenge_method': 'S256', 'code_challenge_method': 'S256',
'code_challenge': base64.urlsafe_b64encode( 'code_challenge': bytes2str(base64.urlsafe_b64encode(
hashlib.sha256(code_verifier).digest(), hashlib.sha256(code_verifier).digest(),
).rstrip('='), )).rstrip('='),
'redirect_uri': _EXTERNAL_CLIENT_REDIRECT_URI, 'redirect_uri': _EXTERNAL_CLIENT_REDIRECT_URI,
}), }),
redirect_uri=_EXTERNAL_CLIENT_REDIRECT_URI, redirect_uri=_EXTERNAL_CLIENT_REDIRECT_URI,
......
...@@ -583,7 +583,7 @@ class OAuth2AuthorisationClientConnector( ...@@ -583,7 +583,7 @@ class OAuth2AuthorisationClientConnector(
) )
RESPONSE.setCookie( RESPONSE.setCookie(
name=name, name=name,
value=base64.urlsafe_b64encode(content), value=bytes2str(base64.urlsafe_b64encode(str2bytes(content))),
# prevent this cookie from being read over the network # prevent this cookie from being read over the network
# (assuming an uncompromised SSL setup, but if it is compromised # (assuming an uncompromised SSL setup, but if it is compromised
# then the attacker may just as well impersonate the victim using # then the attacker may just as well impersonate the victim using
...@@ -618,10 +618,10 @@ class OAuth2AuthorisationClientConnector( ...@@ -618,10 +618,10 @@ class OAuth2AuthorisationClientConnector(
ttl = self._SESSION_STATE_VALIDITY ttl = self._SESSION_STATE_VALIDITY
for name, value in six.iteritems(self._getRawStateCookieDict(REQUEST)): for name, value in six.iteritems(self._getRawStateCookieDict(REQUEST)):
try: try:
result[name] = decrypt( result[name] = bytes2str(decrypt(
base64.urlsafe_b64decode(value), base64.urlsafe_b64decode(value),
ttl=ttl, ttl=ttl,
) ))
except (fernet.InvalidToken, TypeError): except (fernet.InvalidToken, TypeError):
self._expireStateCookie(RESPONSE, name) self._expireStateCookie(RESPONSE, name)
return result return result
...@@ -804,9 +804,9 @@ class OAuth2AuthorisationClientConnector( ...@@ -804,9 +804,9 @@ class OAuth2AuthorisationClientConnector(
( (
'code_challenge', 'code_challenge',
# S256 standard PKCE encoding # S256 standard PKCE encoding
base64.urlsafe_b64encode( bytes2str(base64.urlsafe_b64encode(
hashlib.sha256(code_verifier).digest(), hashlib.sha256(str2bytes(code_verifier)).digest(),
).rstrip('='), )).rstrip('='),
), ),
] ]
if scope_list: if scope_list:
...@@ -820,7 +820,7 @@ class OAuth2AuthorisationClientConnector( ...@@ -820,7 +820,7 @@ class OAuth2AuthorisationClientConnector(
self._setStateCookie( self._setStateCookie(
RESPONSE=RESPONSE, RESPONSE=RESPONSE,
name=name, name=name,
content=encrypt(identifier), content=bytes2str(encrypt(str2bytes(identifier))),
) )
if ( if (
self.isAuthorisationServerRemote() or self.isAuthorisationServerRemote() or
...@@ -831,7 +831,7 @@ class OAuth2AuthorisationClientConnector( ...@@ -831,7 +831,7 @@ class OAuth2AuthorisationClientConnector(
'Location', 'Location',
self._getAuthorisationServerValue( self._getAuthorisationServerValue(
REQUEST=REQUEST, REQUEST=REQUEST,
).absolute_url() + '/authorize?' + urllib.urlencode(query_list), ).absolute_url() + '/authorize?' + urlencode(query_list),
) )
else: else:
# Provide the current URL to authorize, so that it can redirect the # Provide the current URL to authorize, so that it can redirect the
......
import six
import zope import zope
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet from Products.ERP5Type import Permissions, PropertySheet
from Products.ERP5Type.XMLObject import XMLObject from Products.ERP5Type.XMLObject import XMLObject
import hashlib import hashlib
from zLOG import LOG, WARNING from zLOG import LOG, WARNING
import base64 if six.PY2:
from base64 import encodestring as base64_encodebytes
else:
from base64 import encodebytes as base64_encodebytes
import datetime import datetime
import os import os
import time import time
...@@ -54,10 +58,10 @@ class PayzenREST: ...@@ -54,10 +58,10 @@ class PayzenREST:
""" """
def callPayzenApi(self, URL, payzen_dict): def callPayzenApi(self, URL, payzen_dict):
base64string = base64.encodestring( base64string = base64_encodebytes(
'%s:%s' % ( ('%s:%s' % (
self.getServiceUsername(), self.getServiceUsername(),
self.getServiceApiKey())).replace('\n', '') self.getServiceApiKey())).encode()).decode().replace('\n', '')
header = {"Authorization": "Basic %s" % base64string} header = {"Authorization": "Basic %s" % base64string}
LOG('callPayzenApi', WARNING, LOG('callPayzenApi', WARNING,
"data = %s URL = %s" % (str(payzen_dict), URL), error=False) "data = %s URL = %s" % (str(payzen_dict), URL), error=False)
...@@ -141,7 +145,7 @@ class PayzenService(XMLObject, PayzenREST): ...@@ -141,7 +145,7 @@ class PayzenService(XMLObject, PayzenREST):
v = str(v) v = str(v)
signature += v + '+' signature += v + '+'
signature += self.getServicePassword() signature += self.getServicePassword()
return hashlib.sha1(signature).hexdigest() return hashlib.sha1(signature.encode('utf-8')).hexdigest()
def _getFieldList(self, payzen_dict): def _getFieldList(self, payzen_dict):
payzen_dict.update( payzen_dict.update(
......
...@@ -115,19 +115,19 @@ class TestERP5PayzenSecurePayment(TestERP5PayzenSecurePaymentMixin): ...@@ -115,19 +115,19 @@ class TestERP5PayzenSecurePayment(TestERP5PayzenSecurePaymentMixin):
def test_getSignature_dict_simple(self): def test_getSignature_dict_simple(self):
self.assertEqual( self.assertEqual(
self.service._getSignature({'key': 'value'}, ['key']), self.service._getSignature({'key': 'value'}, ['key']),
sha1('value+' + self.service_password) sha1(('value+' + self.service_password).encode())
) )
def test_getSignature_dict_key_sort(self): def test_getSignature_dict_key_sort(self):
self.assertEqual( self.assertEqual(
self.service._getSignature({'key': 'value', 'key1': 'value1'}, ['key', self.service._getSignature({'key': 'value', 'key1': 'value1'}, ['key',
'key1']), 'key1']),
sha1('value+value1+' + self.service_password) sha1(('value+value1+' + self.service_password).encode())
) )
self.assertEqual( self.assertEqual(
self.service._getSignature({'key': 'value', 'key1': 'value1'}, ['key1', self.service._getSignature({'key': 'value', 'key1': 'value1'}, ['key1',
'key']), 'key']),
sha1('value1+value+' + self.service_password) sha1(('value1+value+' + self.service_password).encode())
) )
def test_getSignature_dict_date_as_datetime(self): def test_getSignature_dict_date_as_datetime(self):
...@@ -135,7 +135,7 @@ class TestERP5PayzenSecurePayment(TestERP5PayzenSecurePaymentMixin): ...@@ -135,7 +135,7 @@ class TestERP5PayzenSecurePayment(TestERP5PayzenSecurePaymentMixin):
d = {'key': now} d = {'key': now}
self.assertEqual( self.assertEqual(
self.service._getSignature(d, ['key']), self.service._getSignature(d, ['key']),
sha1(now.strftime('%Y%m%d') + '+' + self.service_password) sha1((now.strftime('%Y%m%d') + '+' + self.service_password).encode())
) )
# dict was updated # dict was updated
self.assertEqual(d['key'], now) self.assertEqual(d['key'], now)
...@@ -158,8 +158,8 @@ class TestERP5PayzenSecurePayment(TestERP5PayzenSecurePaymentMixin): ...@@ -158,8 +158,8 @@ class TestERP5PayzenSecurePayment(TestERP5PayzenSecurePaymentMixin):
self.portal.changeSkin(None) self.portal.changeSkin(None)
try: try:
result = self.service.navigate(pt_id, {"key": 'value'}) result = self.service.navigate(pt_id, {"key": 'value'})
signature = sha1('value+INTERACTIVE+ERP5+TEST+REGISTER+SINGLE+0123456+V2+' signature = sha1(('value+INTERACTIVE+ERP5+TEST+REGISTER+SINGLE+0123456+V2+'
+ self.service_password) + self.service_password).encode())
self.assertEqual(result, """key=key value=value self.assertEqual(result, """key=key value=value
key=signature value=%s key=signature value=%s
key=vads_action_mode value=INTERACTIVE key=vads_action_mode value=INTERACTIVE
......
...@@ -135,7 +135,7 @@ class TestStaticWebSiteRedirection(ERP5TypeTestCase): ...@@ -135,7 +135,7 @@ class TestStaticWebSiteRedirection(ERP5TypeTestCase):
self.assertEqual(response.status, status_to_assert, '%s: %s' % (response.status, url_to_check)) self.assertEqual(response.status, status_to_assert, '%s: %s' % (response.status, url_to_check))
self.assertEqual(response.getheader(LOCATION), redirect_location) self.assertEqual(response.getheader(LOCATION), redirect_location)
self.assertEqual(response.getheader('Content-Type'), 'text/plain; charset=utf-8') self.assertEqual(response.getheader('Content-Type'), 'text/plain; charset=utf-8')
self.assertEqual(response_body, redirect_location) self.assertEqual(response_body.decode('utf-8'), redirect_location)
############################################################################## ##############################################################################
......
...@@ -8,7 +8,7 @@ from six.moves.urllib.request import Request, urlopen ...@@ -8,7 +8,7 @@ from six.moves.urllib.request import Request, urlopen
from six.moves.urllib.parse import urlparse from six.moves.urllib.parse import urlparse
from six import string_types as basestring from six import string_types as basestring
try: try:
import xml.etree.cElementTree as ET import xml.etree.cElementTree as ET # six.PY2: pylint:disable=deprecated-module
except ImportError: except ImportError:
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
......
...@@ -90,17 +90,17 @@ class TestERP5WechatSecurePayment(TestERP5WechatSecurePaymentMixin): ...@@ -90,17 +90,17 @@ class TestERP5WechatSecurePayment(TestERP5WechatSecurePaymentMixin):
def test_calculateSign_dict_simple(self): def test_calculateSign_dict_simple(self):
self.assertEqual( self.assertEqual(
self.service.calculateSign({'key': 'value'}, 'mysecretkey'), self.service.calculateSign({'key': 'value'}, 'mysecretkey'),
hashlib.md5("key=value&key=mysecretkey").hexdigest().upper() hashlib.md5(b"key=value&key=mysecretkey").hexdigest().upper()
) )
def test_calculateSign_dict_key_sort(self): def test_calculateSign_dict_key_sort(self):
self.assertEqual( self.assertEqual(
self.service.calculateSign({'key0': 'value0', 'key1': 'value1'}, 'mysecretkey'), self.service.calculateSign({'key0': 'value0', 'key1': 'value1'}, 'mysecretkey'),
hashlib.md5("key0=value0&key1=value1&key=mysecretkey").hexdigest().upper() hashlib.md5(b"key0=value0&key1=value1&key=mysecretkey").hexdigest().upper()
) )
self.assertEqual( self.assertEqual(
self.service.calculateSign({'key1': 'value1', 'key0': 'value0'}, 'mysecretkey'), self.service.calculateSign({'key1': 'value1', 'key0': 'value0'}, 'mysecretkey'),
hashlib.md5("key0=value0&key1=value1&key=mysecretkey").hexdigest().upper() hashlib.md5(b"key0=value0&key1=value1&key=mysecretkey").hexdigest().upper()
) )
def test_navigate(self): def test_navigate(self):
......
...@@ -33,6 +33,7 @@ from Acquisition import aq_base ...@@ -33,6 +33,7 @@ from Acquisition import aq_base
from OFS.Traversable import Traversable from OFS.Traversable import Traversable
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions as ERP5Permissions from Products.ERP5Type import Permissions as ERP5Permissions
from Products.ERP5Type.Utils import str2bytes
from Products.PythonScripts.Utility import allow_class from Products.PythonScripts.Utility import allow_class
from hashlib import md5 from hashlib import md5
...@@ -375,8 +376,8 @@ class Selection(Acquisition.Implicit, Traversable, Persistent): ...@@ -375,8 +376,8 @@ class Selection(Acquisition.Implicit, Traversable, Persistent):
security.declarePublic('getAnonymousSelectionKey') security.declarePublic('getAnonymousSelectionKey')
def getAnonymousSelectionKey(self): def getAnonymousSelectionKey(self):
return md5(repr({k: v for k, v in six.iteritems(self.__dict__) return md5(str2bytes(repr({k: v for k, v in six.iteritems(self.__dict__)
if k != 'index'})).hexdigest() if k != 'index'}))).hexdigest()
InitializeClass(Selection) InitializeClass(Selection)
allow_class(Selection) allow_class(Selection)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment