Skip to content

Commit 61f51b0

Browse files
Egor Panfilovc00kiemon5ter
authored andcommitted
[Need help] Fix IdP example to work with python 3
1 parent 303e6ad commit 61f51b0

File tree

2 files changed

+55
-23
lines changed

2 files changed

+55
-23
lines changed

example/idp2/idp.py

Lines changed: 53 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -103,12 +103,12 @@ def __init__(self, environ, start_response, user=None):
103103
def unpack_redirect(self):
104104
if "QUERY_STRING" in self.environ:
105105
_qs = self.environ["QUERY_STRING"]
106-
return dict([(k, v[0]) for k, v in parse_qs(_qs).items()])
106+
return dict([(k, v[0]) for k, v in _get_query(_qs).items()])
107107
else:
108108
return None
109109

110110
def unpack_post(self):
111-
_dict = parse_qs(get_post(self.environ))
111+
_dict = _get_query(get_post(self.environ))
112112
logger.debug("unpack_post:: %s", _dict)
113113
try:
114114
return dict([(k, v[0]) for k, v in _dict.items()])
@@ -297,7 +297,7 @@ def verify_request(self, query, binding):
297297

298298
resp_args = {}
299299
try:
300-
resp_args = IDP.response_args(_authn_req)
300+
resp_args = IDP.response_args(_authn_req, self.response_bindings)
301301
_resp = None
302302
except UnknownPrincipal as excp:
303303
_resp = IDP.create_error_response(_authn_req.id,
@@ -482,13 +482,13 @@ def ecp(self):
482482
resp = Unauthorized()
483483
else:
484484
try:
485-
(user, passwd) = _info.split(":")
486-
if is_equal(PASSWD[user], passwd):
485+
(user, passwd) = _info.split(b":")
486+
user = user.decode()
487+
if not is_equal(PASSWD[user], passwd):
487488
resp = Unauthorized()
488489
self.user = user
489-
self.environ[
490-
"idp.authn"] = AUTHN_BROKER.get_authn_by_accr(
491-
PASSWORD)
490+
self.environ["idp.authn"] = \
491+
AUTHN_BROKER.get_authn_by_accr(PASSWORD)
492492
except ValueError:
493493
resp = Unauthorized()
494494
else:
@@ -531,11 +531,11 @@ def do_authentication(environ, start_response, authn_context, key,
531531
# -----------------------------------------------------------------------------
532532

533533
PASSWD = {
534-
"daev0001": "qwerty",
535-
"testuser": "qwerty",
536-
"roland": "dianakra",
537-
"babs": "howes",
538-
"upper": "crust"}
534+
"daev0001": b"qwerty",
535+
"testuser": b"qwerty",
536+
"roland": b"dianakra",
537+
"babs": b"howes",
538+
"upper": b"crust"}
539539

540540

541541
def username_password_authn(environ, start_response, reference, key,
@@ -563,18 +563,46 @@ def username_password_authn(environ, start_response, reference, key,
563563
return resp(environ, start_response, **argv)
564564

565565

566+
def _ensure_string(thing):
567+
import six
568+
if isinstance(thing, six.binary_type):
569+
return thing.decode()
570+
elif isinstance(thing, six.string_types):
571+
return thing
572+
elif isinstance(thing, list):
573+
return [_ensure_string(item) for item in thing]
574+
else:
575+
return thing
576+
577+
578+
def _convert_dict_with_bytes(d):
579+
new_d = {}
580+
for key, value in d.items():
581+
new_key = _ensure_string(key)
582+
new_value = _ensure_string(value)
583+
new_d[new_key] = new_value
584+
return new_d
585+
586+
587+
def _get_query(qs):
588+
query = parse_qs(qs)
589+
return _convert_dict_with_bytes(query)
590+
591+
566592
def verify_username_and_password(dic):
567593
global PASSWD
568594
# verify username and password
569-
if PASSWD[dic["login"][0]] == dic["password"][0]:
570-
return True, dic["login"][0]
595+
login = dic["login"][0]
596+
password = dic["password"][0].encode()
597+
598+
if PASSWD[login] == password:
599+
return True, login
571600
else:
572601
return False, ""
573602

574603

575604
def do_verify(environ, start_response, _):
576-
query = parse_qs(get_post(environ))
577-
605+
query = _get_query(get_post(environ))
578606
logger.debug("do_verify: %s", query)
579607

580608
try:
@@ -861,7 +889,8 @@ def info_from_cookie(kaka):
861889
morsel = cookie_obj.get("idpauthn", None)
862890
if morsel:
863891
try:
864-
key, ref = base64.b64decode(morsel.value).split(":")
892+
key, ref = \
893+
_ensure_string(base64.b64decode(morsel.value)).split(":")
865894
return IDP.cache.uid2user[key], ref
866895
except (KeyError, TypeError):
867896
return None, None
@@ -886,8 +915,10 @@ def delete_cookie(environ, name):
886915

887916

888917
def set_cookie(name, _, *args):
918+
args = [a.encode() for a in args]
919+
889920
cookie = SimpleCookie()
890-
cookie[name] = base64.b64encode(":".join(args))
921+
cookie[name] = base64.b64encode(b":".join(args)).decode()
891922
cookie[name]['path'] = "/"
892923
cookie[name]["expires"] = _expiration(5) # 5 minutes from now
893924
logger.debug("Cookie expires: %s", cookie[name]["expires"])
@@ -951,7 +982,7 @@ def metadata(environ, start_response):
951982
args.valid, args.cert, args.keyfile,
952983
args.id, args.name, args.sign)
953984
start_response('200 OK', [('Content-Type', "text/xml")])
954-
return metadata
985+
return [metadata]
955986
except Exception as ex:
956987
logger.error("An error occured while creating metadata: %s", ex.message)
957988
return not_found(environ, start_response)
@@ -1042,7 +1073,8 @@ def application(environ, start_response):
10421073

10431074
if __name__ == '__main__':
10441075
parser = argparse.ArgumentParser()
1045-
parser.add_argument('-p', dest='path', help='Path to configuration file.', default='./idp_conf.py')
1076+
parser.add_argument('-p', dest='path', help='Path to configuration file.',
1077+
default='./idp_conf.py')
10461078
parser.add_argument('-v', dest='valid',
10471079
help="How long, in days, the metadata is valid from "
10481080
"the time of creation")

example/idp2/idp_conf.py.example

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
#!/usr/bin/env python
22
# -*- coding: utf-8 -*-
3+
import os.path
4+
35
from saml2 import BINDING_HTTP_REDIRECT, BINDING_URI
46
from saml2 import BINDING_HTTP_ARTIFACT
57
from saml2 import BINDING_HTTP_POST
68
from saml2 import BINDING_SOAP
79
from saml2.saml import NAME_FORMAT_URI
810
from saml2.saml import NAMEID_FORMAT_TRANSIENT
911
from saml2.saml import NAMEID_FORMAT_PERSISTENT
10-
import os.path
11-
import saml2.xmldsig as ds
1212

1313
try:
1414
from saml2.sigver import get_xmlsec_binary

0 commit comments

Comments
 (0)