all: implement black as code formatter

This commit is contained in:
Jens Langhammer
2019-12-31 12:51:16 +01:00
parent 8eb3f0f708
commit 3bd1eadd51
298 changed files with 4825 additions and 3145 deletions

View File

@ -24,9 +24,12 @@ class Connector:
def bind(self):
"""Bind using Source's Credentials"""
self._connection = ldap3.Connection(self._server, raise_exceptions=True,
user=self._source.bind_cn,
password=self._source.bind_password)
self._connection = ldap3.Connection(
self._server,
raise_exceptions=True,
user=self._source.bind_cn,
password=self._source.bind_password,
)
self._connection.bind()
if self._source.start_tls:
@ -35,17 +38,17 @@ class Connector:
@staticmethod
def encode_pass(password: str) -> bytes:
"""Encodes a plain-text password so it can be used by AD"""
return '"{}"'.format(password).encode('utf-16-le')
return '"{}"'.format(password).encode("utf-16-le")
@property
def base_dn_users(self) -> str:
"""Shortcut to get full base_dn for user lookups"""
return ','.join([self._source.additional_user_dn, self._source.base_dn])
return ",".join([self._source.additional_user_dn, self._source.base_dn])
@property
def base_dn_groups(self) -> str:
"""Shortcut to get full base_dn for group lookups"""
return ','.join([self._source.additional_group_dn, self._source.base_dn])
return ",".join([self._source.additional_group_dn, self._source.base_dn])
def sync_groups(self):
"""Iterate over all LDAP Groups and create passbook_core.Group instances"""
@ -56,22 +59,29 @@ class Connector:
search_base=self.base_dn_groups,
search_filter=self._source.group_object_filter,
search_scope=ldap3.SUBTREE,
attributes=ldap3.ALL_ATTRIBUTES)
attributes=ldap3.ALL_ATTRIBUTES,
)
for group in groups:
attributes = group.get('attributes', {})
attributes = group.get("attributes", {})
_, created = Group.objects.update_or_create(
attributes__ldap_uniq=attributes.get(self._source.object_uniqueness_field, ''),
attributes__ldap_uniq=attributes.get(
self._source.object_uniqueness_field, ""
),
parent=self._source.sync_parent_group,
# defaults=self._build_object_properties(attributes),
defaults={
'name': attributes.get('name', ''),
'attributes': {
'ldap_uniq': attributes.get(self._source.object_uniqueness_field, ''),
'distinguishedName': attributes.get('distinguishedName')
}
}
"name": attributes.get("name", ""),
"attributes": {
"ldap_uniq": attributes.get(
self._source.object_uniqueness_field, ""
),
"distinguishedName": attributes.get("distinguishedName"),
},
},
)
LOGGER.debug(
"Synced group", group=attributes.get("name", ""), created=created
)
LOGGER.debug("Synced group", group=attributes.get('name', ''), created=created)
def sync_users(self):
"""Iterate over all LDAP Users and create passbook_core.User instances"""
@ -79,17 +89,22 @@ class Connector:
search_base=self.base_dn_users,
search_filter=self._source.user_object_filter,
search_scope=ldap3.SUBTREE,
attributes=ldap3.ALL_ATTRIBUTES)
attributes=ldap3.ALL_ATTRIBUTES,
)
for user in users:
attributes = user.get('attributes', {})
attributes = user.get("attributes", {})
user, created = User.objects.update_or_create(
attributes__ldap_uniq=attributes.get(self._source.object_uniqueness_field, ''),
attributes__ldap_uniq=attributes.get(
self._source.object_uniqueness_field, ""
),
defaults=self._build_object_properties(attributes),
)
if created:
user.set_unusable_password()
user.save()
LOGGER.debug("Synced User", user=attributes.get('name', ''), created=created)
LOGGER.debug(
"Synced User", user=attributes.get("name", ""), created=created
)
def sync_membership(self):
"""Iterate over all Users and assign Groups using memberOf Field"""
@ -99,21 +114,31 @@ class Connector:
search_scope=ldap3.SUBTREE,
attributes=[
self._source.user_group_membership_field,
self._source.object_uniqueness_field])
self._source.object_uniqueness_field,
],
)
group_cache: Dict[str, Group] = {}
for user in users:
member_of = user.get('attributes', {}).get(self._source.user_group_membership_field, [])
uniq = user.get('attributes', {}).get(self._source.object_uniqueness_field, [])
member_of = user.get("attributes", {}).get(
self._source.user_group_membership_field, []
)
uniq = user.get("attributes", {}).get(
self._source.object_uniqueness_field, []
)
for group_dn in member_of:
# Check if group_dn is within our base_dn_groups, and skip if not
if not group_dn.endswith(self.base_dn_groups):
continue
# Check if we fetched the group already, and if not cache it for later
if group_dn not in group_cache:
groups = Group.objects.filter(attributes__distinguishedName=group_dn)
groups = Group.objects.filter(
attributes__distinguishedName=group_dn
)
if not groups.exists():
LOGGER.warning("Group does not exist in our DB yet, run sync_groups first.",
group=group_dn)
LOGGER.warning(
"Group does not exist in our DB yet, run sync_groups first.",
group=group_dn,
)
return
group_cache[group_dn] = groups.first()
group = group_cache[group_dn]
@ -124,16 +149,19 @@ class Connector:
group.save()
LOGGER.debug("Successfully updated group membership")
def _build_object_properties(self, attributes: Dict[str, Any]) -> Dict[str, Dict[Any, Any]]:
properties = {
'attributes': {}
}
def _build_object_properties(
self, attributes: Dict[str, Any]
) -> Dict[str, Dict[Any, Any]]:
properties = {"attributes": {}}
for mapping in self._source.property_mappings.all().select_subclasses():
properties[mapping.object_field] = attributes.get(mapping.ldap_property, '')
properties[mapping.object_field] = attributes.get(mapping.ldap_property, "")
if self._source.object_uniqueness_field in attributes:
properties['attributes']['ldap_uniq'] = \
attributes.get(self._source.object_uniqueness_field)
properties['attributes']['distinguishedName'] = attributes.get('distinguishedName')
properties["attributes"]["ldap_uniq"] = attributes.get(
self._source.object_uniqueness_field
)
properties["attributes"]["distinguishedName"] = attributes.get(
"distinguishedName"
)
return properties
def auth_user(self, password: str, **filters: Dict[str, str]) -> Optional[User]:
@ -143,8 +171,10 @@ class Connector:
if not users.exists():
return None
user: User = users.first()
if 'distinguishedName' not in user.attributes:
LOGGER.debug("User doesn't have DN set, assuming not LDAP imported.", user=user)
if "distinguishedName" not in user.attributes:
LOGGER.debug(
"User doesn't have DN set, assuming not LDAP imported.", user=user
)
return None
# Either has unusable password,
# or has a password, but couldn't be authenticated by ModelBackend.
@ -165,9 +195,12 @@ class Connector:
# Try to bind as new user
LOGGER.debug("Attempting Binding as user", user=user)
try:
temp_connection = ldap3.Connection(self._server,
user=user.attributes.get('distinguishedName'),
password=password, raise_exceptions=True)
temp_connection = ldap3.Connection(
self._server,
user=user.attributes.get("distinguishedName"),
password=password,
raise_exceptions=True,
)
temp_connection.bind()
return user
except ldap3.core.exceptions.LDAPInvalidCredentialsResult as exception: