Skip to content
This repository was archived by the owner on Jun 12, 2021. It is now read-only.

Commit bcf0f78

Browse files
authored
Merge pull request #20 from peppelinux/master
Registration and Authorization code style
2 parents 2913213 + dff94e4 commit bcf0f78

2 files changed

Lines changed: 126 additions & 174 deletions

File tree

src/oidcendpoint/oidc/authorization.py

Lines changed: 82 additions & 121 deletions
Original file line numberDiff line numberDiff line change
@@ -52,26 +52,26 @@
5252
</html>"""
5353

5454

55+
DEFAULT_SCOPES = list(SCOPE2CLAIMS.keys())
56+
DEFAULT_SCOPES.append("openid")
57+
58+
5559
def inputs(form_args):
5660
"""
5761
Creates list of input elements
5862
"""
5963
element = []
64+
html_field = '<input type="hidden" name="{}" value="{}"/>'
6065
for name, value in form_args.items():
6166
element.append(
62-
'<input type="hidden" name="{}" value="{}"/>'.format(name, value)
67+
html_field.format(name, value)
6368
)
6469
return "\n".join(element)
6570

6671

6772
def max_age(request):
68-
try:
69-
return request[verified_claim_name("request")]["max_age"]
70-
except KeyError:
71-
try:
72-
return request["max_age"]
73-
except KeyError:
74-
return 0
73+
cn = verified_claim_name("request")
74+
return request.get(cn, {}).get("max_age") or request.get("max_age", 0)
7575

7676

7777
def re_authenticate(request, authn):
@@ -83,21 +83,14 @@ def re_authenticate(request, authn):
8383

8484

8585
def acr_claims(request):
86-
try:
87-
acrdef = request["claims"]["id_token"]["acr"]
88-
except KeyError:
89-
return None
90-
else:
91-
if isinstance(acrdef, dict):
92-
try:
93-
return [acrdef["value"]]
94-
except KeyError:
95-
try:
96-
return acrdef["values"]
97-
except KeyError:
98-
pass
86+
if request["claims"].get("id_token"):
87+
acrdef = request["claims"]["id_token"].get("acr")
9988

100-
return None
89+
if isinstance(acrdef, dict):
90+
if acrdef.get("value"):
91+
return [acrdef["value"]]
92+
elif acrdef.get("values"):
93+
return acrdef["values"]
10194

10295

10396
def verify_uri(endpoint_context, request, uri_type, client_id=None):
@@ -112,10 +105,7 @@ def verify_uri(endpoint_context, request, uri_type, client_id=None):
112105
:return: An error response if the redirect URI is faulty otherwise
113106
None
114107
"""
115-
try:
116-
_cid = request["client_id"]
117-
except KeyError:
118-
_cid = client_id
108+
_cid = request.get("client_id", client_id)
119109

120110
if not _cid:
121111
LOGGER.error("No client id found")
@@ -132,9 +122,8 @@ def verify_uri(endpoint_context, request, uri_type, client_id=None):
132122
_query = parse_qs(_query)
133123

134124
match = False
135-
try:
136-
values = endpoint_context.cdb[_cid]["{}s".format(uri_type)]
137-
except KeyError:
125+
values = endpoint_context.cdb.get(_cid, {}).get("{}s".format(uri_type))
126+
if not values:
138127
raise ValueError("No registered {}".format(uri_type))
139128
else:
140129
for regbase, rquery in values:
@@ -229,16 +218,12 @@ def authn_args_gather(request, authn_class_ref, cinfo, **kwargs):
229218
authn_args["as_user"] = (kwargs["req_user"],)
230219

231220
for attr in ["policy_uri", "logo_uri", "tos_uri"]:
232-
try:
221+
if cinfo.get(attr):
233222
authn_args[attr] = cinfo[attr]
234-
except KeyError:
235-
pass
236223

237224
for attr in ["ui_locales", "acr_values", "login_hint"]:
238-
try:
225+
if request.get(attr):
239226
authn_args[attr] = request[attr]
240-
except KeyError:
241-
pass
242227

243228
return authn_args
244229

