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

Commit a3ea7e2

Browse files
committed
Authorization endpoint cosmesi
1 parent d8439ac commit a3ea7e2

1 file changed

Lines changed: 80 additions & 128 deletions

File tree

src/oidcendpoint/oidc/authorization.py

Lines changed: 80 additions & 128 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[cn].get("max_age") or request.get("max_age", 0)
7575

7676

7777
def re_authenticate(request, authn):
@@ -83,21 +83,12 @@ 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 "id_token" in request["claims"]:
87+
acrdef = request["claims"]["id_token"].get("acr")
9988

100-
return None
89+
if isinstance(acrdef, dict):
90+
values = [acrdef.get("value")] or acrdef.get("values")
91+
return values
10192

10293

10394
def verify_uri(endpoint_context, request, uri_type, client_id=None):
@@ -112,10 +103,7 @@ def verify_uri(endpoint_context, request, uri_type, client_id=None):
112103
:return: An error response if the redirect URI is faulty otherwise
113104
None
114105
"""
115-
try:
116-
_cid = request["client_id"]
117-
except KeyError:
118-
_cid = client_id
106+
_cid = request.get("client_id", client_id)
119107

120108
if not _cid:
121109
LOGGER.error("No client id found")
@@ -132,9 +120,8 @@ def verify_uri(endpoint_context, request, uri_type, client_id=None):
132120
_query = parse_qs(_query)
133121

134122
match = False
135-
try:
136-
values = endpoint_context.cdb[_cid]["{}s".format(uri_type)]
137-
except KeyError:
123+
values = endpoint_context.cdb[_cid].get("{}s".format(uri_type))
124+
if not values:
138125
raise ValueError("No registered {}".format(uri_type))
139126
else:
140127
for regbase, rquery in values:
@@ -229,16 +216,12 @@ def authn_args_gather(request, authn_class_ref, cinfo, **kwargs):
229216
authn_args["as_user"] = (kwargs["req_user"],)
230217

231218
for attr in ["policy_uri", "logo_uri", "tos_uri"]:
232-
try:
219+
if cinfo.get(attr):
233220
authn_args[attr] = cinfo[attr]
234-
except KeyError:
235-
pass
236221

237222
for attr in ["ui_locales", "acr_values", "login_hint"]:
238-
try:
223+
if request.get(attr):
239224
authn_args[attr] = request[attr]
240-
except KeyError:
241-
pass
242225

243226
return authn_args
244227

@@ -253,28 +236,24 @@ def create_authn_response(endpoint, request, sid):
253236
"""
254237
# create the response
255238
aresp = AuthorizationResponse()
256-
try:
239+
if request.get("state"):
257240
aresp["state"] = request["state"]
258-
except KeyError:
259-
pass
260241

261242
if "response_type" in request and request["response_type"] == ["none"]:
262243
fragment_enc = False
263244
else:
264245
_context = endpoint.endpoint_context
265246
_sinfo = _context.sdb[sid]
266247

267-
try:
248+
if request.get("scope"):
268249
aresp["scope"] = request["scope"]
269-
except KeyError:
270-
pass
271250

272251
rtype = set(request["response_type"][:])
273252
handled_response_type = []
253+
254+
fragment_enc = True
274255
if len(rtype) == 1 and "code" in rtype:
275256
fragment_enc = False
276-
else:
277-
fragment_enc = True
278257

279258
if "code" in request["response_type"]:
280259
_code = aresp["code"] = _context.sdb[sid]["code"]
@@ -293,11 +272,8 @@ def create_authn_response(endpoint, request, sid):
293272

294273
handled_response_type.append("token")
295274

296-
try:
297-
_access_token = aresp["access_token"]
298-
except KeyError:
299-
_access_token = None
300-
275+
_access_token = aresp.get("access_token", None)
276+
301277
if "id_token" in request["response_type"]:
302278
kwargs = {}
303279
if {"code", "id_token", "token"}.issubset(rtype):
@@ -335,14 +311,8 @@ def create_authn_response(endpoint, request, sid):
335311

336312

337313
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")
314+
cn = verified_claim_name("it_token_hint")
315+
return request[cn].get("sub", "")
346316

347317

348318
class Authorization(Endpoint):
@@ -381,9 +351,9 @@ def filter_request(self, endpoint_context, req):
381351

382352
def verify_response_type(self, request, cinfo):
383353
# Checking response types
384-
try:
385-
_registered = [set(rt.split(" ")) for rt in cinfo["response_types"]]
386-
except KeyError:
354+
_registered = [set(rt.split(" "))
355+
for rt in cinfo.get("response_types", [])]
356+
if not _registered:
387357
# If no response_type is registered by the client then we'll
388358
# code which it the default according to the OIDC spec.
389359
_registered = [{"code"}]
@@ -408,9 +378,8 @@ def _post_parse_request(self, request, client_id, endpoint_context, **kwargs):
408378

409379
request = self.filter_request(endpoint_context, request)
410380

411-
try:
412-
_cinfo = endpoint_context.cdb[client_id]
413-
except KeyError:
381+
_cinfo = endpoint_context.cdb.get(client_id)
382+
if not _cinfo:
414383
LOGGER.error(
415384
"Client ID ({}) not in client database".format(request["client_id"])
416385
)
@@ -439,27 +408,27 @@ def _post_parse_request(self, request, client_id, endpoint_context, **kwargs):
439408
return request
440409

