Skip to content

Commit

Permalink
Pylint updates
Browse files Browse the repository at this point in the history
  • Loading branch information
horilla-opensource committed Mar 6, 2025
1 parent 4232301 commit 39784bb
Show file tree
Hide file tree
Showing 12 changed files with 164 additions and 75 deletions.
8 changes: 6 additions & 2 deletions attendance/scheduler.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import datetime
import sys
from apscheduler.schedulers.background import BackgroundScheduler

from apscheduler.schedulers.background import BackgroundScheduler

today = datetime.datetime.today()

Expand All @@ -22,7 +22,11 @@ def create_work_record(date=today):
WorkRecords.objects.get_or_create(
employee_id=employee,
date=date,
defaults={"work_record_type": "DFT", "shift_id": shift, "message": ""},
defaults={
"work_record_type": "DFT",
"shift_id": shift,
"message": "",
},
)
except:
pass
Expand Down
31 changes: 18 additions & 13 deletions attendance/signals.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
# attendance/signals.py

from datetime import datetime, timedelta

from django.apps import apps
from django.db.models.signals import post_migrate, post_save, pre_delete
from django.utils.translation import gettext_lazy as _
from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _

from attendance.methods.utils import strtime_seconds
from attendance.models import (
Attendance,
AttendanceGeneralSetting,
WorkRecords,
)
from attendance.models import Attendance, AttendanceGeneralSetting, WorkRecords
from base.models import Company, PenaltyAccounts
from employee.models import Employee
from horilla.methods import get_horilla_model_class


if apps.is_installed("payroll"):

@receiver(post_save, sender=PenaltyAccounts)
Expand Down Expand Up @@ -148,7 +144,7 @@ def add_missing_attendance_to_workrecord(sender, **kwargs):
if sender.label not in ["attendance", "leave"]:
return

from attendance.models import WorkRecords, Attendance
from attendance.models import Attendance, WorkRecords

try:
work_records = WorkRecords.objects.filter(
Expand Down Expand Up @@ -230,6 +226,7 @@ def create_attendance_setting(sender, instance, created, raw, **kwargs):
if created:
AttendanceGeneralSetting.objects.get_or_create(company_id=instance)


@receiver(post_migrate)
def create_missing_work_records(sender, **kwargs):
if sender.label not in ["attendance"]:
Expand All @@ -247,10 +244,15 @@ def create_missing_work_records(sender, **kwargs):
end_date = datetime.today().date()

existing_dates = set(
WorkRecords.objects.filter(employee_id=employee.id).values_list("date", flat=True)
WorkRecords.objects.filter(employee_id=employee.id).values_list(
"date", flat=True
)
)

all_dates = {start_date + timedelta(days=i) for i in range((end_date - start_date).days)}
all_dates = {
start_date + timedelta(days=i)
for i in range((end_date - start_date).days)
}
missing_dates = all_dates - existing_dates

work_records_to_create = [
Expand All @@ -264,8 +266,11 @@ def create_missing_work_records(sender, **kwargs):
]

if work_records_to_create:
WorkRecords.objects.bulk_create(work_records_to_create, batch_size=500, ignore_conflicts=True)
WorkRecords.objects.bulk_create(
work_records_to_create, batch_size=500, ignore_conflicts=True
)

except Exception as e:
print(f"Error creating missing work records for employee {employee}: {e}")

print(
f"Error creating missing work records for employee {employee}: {e}"
)
8 changes: 5 additions & 3 deletions horilla_ldap/apps.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
from django.apps import AppConfig
from django.conf import settings

import horilla.horilla_settings


class HorillaLdapConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'horilla_ldap'
default_auto_field = "django.db.models.BigAutoField"
name = "horilla_ldap"

def ready(self):
from django.urls import include, path
from horilla.urls import urlpatterns

from horilla.horilla_settings import APPS
from horilla.urls import urlpatterns

APPS.append("horilla_ldap")
urlpatterns.append(
Expand Down
11 changes: 8 additions & 3 deletions horilla_ldap/forms.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
from django import forms
from .models import LDAPSettings
from django.template.loader import render_to_string

from base.forms import ModelForm

from .models import LDAPSettings


class LDAPSettingsForm(ModelForm):
bind_password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"oh-input w-100"}), required=True)
bind_password = forms.CharField(
widget=forms.PasswordInput(attrs={"class": "oh-input w-100"}), required=True
)

class Meta:
model = LDAPSettings
fields = ['ldap_server', 'bind_dn', 'bind_password', 'base_dn']
fields = ["ldap_server", "bind_dn", "bind_password", "base_dn"]

