Skip to content

Commit 4572ee6

Browse files
Merge pull request #558 from erakli/refactor
Small refactor and indentation
2 parents a8c6320 + baa046e commit 4572ee6

File tree

11 files changed

+259
-227
lines changed

11 files changed

+259
-227
lines changed

src/saml2/client.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,7 @@ def prepare_for_negotiated_authenticate(
8484
nameid_format=None, scoping=None, consent=None, extensions=None,
8585
sign=None, response_binding=saml2.BINDING_HTTP_POST, **kwargs):
8686
""" Makes all necessary preparations for an authentication request
87-
that negotiates
88-
which binding to use for authentication.
87+
that negotiates which binding to use for authentication.
8988
9089
:param entityid: The entity ID of the IdP to send the request to
9190
:param relay_state: To where the user should be returned after

src/saml2/client_base.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
"""
88
import threading
99
import six
10+
import time
11+
import logging
1012

1113
from saml2.entity import Entity
1214

@@ -25,7 +27,6 @@
2527
from saml2.extension import requested_attributes
2628

2729
import saml2
28-
import time
2930
from saml2.soap import make_soap_enveloped_saml_thingy
3031

3132
from six.moves.urllib.parse import parse_qs
@@ -51,7 +52,7 @@
5152
from saml2 import BINDING_HTTP_REDIRECT
5253
from saml2 import BINDING_HTTP_POST
5354
from saml2 import BINDING_PAOS
54-
import logging
55+
5556

5657
logger = logging.getLogger(__name__)
5758

@@ -94,7 +95,7 @@ class Base(Entity):
9495
""" The basic pySAML2 service provider class """
9596

