Skip to content

Commit 3a252c9

Browse files
committed
chore: small code linting
1 parent 883004e commit 3a252c9

File tree

4 files changed

+35
-21
lines changed

4 files changed

+35
-21
lines changed

djangosaml2/backends.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ def authenticate(self, request, session_info=None, attribute_mapping=None, creat
140140
if user is not None:
141141
user = self._update_user(
142142
user, attributes, attribute_mapping, force_save=created)
143-
143+
144144
if self.user_can_authenticate(user):
145145
return user
146146

djangosaml2/conf.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,12 @@ def config_settings_loader(request: Optional[HttpRequest] = None) -> SPConfig:
5151
return conf
5252

5353

54-
def get_config(config_loader_path: Optional[Union[Callable, str]] = None, request: Optional[HttpRequest] = None) -> SPConfig:
55-
""" Load a config_loader function if necessary, and call that function with the request as argument.
56-
If the config_loader_path is a callable instead of a string, no importing is necessary and it will be used directly.
54+
def get_config(config_loader_path: Optional[Union[Callable, str]] = None,
55+
request: Optional[HttpRequest] = None) -> SPConfig:
56+
""" Load a config_loader function if necessary, and call that
57+
function with the request as argument.
58+
If the config_loader_path is a callable instead of a string,
59+
no importing is necessary and it will be used directly.
5760
Return the resulting SPConfig.
5861
"""
5962
config_loader_path = config_loader_path or get_custom_setting(

djangosaml2/utils.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -104,23 +104,25 @@ def saml2_from_httpredirect_request(url):
104104

105105

106106
def get_session_id_from_saml2(saml2_xml):
107-
saml2_xml = saml2_xml.encode() if isinstance(saml2_xml, str) else saml2_xml
108-
return re.findall(b'ID="([a-z0-9\-]*)"', saml2_xml, re.I)[0].decode()
107+
saml2_xml = saml2_xml.decode() if isinstance(saml2_xml, bytes) else saml2_xml
108+
return re.findall(r'ID="([a-z0-9\-]*)"', saml2_xml, re.I)[0]
109109

110110

111111
def get_subject_id_from_saml2(saml2_xml):
112112
saml2_xml = saml2_xml if isinstance(saml2_xml, str) else saml2_xml.decode()
113113
re.findall('">([a-z0-9]+)</saml:NameID>', saml2_xml)[0]
114114

115-
def add_param_in_url(url:str, param_key:str, param_value:str):
115+
116+
def add_param_in_url(url: str, param_key: str, param_value: str):
116117
params = list(url.split('?'))
117118
params.append(f'{param_key}={param_value}')
118-
new_url = params[0] + '?' +''.join(params[1:])
119+
new_url = params[0] + '?' + ''.join(params[1:])
119120
return new_url
120121

122+
121123
def add_idp_hinting(request, http_response) -> bool:
122124
idphin_param = getattr(settings, 'SAML2_IDPHINT_PARAM', 'idphint')
123-
params = urllib.parse.urlencode(request.GET)
125+
urllib.parse.urlencode(request.GET)
124126

125127
if idphin_param not in request.GET.keys():
126128
return False

djangosaml2/views.py

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,6 @@
4646
from saml2.samlp import AuthnRequest
4747
from saml2.sigver import MissingKey
4848
from saml2.validate import ResponseLifetimeExceed, ToEarly
49-
from saml2.xmldsig import ( # support for SHA1 is required by spec
50-
SIG_RSA_SHA1, SIG_RSA_SHA256)
5149

5250
from .cache import IdentityCache, OutstandingQueriesCache, StateCache
5351
from .conf import get_config
@@ -160,6 +158,8 @@ def get(self, request, *args, **kwargs):
160158
configured_idps = available_idps(conf)
161159
selected_idp = request.GET.get('idp', None)
162160

161+
sso_kwargs = {}
162+
163163
# Do we have a Discovery Service?
164164
if not selected_idp:
165165
discovery_service = getattr(settings, 'SAML2_DISCO_URL', None)
@@ -193,7 +193,8 @@ def get(self, request, *args, **kwargs):
193193
selected_idp = list(configured_idps.keys())[0]
194194

195195
# choose a binding to try first
196-
binding = getattr(settings, 'SAML_DEFAULT_BINDING', saml2.BINDING_HTTP_POST)
196+
binding = getattr(settings, 'SAML_DEFAULT_BINDING',
197+
saml2.BINDING_HTTP_POST)
197198
logger.debug(f'Trying binding {binding} for IDP {selected_idp}')
198199

199200
# ensure our selected binding is supported by the IDP
@@ -225,18 +226,17 @@ def get(self, request, *args, **kwargs):
225226
)
226227

227228
client = Saml2Client(conf)
228-
http_response = None
229229

230230
# SSO options
231231
sign_requests = getattr(conf, '_sp_authn_requests_signed', False)
232-
sso_kwargs = {}
232+
233233
if sign_requests:
234234
sso_kwargs["sigalg"] = settings.SAML_CONFIG['service']['sp']\
235235
.get('signing_algorithm',
236236
saml2.xmldsig.SIG_RSA_SHA256)
237237
sso_kwargs["digest_alg"] = settings.SAML_CONFIG['service']['sp']\
238-
.get('digest_algorithm',
239-
saml2.xmldsig.DIGEST_SHA256)
238+
.get('digest_algorithm',
239+
saml2.xmldsig.DIGEST_SHA256)
240240

241241
# pysaml needs a string otherwise: "cannot serialize True (type bool)"
242242
if getattr(conf, '_sp_force_authn', False):
@@ -249,6 +249,8 @@ def get(self, request, *args, **kwargs):
249249

250250
logger.debug(f'Redirecting user to the IdP via {binding} binding.')
251251
_msg = 'Unable to know which IdP to use'
252+
http_response = None
253+
252254
if binding == saml2.BINDING_HTTP_REDIRECT:
253255
try:
254256
session_id, result = client.prepare_for_authenticate(
@@ -260,6 +262,7 @@ def get(self, request, *args, **kwargs):
260262
return HttpResponse(_msg)
261263
else:
262264
http_response = HttpResponseRedirect(get_location(result))
265+
263266
elif binding == saml2.BINDING_HTTP_POST:
264267
if self.post_binding_form_template:
265268
# get request XML to build our own html based on the template
@@ -268,10 +271,12 @@ def get(self, request, *args, **kwargs):
268271
except TypeError as e:
269272
logger.error(f'{_msg}: {e}')
270273
return HttpResponse(_msg)
274+
271275
session_id, request_xml = client.create_authn_request(
272276
location,
273277
binding=binding,
274-
**sso_kwargs)
278+
**sso_kwargs
279+
)
275280
try:
276281
if isinstance(request_xml, AuthnRequest):
277282
# request_xml will be an instance of AuthnRequest if the message is not signed
@@ -287,14 +292,16 @@ def get(self, request, *args, **kwargs):
287292
},
288293
})
289294
except TemplateDoesNotExist as e:
290-
logger.error(f'TemplateDoesNotExist: {e}')
295+
logger.error(
296+
f'TemplateDoesNotExist: [{self.post_binding_form_template}] - {e}'
297+
)
291298

292299
if not http_response:
293300
# use the html provided by pysaml2 if no template was specified or it doesn't exist
294301
try:
295302
session_id, result = client.prepare_for_authenticate(
296303
entityid=selected_idp, relay_state=next_path,
297-
binding=binding)
304+
binding=binding, **sso_kwargs)
298305
except TypeError as e:
299306
_msg = f"Can't prepare the authentication for {selected_idp}"
300307
logger.error(f'{_msg}: {e}')
@@ -373,7 +380,8 @@ def post(self, request, attribute_mapping=None, create_unknown_user=None):
373380
except ResponseLifetimeExceed as e:
374381
_exception = e
375382
logger.info(
376-
("SAML Assertion is no longer valid. Possibly caused by network delay or replay attack."), exc_info=True)
383+
("SAML Assertion is no longer valid. Possibly caused "
384+
"by network delay or replay attack."), exc_info=True)
377385
except SignatureError as e:
378386
_exception = e
379387
logger.info("Invalid or malformed SAML Assertion.", exc_info=True)
@@ -428,7 +436,8 @@ def post(self, request, attribute_mapping=None, create_unknown_user=None):
428436
for sc in assertion.subject.subject_confirmation:
429437
if sc.method == SCM_BEARER:
430438
assertion_not_on_or_after = sc.subject_confirmation_data.not_on_or_after
431-
assertion_info = {'assertion_id': assertion.id, 'not_on_or_after': assertion_not_on_or_after}
439+
assertion_info = {'assertion_id': assertion.id,
440+
'not_on_or_after': assertion_not_on_or_after}
432441
break
433442

434443
if callable(attribute_mapping):

0 commit comments

Comments
 (0)