def as_p(self):
"""
Expand Down
74 changes: 57 additions & 17 deletions horilla_ldap/management/commands/import_ldap_users.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import platform
import re
import sys
import platform

from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.db.models import Q
from django.contrib.auth.models import User
from horilla_ldap.models import LDAPSettings

from employee.models import Employee
from horilla_ldap.models import LDAPSettings

if platform.system() == "Linux":
import ldap # Use python-ldap for Linux
else:
from ldap3 import Server, Connection, ALL # Use ldap3 for Windows
from ldap3 import ALL, Connection, Server # Use ldap3 for Windows


class Command(BaseCommand):
Expand All @@ -33,7 +35,11 @@ def handle(self, *args, **kwargs):
base_dn = settings.base_dn

if not all([ldap_server, bind_dn, bind_password, base_dn]):
self.stdout.write(self.style.ERROR("LDAP settings are incomplete. Please check your configuration."))
self.stdout.write(
self.style.ERROR(
"LDAP settings are incomplete. Please check your configuration."
)
)
return

try:
Expand All @@ -42,7 +48,9 @@ def handle(self, *args, **kwargs):
connection = ldap.initialize(ldap_server)
connection.simple_bind_s(bind_dn, bind_password)
search_filter = "(objectClass=inetOrgPerson)"
results = connection.search_s(base_dn, ldap.SCOPE_SUBTREE, search_filter)
results = connection.search_s(
base_dn, ldap.SCOPE_SUBTREE, search_filter
)

for dn, entry in results:
user_id = entry.get("uid", [b""])[0].decode("utf-8")
Expand All @@ -53,13 +61,17 @@ def handle(self, *args, **kwargs):
phone = entry.get("telephoneNumber", [b""])[0].decode("utf-8")

# Get the password from LDAP
ldap_password = entry.get("telephoneNumber", [b""])[0].decode("utf-8")
ldap_password = entry.get("telephoneNumber", [b""])[0].decode(
"utf-8"
)

# Remove non-numeric characters but keep numbers
clean_phone = re.sub(r"[^\d]", "", phone)
clean_phone = re.sub(r"[^\d]", "", phone)
ldap_password = clean_phone

self.create_or_update_employee(user_id, email, first_name, last_name, phone, ldap_password)
self.create_or_update_employee(
user_id, email, first_name, last_name, phone, ldap_password
)

connection.unbind_s()

Expand All @@ -68,11 +80,27 @@ def handle(self, *args, **kwargs):
server = Server(ldap_server, get_info=ALL)
connection = Connection(server, user=bind_dn, password=bind_password)
if not connection.bind():
self.stdout.write(self.style.ERROR(f"Failed to bind to LDAP server: {connection.last_error}"))
self.stdout.write(
self.style.ERROR(
f"Failed to bind to LDAP server: {connection.last_error}"
)
)
return

search_filter = "(objectClass=inetOrgPerson)"
connection.search(base_dn, search_filter, attributes=['uid', 'mail', 'givenName', 'sn', 'cn', 'telephoneNumber', 'userPassword'])
connection.search(
base_dn,
search_filter,
attributes=[
"uid",
"mail",
"givenName",
"sn",
"cn",
"telephoneNumber",
"userPassword",
],
)

for entry in connection.entries:
user_id = entry.uid.value if entry.uid else ""
Expand All @@ -86,32 +114,44 @@ def handle(self, *args, **kwargs):
clean_phone = re.sub(r"[^\d]", "", phone)
ldap_password = clean_phone

self.create_or_update_employee(user_id, email, first_name, last_name, phone, ldap_password)
self.create_or_update_employee(
user_id, email, first_name, last_name, phone, ldap_password
)

connection.unbind()

except Exception as e:
self.stderr.write(self.style.ERROR(f"Error: {e}"))

def create_or_update_employee(self, user_id, email, first_name, last_name, phone, ldap_password):
def create_or_update_employee(
self, user_id, email, first_name, last_name, phone, ldap_password
):
employee, created = Employee.objects.update_or_create(
email=email,
defaults={
"employee_first_name": first_name or "",
"employee_last_name": last_name or "",
"phone": phone or "",
}
},
)

try:
user = User.objects.get(Q(username=email) | Q(username=user_id) | Q(email=email))
user = User.objects.get(
Q(username=email) | Q(username=user_id) | Q(email=email)
)
user.username = user_id
user.set_password(ldap_password) # Hash and store password securely
user.save()
action = "Updated"
except User.DoesNotExist:
self.stdout.write(self.style.WARNING(f"User for employee {first_name} {last_name} does not exist."))
self.stdout.write(
self.style.WARNING(
f"User for employee {first_name} {last_name} does not exist."
)
)
return

action = "Created" if created else "Updated"
self.stdout.write(self.style.SUCCESS(f"{action} employee {first_name} {last_name}."))
self.stdout.write(
self.style.SUCCESS(f"{action} employee {first_name} {last_name}.")
)
Loading

0 comments on commit 39784bb

Please sign in to comment.