441410
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-
}
411+
auth_id = kwargs.get("auth_method_id")
412+
if auth_id:
413+
return self.endpoint_context.authn_broker[auth_id]
414+
415+
if acr:
416+
res = self.endpoint_context.authn_broker.pick(acr)
457417
else:
458-
res = self.endpoint_context.authn_broker[auth_id]
459-
460-
return res
418+
res = pick_auth(self.endpoint_context, request)
461419

462-
def setup_auth(self, request, redirect_uri, cinfo, cookie, acr=None, **kwargs):
420+
if res:
421+
return res
422+
else:
423+
return {
424+
"error": "access_denied",
425+
"error_description": "ACR I do not support",
426+
"return_uri": redirect_uri,
427+
"return_type": request["response_type"],
428+
}
429+
430+
def setup_auth(self, request, redirect_uri,
431+
cinfo, cookie, acr=None, **kwargs):
463432
"""
464433
465434
:param request: The authorization/authentication request
@@ -477,11 +446,7 @@ def setup_auth(self, request, redirect_uri, cinfo, cookie, acr=None, **kwargs):
477446
authn_class_ref = res["acr"]
478447

479448
try:
480-
try:
481-
_auth_info = kwargs["authn"]
482-
except KeyError:
483-
_auth_info = ""
484-
449+
_auth_info = kwargs.get("authn", "")
485450
if "upm_answer" in request and request["upm_answer"] == "true":
486451
_max_age = 0
487452
else:
@@ -506,17 +471,12 @@ def setup_auth(self, request, redirect_uri, cinfo, cookie, acr=None, **kwargs):
506471
else:
507472
identity = json.loads(as_unicode(_id))
508473

509-
try:
510-
session = self.endpoint_context.sdb[identity["sid"]]
511-
except KeyError:
474+
session = self.endpoint_context.sdb.get(identity["sid"])
475+
if not session or "revoked" in session:
512476
identity = None
513-
else:
514-
if session is None:
515-
identity = None
516-
elif "revoked" in session:
517-
identity = None
518477

519-
authn_args = authn_args_gather(request, authn_class_ref, cinfo, **kwargs)
478+
authn_args = authn_args_gather(request, authn_class_ref,
479+
cinfo, **kwargs)
520480

521481
# To authenticate or Not
522482
if identity is None: # No!
@@ -563,12 +523,13 @@ def setup_auth(self, request, redirect_uri, cinfo, cookie, acr=None, **kwargs):
563523
authn_info=authn_class_ref,
564524
time_stamp=_ts,
565525
)
566-
try:
567-
authn_event["valid_until"] = time.time() + authn.kwargs["expires_in"]
568-
except KeyError:
569-
pass
526+
if "valid_until" in authn_event:
527+
vu = time.time() + authn.kwargs.get("expires_in", 0.0)
528+
authn_event["valid_until"] = vu
570529

571-
return {"authn_event": authn_event, "identity": identity, "user": user}
530+
return {"authn_event": authn_event,
531+
"identity": identity,
532+
"user": user}
572533

573534
def aresp_check(self, aresp, request):
574535
return ""
@@ -710,9 +671,7 @@ def authz_part2(self, user, authn_event, request, **kwargs):
710671
if "check_session_iframe" in self.endpoint_context.provider_info:
711672
ec = self.endpoint_context
712673
salt = rndstr()
713-
if ec.sdb.is_session_revoked(sid):
714-
pass
715-
else:
674+
if not ec.sdb.is_session_revoked(sid):
716675
authn_event = ec.sdb.get_authentication_event(
717676
sid
718677
) # use the last session
@@ -761,21 +720,16 @@ def process_request(self, request_info=None, **kwargs):
761720

762721
_cid = request_info["client_id"]
763722
cinfo = self.endpoint_context.cdb[_cid]
764-
try:
765-
cookie = kwargs["cookie"]
766-
except KeyError:
767-
cookie = ""
768-
else:
723+
724+
cookie = kwargs.get("cookie", "")
725+
if cookie:
769726
del kwargs["cookie"]
770727

771728
if proposed_user(request_info):
772729
kwargs["req_user"] = proposed_user(request_info)
773730
else:
774-
try:
731+
if request_info.get("login_hint"):
775732
_login_hint = request_info["login_hint"]
776-
except KeyError:
777-
pass
778-
else:
779733
if self.endpoint_context.login_hint_lookup:
780734
kwargs["req_user"] = self.endpoint_context.login_hint_lookup[
781735
_login_hint
@@ -788,24 +742,22 @@ def process_request(self, request_info=None, **kwargs):
788742
if "error" in info:
789743
return info
790744

791-
try:
792-
_function = info["function"]
793-
except KeyError: # already authenticated
745+
_function = info.get("function")
746+
if not _function:
794747
LOGGER.debug("- authenticated -")
795748
LOGGER.debug("AREQ keys: %s" % request_info.keys())
796-
797749
res = self.authz_part2(
798-
info["user"], info["authn_event"], request_info, cookie=cookie
750+
info["user"], info["authn_event"],
751+
request_info, cookie=cookie
799752
)
800-
801753
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)}
754+
755+
try:
756+
# Run the authentication function
757+
return {
758+
"http_response": _function(**info["args"]),
759+
"return_uri": request_info["redirect_uri"],
760+
}
761+
except Exception as err:
762+
LOGGER.exception(err)
763+
return {"http_response": "Internal error: {}".format(err)}

0 commit comments

Comments
 (0)