Skip to content

Commit a964f51

Browse files
author
Ric Janus Sapasap
committed
Apply black to src/satosa
1 parent 049c70d commit a964f51

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+1816
-968
lines changed

src/satosa/attribute_mapping.py

Lines changed: 65 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ def scope(s):
1414
:param s: string to extract scope from (filtered string in mako template)
1515
:return: the scope
1616
"""
17-
if '@' not in s:
17+
if "@" not in s:
1818
raise ValueError("Unscoped string")
19-
(local_part, _, domain_part) = s.partition('@')
19+
(local_part, _, domain_part) = s.partition("@")
2020
return domain_part
2121

2222

@@ -31,16 +31,22 @@ def __init__(self, internal_attributes):
3131
:param internal_attributes: A map of how to convert the attributes
3232
(dict[internal_name, dict[attribute_profile, external_name]])
3333
"""
34-
self.separator = "." # separator for nested attribute values, e.g. address.street_address
35-
self.multivalue_separator = ";" # separates multiple values, e.g. when using templates
34+
self.separator = (
35+
"." # separator for nested attribute values, e.g. address.street_address
36+
)
37+
self.multivalue_separator = (
38+
";" # separates multiple values, e.g. when using templates
39+
)
3640
self.from_internal_attributes = internal_attributes["attributes"]
3741
self.template_attributes = internal_attributes.get("template_attributes", None)
3842

3943
self.to_internal_attributes = defaultdict(dict)
4044
for internal_attribute_name, mappings in self.from_internal_attributes.items():
4145
for profile, external_attribute_names in mappings.items():
4246
for external_attribute_name in external_attribute_names:
43-
self.to_internal_attributes[profile][external_attribute_name] = internal_attribute_name
47+
self.to_internal_attributes[profile][
48+
external_attribute_name
49+
] = internal_attribute_name
4450

4551
def to_internal_filter(self, attribute_profile, external_attribute_names):
4652
"""
@@ -59,7 +65,11 @@ def to_internal_filter(self, attribute_profile, external_attribute_names):
5965
try:
6066
profile_mapping = self.to_internal_attributes[attribute_profile]
6167
except KeyError:
62-
logline = "no attribute mapping found for the given attribute profile {}".format(attribute_profile)
68+
logline = (
69+
"no attribute mapping found for the given attribute profile {}".format(
70+
attribute_profile
71+
)
72+
)
6373
logger.warn(logline)
6474
# no attributes since the given profile is not configured
6575
return []
@@ -103,7 +113,9 @@ def to_internal(self, attribute_profile, external_dict):
103113
)
104114
if attribute_values: # Only insert key if it has some values
105115
logline = "backend attribute {external} mapped to {internal} ({value})".format(
106-
external=external_attribute_name, internal=internal_attribute_name, value=attribute_values
116+
external=external_attribute_name,
117+
internal=internal_attribute_name,
118+
value=attribute_values,
107119
)
108120
logger.debug(logline)
109121
internal_dict[internal_attribute_name] = attribute_values
@@ -112,7 +124,9 @@ def to_internal(self, attribute_profile, external_dict):
112124
external_attribute_name
113125
)
114126
logger.debug(logline)
115-
internal_dict = self._handle_template_attributes(attribute_profile, internal_dict)
127+
internal_dict = self._handle_template_attributes(
128+
attribute_profile, internal_dict
129+
)
116130
return internal_dict
117131

118132
def _collate_attribute_values_by_priority_order(self, attribute_names, data):
@@ -128,7 +142,11 @@ def _collate_attribute_values_by_priority_order(self, attribute_names, data):
128142
return result
129143

130144
def _render_attribute_template(self, template, data):
131-
t = Template(template, cache_enabled=True, imports=["from satosa.attribute_mapping import scope"])
145+
t = Template(
146+
template,
147+
cache_enabled=True,
148+
imports=["from satosa.attribute_mapping import scope"],
149+
)
132150
try:
133151
return t.render(**data).split(self.multivalue_separator)
134152
except (NameError, TypeError):
@@ -144,11 +162,19 @@ def _handle_template_attributes(self, attribute_profile, internal_dict):
144162
continue
145163

146164
external_attribute_name = mapping[attribute_profile]
147-
templates = [t for t in external_attribute_name if "$" in t] # these looks like templates...
148-
template_attribute_values = [self._render_attribute_template(template, internal_dict) for template in
149-
templates]
150-
flattened_attribute_values = list(chain.from_iterable(template_attribute_values))
151-
attribute_values = flattened_attribute_values or internal_dict.get(internal_attribute_name, None)
165+
templates = [
166+
t for t in external_attribute_name if "$" in t
167+
] # these looks like templates...
168+
template_attribute_values = [
169+
self._render_attribute_template(template, internal_dict)
170+
for template in templates
171+
]
172+
flattened_attribute_values = list(
173+
chain.from_iterable(template_attribute_values)
174+
)
175+
attribute_values = flattened_attribute_values or internal_dict.get(
176+
internal_attribute_name, None
177+
)
152178
if attribute_values: # only insert key if it has some values
153179
internal_dict[internal_attribute_name] = attribute_values
154180

@@ -172,7 +198,9 @@ def _create_nested_attribute_value(self, nested_attribute_names, value):
172198
return {nested_attribute_names[0]: value}
173199

174200
# keep digging further into the nested attribute names
175-
child_dict = self._create_nested_attribute_value(nested_attribute_names[1:], value)
201+
child_dict = self._create_nested_attribute_value(
202+
nested_attribute_names[1:], value
203+
)
176204
return {nested_attribute_names[0]: child_dict}
177205

178206
def from_internal(self, attribute_profile, internal_dict):
@@ -190,10 +218,14 @@ def from_internal(self, attribute_profile, internal_dict):
190218
external_dict = {}
191219
for internal_attribute_name in internal_dict:
192220
try:
193-
attribute_mapping = self.from_internal_attributes[internal_attribute_name]
194-
except KeyError:
195-
logline = "no attribute mapping found for the internal attribute {}".format(
221+
attribute_mapping = self.from_internal_attributes[
196222
internal_attribute_name
223+
]
224+
except KeyError:
225+
logline = (
226+
"no attribute mapping found for the internal attribute {}".format(
227+
internal_attribute_name
228+
)
197229
)
198230
logger.debug(logline)
199231
continue
@@ -206,20 +238,29 @@ def from_internal(self, attribute_profile, internal_dict):
206238
logger.debug(logline)
207239
continue
208240

209-
external_attribute_names = self.from_internal_attributes[internal_attribute_name][attribute_profile]
241+
external_attribute_names = self.from_internal_attributes[
242+
internal_attribute_name
243+
][attribute_profile]
210244
# select the first attribute name
211245
external_attribute_name = external_attribute_names[0]
212-
logline = "frontend attribute {external} mapped from {internal} ({value})".format(
213-
external=external_attribute_name, internal=internal_attribute_name, value=internal_dict[internal_attribute_name]
246+
logline = (
247+
"frontend attribute {external} mapped from {internal} ({value})".format(
248+
external=external_attribute_name,
249+
internal=internal_attribute_name,
250+
value=internal_dict[internal_attribute_name],
251+
)
214252
)
215253
logger.debug(logline)
216254

217255
if self.separator in external_attribute_name:
218256
nested_attribute_names = external_attribute_name.split(self.separator)
219-
nested_dict = self._create_nested_attribute_value(nested_attribute_names[1:],
220-
internal_dict[internal_attribute_name])
257+
nested_dict = self._create_nested_attribute_value(
258+
nested_attribute_names[1:], internal_dict[internal_attribute_name]
259+
)
221260
external_dict[nested_attribute_names[0]] = nested_dict
222261
else:
223-
external_dict[external_attribute_name] = internal_dict[internal_attribute_name]
262+
external_dict[external_attribute_name] = internal_dict[
263+
internal_attribute_name
264+
]
224265

225266
return external_dict

src/satosa/backends/apple.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
Apple backend module.
33
"""
4+
45
import logging
56
from .openid_connect import OpenIDConnectBackend, STATE_KEY
67
from oic.oauth2.message import Message