9697
def __init__(self, config=None, identity_cache=None, state_cache=None,
97-
virtual_organization="", config_file="", msg_cb=None):
98+
virtual_organization="", config_file="", msg_cb=None):
9899
"""
99100
:param config: A saml2.config.Config instance
100101
:param identity_cache: Where the class should store identity information
@@ -133,10 +134,13 @@ def __init__(self, config=None, identity_cache=None, state_cache=None,
133134

134135
setattr(self, attr, val)
135136

136-
if self.entity_type == "sp" and not any([self.want_assertions_signed,
137-
self.want_response_signed]):
138-
logger.warning("The SAML service provider accepts unsigned SAML Responses " +
139-
"and Assertions. This configuration is insecure.")
137+
if self.entity_type == "sp" and not any(
138+
[self.want_assertions_signed, self.want_response_signed]
139+
):
140+
logger.warning(
141+
"The SAML service provider accepts unsigned SAML Responses "
142+
"and Assertions. This configuration is insecure."
143+
)
140144

141145
self.artifact2response = {}
142146

src/saml2/config.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -381,11 +381,11 @@ def _load(self, fil):
381381

382382
return importlib.import_module(tail)
383383

384-
def load_file(self, config_file, metadata_construction=False):
385-
if config_file.endswith(".py"):
386-
config_file = config_file[:-3]
384+
def load_file(self, config_filename, metadata_construction=False):
385+
if config_filename.endswith(".py"):
386+
config_filename = config_filename[:-3]
387387

388-
mod = self._load(config_file)
388+
mod = self._load(config_filename)
389389
return self.load(copy.deepcopy(mod.CONFIG), metadata_construction)
390390

391391
def load_metadata(self, metadata_conf):

src/saml2/ecp_client.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@
3333

3434

3535
class Client(Entity):
36+
"""ECP-aware client that works on the client (application) side.
37+
38+
You can use this class when you want to login user through
39+
ECP-aware SP and IdP.
40+
"""
41+
3642
def __init__(self, user, passwd, sp="", idp=None, metadata_file=None,
3743
xmlsec_binary=None, verbose=0, ca_certs="",
3844
disable_ssl_certificate_validation=True, key_file=None,
@@ -221,7 +227,8 @@ def ecp_conversation(self, respdict, idp_entity_id=None):
221227

222228
return None
223229

224-
def add_paos_headers(self, headers=None):
230+
@staticmethod
231+
def add_paos_headers(headers=None):
225232
if headers:
226233
headers = set_list2dict(headers)
227234
headers["PAOS"] = PAOS_HEADER_INFO
@@ -283,7 +290,7 @@ def operation(self, url, idp_entity_id, op, **opargs):
283290
# should by now be authenticated so this should go smoothly
284291
response = self.send(url, op, **opargs)
285292
except (soap.XmlParseError, AssertionError, KeyError):
286-
pass
293+
raise
287294

288295
if response.status_code >= 400:
289296
raise SAMLError("Error performing operation: %s" % (

src/saml2/entity.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,6 @@
6363
from saml2.sigver import security_context
6464
from saml2.sigver import response_factory
6565
from saml2.sigver import SigverError
66-
from saml2.sigver import CryptoBackendXmlSec1
6766
from saml2.sigver import make_temp
6867
from saml2.sigver import pre_encryption_part
6968
from saml2.sigver import pre_signature_part
@@ -554,7 +553,6 @@ def _encrypt_assertion(self, encrypt_cert, sp_entity_id, response,
554553
_certs = []
555554

556555
if encrypt_cert:
557-
_certs = []
558556
_certs.append(encrypt_cert)
559557
elif sp_entity_id is not None:
560558
_certs = self.metadata.certs(sp_entity_id, "any", "encryption")
@@ -1134,12 +1132,11 @@ def _parse_response(self, xmlstr, response_cls, service, binding,
11341132
raise
11351133

11361134
xmlstr = self.unravel(xmlstr, binding, response_cls.msgtype)
1137-
origxml = xmlstr
11381135
if not xmlstr: # Not a valid reponse
11391136
return None
11401137

11411138
try:
1142-
response = response.loads(xmlstr, False, origxml=origxml)
1139+
response = response.loads(xmlstr, False, origxml=xmlstr)
11431140
except SigverError as err:
11441141
logger.error("Signature Error: %s", err)
11451142
raise

src/saml2/population.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import logging
2+
23
import six
4+
35
from saml2.cache import Cache
4-
from saml2.ident import code
56

67
logger = logging.getLogger(__name__)
78

src/saml2/s2repoze/plugins/challenge_decider.py

Lines changed: 42 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -9,74 +9,78 @@
99
import re
1010

1111
_DAV_METHODS = (
12-
'OPTIONS',
13-
'PROPFIND',
14-
'PROPPATCH',
15-
'MKCOL',
16-
'LOCK',
17-
'UNLOCK',
18-
'TRACE',
19-
'DELETE',
20-
'COPY',
21-
'MOVE'
22-
)
12+
"OPTIONS",
13+
"PROPFIND",
14+
"PROPPATCH",
15+
"MKCOL",
16+
"LOCK",
17+
"UNLOCK",
18+
"TRACE",
19+
"DELETE",
20+
"COPY",
21+
"MOVE",
22+
)
2323

2424
_DAV_USERAGENTS = (
25-
'Microsoft Data Access Internet Publishing Provider',
26-
'WebDrive',
27-
'Zope External Editor',
28-
'WebDAVFS',
29-
'Goliath',
30-
'neon',
31-
'davlib',
32-
'wsAPI',
33-
'Microsoft-WebDAV'
34-
)
25+
"Microsoft Data Access Internet Publishing Provider",
26+
"WebDrive",
27+
"Zope External Editor",
28+
"WebDAVFS",
29+
"Goliath",
30+
"neon",
31+
"davlib",
32+
"wsAPI",
33+
"Microsoft-WebDAV",
34+
)
35+
3536

3637
def my_request_classifier(environ):
3738
""" Returns one of the classifiers 'dav', 'xmlpost', or 'browser',
3839
depending on the imperative logic below"""
3940
request_method = REQUEST_METHOD(environ)
4041
if request_method in _DAV_METHODS:
41-
return 'dav'
42+
return "dav"
4243
useragent = USER_AGENT(environ)
4344
if useragent:
4445
for agent in _DAV_USERAGENTS:
4546
if useragent.find(agent) != -1:
46-
return 'dav'
47-
if request_method == 'POST':
48-
if CONTENT_TYPE(environ) == 'text/xml':
49-
return 'xmlpost'
47+
return "dav"
48+
if request_method == "POST":
49+
if CONTENT_TYPE(environ) == "text/xml":
50+
return "xmlpost"
5051
elif CONTENT_TYPE(environ) == "application/soap+xml":
51-
return 'soap'
52-
return 'browser'
52+
return "soap"
53+
return "browser"
54+
5355

5456
zope.interface.directlyProvides(my_request_classifier, IRequestClassifier)
5557

58+
5659
class MyChallengeDecider:
5760
def __init__(self, path_login="", path_logout=""):
5861
self.path_login = path_login
5962
self.path_logout = path_logout
63+
6064
def __call__(self, environ, status, _headers):
61-
if status.startswith('401 '):
65+
if status.startswith("401 "):
6266
return True
6367
else:
64-
if environ.has_key('samlsp.pending'):
68+
if environ.has_key("samlsp.pending"):
6569
return True
6670

67-
uri = environ.get('REQUEST_URI', None)
71+
uri = environ.get("REQUEST_URI", None)
6872
if uri is None:
6973
uri = construct_url(environ)
7074

7175
# require and challenge for logout and inform the challenge plugin that it is a logout we want
7276
for regex in self.path_logout:
7377
if regex.match(uri) is not None:
74-
environ['samlsp.logout'] = True
78+
environ["samlsp.logout"] = True
7579
return True
7680

7781
# If the user is already authent, whatever happens(except logout),
7882
# don't make a challenge
79-
if environ.has_key('repoze.who.identity'):
83+
if environ.has_key("repoze.who.identity"):
8084
return False
8185

8286
# require a challenge for login
@@ -87,27 +91,24 @@ def __call__(self, environ, status, _headers):
8791
return False
8892

8993

90-
91-
def make_plugin(path_login = None, path_logout = None):
94+
def make_plugin(path_login=None, path_logout=None):
9295
if path_login is None:
93-
raise ValueError(
94-
'must include path_login in configuration')
96+
raise ValueError("must include path_login in configuration")
9597

96-
# make regexp out of string passed via the config file
98+
# make regexp out of string passed via the config file
9799
list_login = []
98100
for arg in path_login.splitlines():
99101
carg = arg.lstrip()
100-
if carg != '':
102+
if carg != "":
101103
list_login.append(re.compile(carg))
102104

103105
list_logout = []
104106
if path_logout is not None:
105107
for arg in path_logout.splitlines():
106108
carg = arg.lstrip()
107-
if carg != '':
109+
if carg != "":
108110
list_logout.append(re.compile(carg))
109111

110112
plugin = MyChallengeDecider(list_login, list_logout)
111113

112114
return plugin
113-

src/saml2/s2repoze/plugins/entitlement.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33

44
from zope.interface import implements
55

6-
#from repoze.who.interfaces import IChallenger, IIdentifier, IAuthenticator
6+
# from repoze.who.interfaces import IChallenger, IIdentifier, IAuthenticator
77
from repoze.who.interfaces import IMetadataProvider
88

9+
910
class EntitlementMetadataProvider(object):
1011

1112
implements(IMetadataProvider)
@@ -43,7 +44,7 @@ def get_entitlement(self, user, virtualorg):
4344

4445
def store_entitlement(self, user, virtualorg, entitlement=None):
4546
if user not in self._store:
46-
self._store[user] = {"entitlement":{}}
47+
self._store[user] = {"entitlement": {}}
4748
elif "entitlement" not in self._store[user]:
4849
self._store[user]["entitlement"] = {}
4950

@@ -53,18 +54,17 @@ def store_entitlement(self, user, virtualorg, entitlement=None):
5354
self._store.sync()
5455

5556
def add_metadata(self, environ, identity):
56-
#logger = environ.get('repoze.who.logger','')
57+
# logger = environ.get('repoze.who.logger','')
5758
try:
58-
user = self._store[identity.get('repoze.who.userid')]
59+
user = self._store[identity.get("repoze.who.userid")]
5960
except KeyError:
6061
return
6162

6263
try:
6364
vorg = environ["myapp.vo"]
6465
try:
6566
ents = user["entitlement"][vorg]
66-
identity["user"] = {
67-
"entitlement": ["%s:%s" % (vorg,e) for e in ents]}
67+
identity["user"] = {"entitlement": ["%s:%s" % (vorg, e) for e in ents]}
6868
except KeyError:
6969
pass
7070
except KeyError:
@@ -73,5 +73,6 @@ def add_metadata(self, environ, identity):
7373
res.extend(["%s:%s" % (vorg, e) for e in ents])
7474
identity["user"] = res
7575

76+
7677
def make_plugin(filename, key_attribute=""):
7778
return EntitlementMetadataProvider(filename, key_attribute)

0 commit comments

Comments
 (0)