@@ -253,28 +238,24 @@ def create_authn_response(endpoint, request, sid):
253238
"""
254239
# create the response
255240
aresp = AuthorizationResponse()
256-
try:
241+
if request.get("state"):
257242
aresp["state"] = request["state"]
258-
except KeyError:
259-
pass
260243

261244
if "response_type" in request and request["response_type"] == ["none"]:
262245
fragment_enc = False
263246
else:
264247
_context = endpoint.endpoint_context
265248
_sinfo = _context.sdb[sid]
266249

267-
try:
250+
if request.get("scope"):
268251
aresp["scope"] = request["scope"]
269-
except KeyError:
270-
pass
271252

272253
rtype = set(request["response_type"][:])
273254
handled_response_type = []
255+
256+
fragment_enc = True
274257
if len(rtype) == 1 and "code" in rtype:
275258
fragment_enc = False
276-
else:
277-
fragment_enc = True
278259

279260
if "code" in request["response_type"]:
280261
_code = aresp["code"] = _context.sdb[sid]["code"]
@@ -293,11 +274,8 @@ def create_authn_response(endpoint, request, sid):
293274

294275
handled_response_type.append("token")
295276

296-
try:
297-
_access_token = aresp["access_token"]
298-
except KeyError:
299-
_access_token = None
300-
277+
_access_token = aresp.get("access_token", None)
278+
301279
if "id_token" in request["response_type"]:
302280
kwargs = {}
303281
if {"code", "id_token", "token"}.issubset(rtype):
@@ -335,15 +313,10 @@ def create_authn_response(endpoint, request, sid):
335313

336314

337315
def proposed_user(request):
338-
try:
339-
return request[verified_claim_name("it_token_hint")]["sub"]
340-
except KeyError:
341-
return ""
342-
343-
344-
DEFAULT_SCOPES = list(SCOPE2CLAIMS.keys())
345-
DEFAULT_SCOPES.append("openid")
346-
316+
cn = verified_claim_name("it_token_hint")
317+
if request.get(cn):
318+
return request[cn].get("sub", "")
319+
return ""
347320

348321
class Authorization(Endpoint):
349322
request_cls = oidc.AuthorizationRequest
@@ -381,9 +354,9 @@ def filter_request(self, endpoint_context, req):
381354

382355
def verify_response_type(self, request, cinfo):
383356
# Checking response types
384-
try:
385-
_registered = [set(rt.split(" ")) for rt in cinfo["response_types"]]
386-
except KeyError:
357+
_registered = [set(rt.split(" "))
358+
for rt in cinfo.get("response_types", [])]
359+
if not _registered:
387360
# If no response_type is registered by the client then we'll
388361
# code which it the default according to the OIDC spec.
389362
_registered = [{"code"}]
@@ -408,9 +381,8 @@ def _post_parse_request(self, request, client_id, endpoint_context, **kwargs):
408381

409382
request = self.filter_request(endpoint_context, request)
410383

411-
try:
412-
_cinfo = endpoint_context.cdb[client_id]
413-
except KeyError:
384+
_cinfo = endpoint_context.cdb.get(client_id)
385+
if not _cinfo:
414386
LOGGER.error(
415387
"Client ID ({}) not in client database".format(request["client_id"])
416388
)
@@ -439,27 +411,27 @@ def _post_parse_request(self, request, client_id, endpoint_context, **kwargs):
439411
return request
440412

441413
def pick_authn_method(self, request, redirect_uri, acr=None, **kwargs):
442-
try:
443-
auth_id = kwargs["auth_method_id"]
444-
except KeyError:
445-
if acr:
446-
res = self.endpoint_context.authn_broker.pick(acr)
447-
else:
448-
res = pick_auth(self.endpoint_context, request)
449-
450-
if not res:
451-
return {
452-
"error": "access_denied",
453-
"error_description": "ACR I do not support",
454-
"return_uri": redirect_uri,
455-
"return_type": request["response_type"],
456-
}
414+
auth_id = kwargs.get("auth_method_id")
415+
if auth_id:
416+
return self.endpoint_context.authn_broker[auth_id]
417+
418+
if acr:
419+
res = self.endpoint_context.authn_broker.pick(acr)
457420
else:
458-
res = self.endpoint_context.authn_broker[auth_id]
421+
res = pick_auth(self.endpoint_context, request)
459422

460-
return res
461-
462-
def setup_auth(self, request, redirect_uri, cinfo, cookie, acr=None, **kwargs):
423+
if res:
424+
return res
425+
else:
426+
return {
427+
"error": "access_denied",
428+
"error_description": "ACR I do not support",
429+
"return_uri": redirect_uri,
430+
"return_type": request["response_type"],
431+
}
432+
433+
def setup_auth(self, request, redirect_uri,
434+
cinfo, cookie, acr=None, **kwargs):
463435
"""
464436
465437
:param request: The authorization/authentication request
@@ -477,11 +449,7 @@ def setup_auth(self, request, redirect_uri, cinfo, cookie, acr=None, **kwargs):
477449
authn_class_ref = res["acr"]
478450