src/satosa/backends/bitbucket.py

Lines changed: 37 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
OAuth backend for BitBucket
33
"""
4+
45
import json
56
import logging
67
import requests
@@ -37,10 +38,17 @@ def __init__(self, outgoing, internal_attributes, config, base_url, name):
3738
:type base_url: str
3839
:type name: str
3940
"""
40-
config.setdefault('response_type', 'code')
41-
config['verify_accesstoken_state'] = False
42-
super().__init__(outgoing, internal_attributes, config, base_url,
43-
name, 'bitbucket', 'account_id')
41+
config.setdefault("response_type", "code")
42+
config["verify_accesstoken_state"] = False
43+
super().__init__(
44+
outgoing,
45+
internal_attributes,
46+
config,
47+
base_url,
48+
name,
49+
"bitbucket",
50+
"account_id",
51+
)
4452

4553
def get_request_args(self, get_state=stateID):
4654
request_args = super().get_request_args(get_state=get_state)
@@ -58,28 +66,36 @@ def get_request_args(self, get_state=stateID):
5866

5967
def auth_info(self, request):
6068
return AuthenticationInformation(
61-
UNSPECIFIED, None,
62-
self.config['server_info']['authorization_endpoint'])
69+
UNSPECIFIED, None, self.config["server_info"]["authorization_endpoint"]
70+
)
6371

