Skip to content

Sourcery Starbot ⭐ refactored danyi1212/django-windowsauth #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 17 additions & 22 deletions windows_auth/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,7 @@ def check_domain(user):
return True

if user.is_authenticated and LDAPUser.objects.filter(user=user).exists():
if domain:
# for specific domain
return user.ldap.domain == domain
else:
# for all domains
return True
return user.ldap.domain == domain if domain else True
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function domain_required.check_domain refactored with the following changes:

This removes the following comments ( why? ):

# for all domains
# for specific domain

else:
return False

Expand All @@ -48,23 +43,23 @@ def ldap_sync_required(function=None, timedelta=None, login_url=None, allow_non_
:param raise_exception: raise sync exception and cause status code 500
"""
def check_sync(user):
if user.is_authenticated and LDAPUser.objects.filter(user=user).exists():
try:
if WAUTH_USE_CACHE:
user.ldap.sync()
else:
# check via database query
if not timedelta or not user.ldap.last_sync or user.ldap.last_sync < timezone.now() - timedelta:
user.ldap.sync()

return True
except Exception as e:
if raise_exception:
raise e
else:
return False
else:
if (
not user.is_authenticated
or not LDAPUser.objects.filter(user=user).exists()
):
return allow_non_ldap
try:
if WAUTH_USE_CACHE:
user.ldap.sync()
elif not timedelta or not user.ldap.last_sync or user.ldap.last_sync < timezone.now() - timedelta:
user.ldap.sync()

return True
except Exception as e:
if raise_exception:
raise e
else:
return False
Comment on lines -51 to +62
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ldap_sync_required.check_sync refactored with the following changes:

This removes the following comments ( why? ):

# check via database query


actual_decorator = user_passes_test(check_sync, login_url=login_url)
if function:
Expand Down
2 changes: 1 addition & 1 deletion windows_auth/ldap.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class LDAPManager:

def __init__(self, domain: str, settings: Optional[LDAPSettings] = None):
self.domain = domain
self.settings = settings if settings else LDAPSettings.for_domain(domain)
self.settings = settings or LDAPSettings.for_domain(domain)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LDAPManager.__init__ refactored with the following changes:

# create server
self.server = self._create_server()
# bind connection
Expand Down
10 changes: 7 additions & 3 deletions windows_auth/ldap_metrics/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,17 @@ def elapsed_time(self, obj):
return obj.elapsed_time

def bytes(self, obj):
return format_bytes(obj.bytes_received) + " / " + format_bytes(obj.bytes_transmitted)
return f'{format_bytes(obj.bytes_received)} / ' + format_bytes(
obj.bytes_transmitted
)
Comment on lines -65 to +67
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LDAPUsageAdmin.bytes refactored with the following changes:


def messages(self, obj):
return str(obj.messages_received) + " / " + str(obj.messages_transmitted)
return f'{str(obj.messages_received)} / {str(obj.messages_transmitted)}'
Comment on lines -68 to +70
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LDAPUsageAdmin.messages refactored with the following changes:


def sockets(self, obj):
return str(obj.open_sockets) + " / " + str(obj.closed_sockets) + " / " + str(obj.wrapped_sockets)
return f'{str(obj.open_sockets)} / {str(obj.closed_sockets)} / ' + str(
obj.wrapped_sockets
)
Comment on lines -71 to +75
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LDAPUsageAdmin.sockets refactored with the following changes:


def has_add_permission(self, request):
return False
Expand Down
2 changes: 1 addition & 1 deletion windows_auth/ldap_metrics/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def create_usage(domain: str, usage: ConnectionUsage) -> LDAPUsage:

def collect_metrics(unbind: bool = True):
if unbind:
logger.info(f"Unbinding all LDAP Connections for collecting metrics")
logger.info("Unbinding all LDAP Connections for collecting metrics")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function collect_metrics refactored with the following changes:


with LogExecutionTime("Collecting LDAP Connection metrics"):
try:
Expand Down
10 changes: 4 additions & 6 deletions windows_auth/management/commands/createtask.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,11 @@ def handle(self, command="", predefined=False, name=None, desc="", identity=LOCA
interval=None, random=None, timeout=None, priority=None, **options):
try:
if predefined:
# predefined tasks
if command in PREDEFINED_TASKS:
create_task = PREDEFINED_TASKS[command]
create_task(command=command, name=name, desc=desc, identity=identity, folder=folder,
interval=interval, random=random, timeout=timeout, priority=priority)
else:
if command not in PREDEFINED_TASKS:
raise CommandError(f"Predefined task for \"{command}\" does not exist.")
create_task = PREDEFINED_TASKS[command]
create_task(command=command, name=name, desc=desc, identity=identity, folder=folder,
interval=interval, random=random, timeout=timeout, priority=priority)
Comment on lines -69 to +73
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Command.handle refactored with the following changes:

This removes the following comments ( why? ):

# predefined tasks

else:
# create task definition
task_def = create_task_definition(command, description=desc, priority=priority, timeout=timeout)
Expand Down
23 changes: 10 additions & 13 deletions windows_auth/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,25 +40,22 @@ def __call__(self, request):

# create new cache key
cache.set(cache_key, True, timeout)
else:
# check via database query
if not ldap_user.last_sync or ldap_user.last_sync < timezone.now() - timezone.timedelta(seconds=timeout):
ldap_user.sync()
elif not ldap_user.last_sync or ldap_user.last_sync < timezone.now() - timezone.timedelta(seconds=timeout):
ldap_user.sync()
except LDAPUser.DoesNotExist:
# user is getting created the first time
pass
except Exception as e:
logger.exception(f"Failed to synchronize user {request.user} against LDAP")
# return error response
if WAUTH_REQUIRE_RESYNC:
if isinstance(WAUTH_ERROR_RESPONSE, int):
return HttpResponse(f"Authorization Failed.", status=WAUTH_ERROR_RESPONSE)
elif callable(WAUTH_ERROR_RESPONSE):
if isinstance(WAUTH_ERROR_RESPONSE, int):
if WAUTH_REQUIRE_RESYNC:
return HttpResponse("Authorization Failed.", status=WAUTH_ERROR_RESPONSE)
elif callable(WAUTH_ERROR_RESPONSE):
if WAUTH_REQUIRE_RESYNC:
return WAUTH_ERROR_RESPONSE(request, e)
else:
raise e
response = self.get_response(request)
return response
elif WAUTH_REQUIRE_RESYNC:
raise e
return self.get_response(request)
Comment on lines -43 to +58
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function UserSyncMiddleware.__call__ refactored with the following changes:

This removes the following comments ( why? ):

# return error response
# check via database query



class SimulateWindowsAuthMiddleware:
Expand Down
13 changes: 5 additions & 8 deletions windows_auth/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,12 @@ def create_user(self, username: str) -> User:
raise ValueError("Username must be in [email protected] format.")

sam_account_name, domain = username.split("@", 2)
else:
if "\\" not in username:
raise ValueError("Username must be in DOMAIN\\username format.")

elif "\\" in username:
domain, sam_account_name = username.split("\\", 2)

else:
raise ValueError("Username must be in DOMAIN\\username format.")
Comment on lines +48 to +52
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LDAPUserManager.create_user refactored with the following changes:


if WAUTH_LOWERCASE_USERNAME:
sam_account_name = sam_account_name.lower()

Expand Down Expand Up @@ -92,10 +92,7 @@ def get_ldap_attr(self, attribute: str, as_list: bool = False):
raise AttributeError(f"User {self.user} does not have LDAP Attribute {attribute}")

attribute_obj: Attribute = getattr(ldap_user, attribute)
if as_list:
return attribute_obj.values
else:
return attribute_obj.value
return attribute_obj.values if as_list else attribute_obj.value
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LDAPUser.get_ldap_attr refactored with the following changes:


@lru_cache()
def get_ldap_user(self, attributes: Optional[Iterable[str]] = None) -> Entry:
Expand Down
10 changes: 2 additions & 8 deletions windows_auth/panels.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,7 @@ def type_icon(self) -> str:

@cached_property
def status_icon(self) -> str:
if self.result.get("result") == 0:
return "✅"
else:
return "❌"
return "✅" if self.result.get("result") == 0 else "❌"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function OperationInfo.status_icon refactored with the following changes:


@cached_property
def scope_label(self) -> str:
Expand Down Expand Up @@ -204,10 +201,7 @@ def wrapper(message_id, timeout=None, get_request=False):
))

# mimic the original logic about get_request
if get_request:
return response, result, request
else:
return response, result
return (response, result, request) if get_request else (response, result)
Comment on lines -207 to +204
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_response_decorator.wrapper refactored with the following changes:


wrapper.original = func
return wrapper
Expand Down
7 changes: 3 additions & 4 deletions windows_auth/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,10 @@ def __init__(self,
self.context = context

def _get_message(self) -> str:
if callable(self.msg):
args, kwargs = self.context or ([], {})
return f"{self.msg(*args, **kwargs)}: {timezone.now() - self.start_time}"
else:
if not callable(self.msg):
return f"{self.msg}: {timezone.now() - self.start_time}"
args, kwargs = self.context or ([], {})
return f"{self.msg(*args, **kwargs)}: {timezone.now() - self.start_time}"
Comment on lines -34 to +37
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LogExecutionTime._get_message refactored with the following changes:


def __enter__(self):
self.start_time = timezone.now()
Expand Down