479451
try:
480-
try:
481-
_auth_info = kwargs["authn"]
482-
except KeyError:
483-
_auth_info = ""
484-
452+
_auth_info = kwargs.get("authn", "")
485453
if "upm_answer" in request and request["upm_answer"] == "true":
486454
_max_age = 0
487455
else:
@@ -516,7 +484,8 @@ def setup_auth(self, request, redirect_uri, cinfo, cookie, acr=None, **kwargs):
516484
elif "revoked" in session:
517485
identity = None
518486

519-
authn_args = authn_args_gather(request, authn_class_ref, cinfo, **kwargs)
487+
authn_args = authn_args_gather(request, authn_class_ref,
488+
cinfo, **kwargs)
520489

521490
# To authenticate or Not
522491
if identity is None: # No!
@@ -563,12 +532,13 @@ def setup_auth(self, request, redirect_uri, cinfo, cookie, acr=None, **kwargs):
563532
authn_info=authn_class_ref,
564533
time_stamp=_ts,
565534
)
566-
try:
567-
authn_event["valid_until"] = time.time() + authn.kwargs["expires_in"]
568-
except KeyError:
569-
pass
535+
if "valid_until" in authn_event:
536+
vu = time.time() + authn.kwargs.get("expires_in", 0.0)
537+
authn_event["valid_until"] = vu
570538

571-
return {"authn_event": authn_event, "identity": identity, "user": user}
539+
return {"authn_event": authn_event,
540+
"identity": identity,
541+
"user": user}
572542

573543
def aresp_check(self, aresp, request):
574544
return ""
@@ -710,9 +680,7 @@ def authz_part2(self, user, authn_event, request, **kwargs):
710680
if "check_session_iframe" in self.endpoint_context.provider_info:
711681
ec = self.endpoint_context
712682
salt = rndstr()
713-
if ec.sdb.is_session_revoked(sid):
714-
pass
715-
else:
683+
if not ec.sdb.is_session_revoked(sid):
716684
authn_event = ec.sdb.get_authentication_event(
717685
sid
718686
) # use the last session
@@ -761,21 +729,16 @@ def process_request(self, request_info=None, **kwargs):
761729

762730
_cid = request_info["client_id"]
763731
cinfo = self.endpoint_context.cdb[_cid]
764-
try:
765-
cookie = kwargs["cookie"]
766-
except KeyError:
767-
cookie = ""
768-
else:
732+
733+
cookie = kwargs.get("cookie", "")
734+
if cookie:
769735
del kwargs["cookie"]
770736

771737
if proposed_user(request_info):
772738
kwargs["req_user"] = proposed_user(request_info)
773739
else:
774-
try:
740+
if request_info.get("login_hint"):
775741
_login_hint = request_info["login_hint"]
776-
except KeyError:
777-
pass
778-
else:
779742
if self.endpoint_context.login_hint_lookup:
780743
kwargs["req_user"] = self.endpoint_context.login_hint_lookup[
781744
_login_hint
@@ -788,24 +751,22 @@ def process_request(self, request_info=None, **kwargs):
788751
if "error" in info:
789752
return info
790753

791-
try:
792-
_function = info["function"]
793-
except KeyError: # already authenticated
754+
_function = info.get("function")
755+
if not _function:
794756
LOGGER.debug("- authenticated -")
795757
LOGGER.debug("AREQ keys: %s" % request_info.keys())
796-
797758
res = self.authz_part2(
798-
info["user"], info["authn_event"], request_info, cookie=cookie
759+
info["user"], info["authn_event"],
760+
request_info, cookie=cookie
799761
)
800-
801762
return res
802-
else:
803-
try:
804-
# Run the authentication function
805-
return {
806-
"http_response": _function(**info["args"]),
807-
"return_uri": request_info["redirect_uri"],
808-
}
809-
except Exception as err:
810-
LOGGER.exception(err)
811-
return {"http_response": "Internal error: {}".format(err)}
763+
764+
try:
765+
# Run the authentication function
766+
return {
767+
"http_response": _function(**info["args"]),
768+
"return_uri": request_info["redirect_uri"],
769+
}
770+
except Exception as err:
771+
LOGGER.exception(err)
772+
return {"http_response": "Internal error: {}".format(err)}

0 commit comments

Comments
 (0)