6472
def user_information(self, access_token):
65-
url = self.config['server_info']['user_endpoint']
73+
url = self.config["server_info"]["user_endpoint"]
6674
email_url = "{}/emails".format(url)
67-
headers = {'Authorization': 'Bearer {}'.format(access_token)}
75+
headers = {"Authorization": "Bearer {}".format(access_token)}
6876
resp = requests.get(url, headers=headers)
6977
data = json.loads(resp.text)
70-
if 'email' in self.config['scope']:
78+
if "email" in self.config["scope"]:
7179
resp = requests.get(email_url, headers=headers)
7280
emails = json.loads(resp.text)
73-
data.update({
74-
'email': [e for e in [d.get('email')
75-
for d in emails.get('values')
76-
if d.get('is_primary')
77-
]
78-
],
79-
'email_confirmed': [e for e in [d.get('email')
80-
for d in emails.get('values')
81-
if d.get('is_confirmed')
82-
]
83-
]
84-
})
81+
data.update(
82+
{
83+
"email": [
84+
e
85+
for e in [
86+
d.get("email")
87+
for d in emails.get("values")
88+
if d.get("is_primary")
89+
]
90+
],
91+
"email_confirmed": [
92+
e
93+
for e in [
94+
d.get("email")
95+
for d in emails.get("values")
96+
if d.get("is_confirmed")
97+
]
98+
],
99+
}
100+
)
85101
return data

src/satosa/backends/github.py

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
OAuth backend for LinkedIn
33
"""
4+
45
import json
56
import logging
67
import requests
@@ -39,11 +40,11 @@ def __init__(self, outgoing, internal_attributes, config, base_url, name):
3940
:type base_url: str
4041
:type name: str
4142
"""
42-
config.setdefault('response_type', 'code')
43-
config['verify_accesstoken_state'] = False
43+
config.setdefault("response_type", "code")
44+
config["verify_accesstoken_state"] = False
4445
super().__init__(
45-
outgoing, internal_attributes, config, base_url, name, 'github',
46-
'id')
46+
outgoing, internal_attributes, config, base_url, name, "github", "id"
47+
)
4748

4849
def start_auth(self, context, internal_request, get_state=stateID):
4950
"""
@@ -58,53 +59,56 @@ def start_auth(self, context, internal_request, get_state=stateID):
5859
context.state[self.name] = dict(state=oauth_state)
5960

6061
request_args = dict(
61-
client_id=self.config['client_config']['client_id'],
62+
client_id=self.config["client_config"]["client_id"],
6263
redirect_uri=self.redirect_url,
6364
state=oauth_state,
64-
allow_signup=self.config.get('allow_signup', False))
65-
scope = ' '.join(self.config['scope'])
65+
allow_signup=self.config.get("allow_signup", False),
66+
)
67+
scope = " ".join(self.config["scope"])
6668
if scope:
67-
request_args['scope'] = scope
69+
request_args["scope"] = scope
6870

69-
cis = self.consumer.construct_AuthorizationRequest(
70-
request_args=request_args)
71+
cis = self.consumer.construct_AuthorizationRequest(request_args=request_args)
7172
return Redirect(cis.request(self.consumer.authorization_endpoint))
7273

7374
def auth_info(self, requrest):
7475
return AuthenticationInformation(
75-
UNSPECIFIED, None,
76-
self.config['server_info']['authorization_endpoint'])
76+
UNSPECIFIED, None, self.config["server_info"]["authorization_endpoint"]
77+
)
7778

7879
def _authn_response(self, context):
7980
state_data = context.state[self.name]
8081
aresp = self.consumer.parse_response(
81-
AuthorizationResponse, info=json.dumps(context.request))
82+
AuthorizationResponse, info=json.dumps(context.request)
83+
)
8284
self._verify_state(aresp, state_data, context.state)
83-
url = self.config['server_info']['token_endpoint']
85+
url = self.config["server_info"]["token_endpoint"]
8486
data = dict(
85-
code=aresp['code'],
87+
code=aresp["code"],
8688
redirect_uri=self.redirect_url,
87-
client_id=self.config['client_config']['client_id'],
88-
client_secret=self.config['client_secret'], )
89-
headers = {'Accept': 'application/json'}
89+
client_id=self.config["client_config"]["client_id"],
90+
client_secret=self.config["client_secret"],
91+
)
92+
headers = {"Accept": "application/json"}
9093

9194
r = requests.post(url, data=data, headers=headers)
9295
response = r.json()
93-
if self.config.get('verify_accesstoken_state', True):
96+
if self.config.get("verify_accesstoken_state", True):
9497
self._verify_state(response, state_data, context.state)
9598

9699
user_info = self.user_information(response["access_token"])
97100
auth_info = self.auth_info(context.request)
98101
internal_response = InternalData(auth_info=auth_info)
99102
internal_response.attributes = self.converter.to_internal(
100-
self.external_type, user_info)
103+
self.external_type, user_info
104+
)
101105
internal_response.subject_id = str(user_info[self.user_id_attr])
102106
return self.auth_callback_func(context, internal_response)
103107

104108
def user_information(self, access_token):
105-
url = self.config['server_info']['user_info']
106-
headers = {'Authorization': 'token {}'.format(access_token)}
109+
url = self.config["server_info"]["user_info"]
110+
headers = {"Authorization": "token {}".format(access_token)}
107111
r = requests.get(url, headers=headers)
108112
ret = r.json()
109-
ret['id'] = str(ret['id'])
113+
ret["id"] = str(ret["id"])
110114
return ret

0 commit comments

Comments
 (0)