Skip to content
This repository has been archived by the owner on May 13, 2024. It is now read-only.

Commit

Permalink
chore: linted
Browse files Browse the repository at this point in the history
  • Loading branch information
c0rydoras committed Apr 16, 2024
1 parent a059fa4 commit 4bc7c86
Show file tree
Hide file tree
Showing 78 changed files with 866 additions and 787 deletions.
45 changes: 19 additions & 26 deletions timed/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,8 @@
class TimedOIDCAuthenticationBackend(OIDCAuthenticationBackend):
def get_introspection(self, access_token, id_token, payload):
"""Return user details dictionary."""

basic = base64.b64encode(
f"{settings.OIDC_RP_INTROSPECT_CLIENT_ID}:{settings.OIDC_RP_INTROSPECT_CLIENT_SECRET}".encode(
"utf-8"
)
f"{settings.OIDC_RP_INTROSPECT_CLIENT_ID}:{settings.OIDC_RP_INTROSPECT_CLIENT_SECRET}".encode()
).decode()
headers = {
"Authorization": f"Basic {basic}",
Expand All @@ -29,42 +26,39 @@ def get_introspection(self, access_token, id_token, payload):
verify=settings.OIDC_VERIFY_SSL,
headers=headers,
data={"token": access_token},
timeout=10,
)
response.raise_for_status()
return response.json()

def get_userinfo_or_introspection(self, access_token):
try:
claims = self.cached_request(
self.get_userinfo, access_token, "auth.userinfo"
)
return claims
return self.cached_request(self.get_userinfo, access_token, "auth.userinfo")
except requests.HTTPError as e:
if e.response.status_code not in [401, 403]:
raise e
raise
if settings.OIDC_CHECK_INTROSPECT:
try:
# check introspection if userinfo fails (confidential client)
claims = self.cached_request(
self.get_introspection, access_token, "auth.introspection"
)
if "client_id" not in claims:
raise SuspiciousOperation(
"client_id not present in introspection"
)
return claims
msg = "client_id not present in introspection"
raise SuspiciousOperation(msg)
except requests.HTTPError as e:
# if the authorization fails it's not a valid client or
# the token is expired and permission is denied.
# Handing on the 401 Client Error would be transformed into
# a 500 by Django's exception handling. But that's not what we want.
if e.response.status_code not in [401, 403]: # pragma: no cover
raise e
raise AuthenticationFailed()
raise
else:
return claims
raise AuthenticationFailed from None

def get_or_create_user(self, access_token, id_token, payload):
"""Verify claims and return user, otherwise raise an Exception."""

claims = self.get_userinfo_or_introspection(access_token)

users = self.filter_users_by_claims(claims)
Expand All @@ -73,15 +67,14 @@ def get_or_create_user(self, access_token, id_token, payload):
user = users.get()
self.update_user_from_claims(user, claims)
return user
elif settings.OIDC_CREATE_USER:
if settings.OIDC_CREATE_USER:
return self.create_user(claims)
else:
LOGGER.debug(
"Login failed: No user with username %s found, and "
"OIDC_CREATE_USER is False",
self.get_username(claims),
)
return None
LOGGER.debug(
"Login failed: No user with username %s found, and "
"OIDC_CREATE_USER is False",
self.get_username(claims),
)
return None

def update_user_from_claims(self, user, claims):
user.email = claims.get(settings.OIDC_EMAIL_CLAIM, "")
Expand All @@ -106,7 +99,6 @@ def cached_request(self, method, token, cache_prefix):

def create_user(self, claims):
"""Return object for a newly created user account."""

username = self.get_username(claims)
email = claims.get(settings.OIDC_EMAIL_CLAIM, "")
first_name = claims.get(settings.OIDC_FIRSTNAME_CLAIM, "")
Expand All @@ -120,4 +112,5 @@ def get_username(self, claims):
try:
return claims[settings.OIDC_USERNAME_CLAIM]
except KeyError:
raise SuspiciousOperation("Couldn't find username claim")
msg = "Couldn't find username claim"
raise SuspiciousOperation(msg) from None
29 changes: 14 additions & 15 deletions timed/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@


def register_module(module):
for name, obj in inspect.getmembers(module):
for _name, obj in inspect.getmembers(module):
if isinstance(obj, FactoryMetaClass) and not obj._meta.abstract:
register(obj)

Expand All @@ -25,7 +25,7 @@ def register_module(module):
register_module(tracking_factories)


@pytest.fixture
@pytest.fixture()
def auth_user(db):
return get_user_model().objects.create_user(
username="user",
Expand All @@ -37,7 +37,7 @@ def auth_user(db):
)


@pytest.fixture
@pytest.fixture()
def admin_user(db):
return get_user_model().objects.create_user(
username="admin",
Expand All @@ -49,7 +49,7 @@ def admin_user(db):
)


@pytest.fixture
@pytest.fixture()
def superadmin_user(db):
return get_user_model().objects.create_user(
username="superadmin",
Expand All @@ -61,7 +61,7 @@ def superadmin_user(db):
)


@pytest.fixture
@pytest.fixture()
def external_employee(db):
user = get_user_model().objects.create_user(
username="user",
Expand All @@ -75,7 +75,7 @@ def external_employee(db):
return user


@pytest.fixture
@pytest.fixture()
def internal_employee(db):
user = get_user_model().objects.create_user(
username="user",
Expand All @@ -90,12 +90,12 @@ def internal_employee(db):
return user


@pytest.fixture
@pytest.fixture()
def client():
return APIClient()


@pytest.fixture
@pytest.fixture()
def auth_client(auth_user):
"""Return instance of a APIClient that is logged in as test user."""
client = APIClient()
Expand All @@ -104,7 +104,7 @@ def auth_client(auth_user):
return client


@pytest.fixture
@pytest.fixture()
def admin_client(admin_user):
"""Return instance of a APIClient that is logged in as a staff user."""
client = APIClient()
Expand All @@ -113,7 +113,7 @@ def admin_client(admin_user):
return client


@pytest.fixture
@pytest.fixture()
def superadmin_client(superadmin_user):
"""Return instance of a APIClient that is logged in as superuser."""
client = APIClient()
Expand All @@ -122,7 +122,7 @@ def superadmin_client(superadmin_user):
return client


@pytest.fixture
@pytest.fixture()
def external_employee_client(external_employee):
"""Return instance of a APIClient that is logged in as external test user."""
client = APIClient()
Expand All @@ -131,7 +131,7 @@ def external_employee_client(external_employee):
return client


@pytest.fixture
@pytest.fixture()
def internal_employee_client(internal_employee):
"""Return instance of a APIClient that is logged in as external test user."""
client = APIClient()
Expand All @@ -140,16 +140,15 @@ def internal_employee_client(internal_employee):
return client


@pytest.fixture(scope="function", autouse=True)
@pytest.fixture(autouse=True)
def _autoclear_cache():
cache.clear()


def setup_customer_and_employment_status(
user, is_assignee, is_customer, is_employed, is_external
):
"""
Set up customer and employment status.
"""Set up customer and employment status.
Return a 2-tuple of assignee and employment, if they
were created
Expand Down
38 changes: 18 additions & 20 deletions timed/employment/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class SupervisorForm(forms.ModelForm):
class Meta:
"""Meta information for the supervisor form."""

fields = "__all__"
fields = "__all__" # noqa: DJ007
model = models.User.supervisors.through


Expand All @@ -51,12 +51,12 @@ class SuperviseeForm(forms.ModelForm):
class Meta:
"""Meta information for the supervisee form."""

fields = "__all__"
fields = "__all__" # noqa: DJ007
model = models.User.supervisors.through


class SupervisorInline(admin.TabularInline):
autocomplete_fields = ["to_user"]
autocomplete_fields = ("to_user",)
form = SupervisorForm
model = models.User.supervisors.through
extra = 0
Expand All @@ -66,7 +66,7 @@ class SupervisorInline(admin.TabularInline):


class SuperviseeInline(admin.TabularInline):
autocomplete_fields = ["from_user"]
autocomplete_fields = ("from_user",)
form = SuperviseeForm
model = models.User.supervisors.through
extra = 0
Expand Down Expand Up @@ -101,11 +101,9 @@ def clean(self):
raise ValidationError(_("The end date must be after the start date"))

if any(
[
e.start_date <= (data.get("end_date") or datetime.date.today())
and data.get("start_date") <= (e.end_date or datetime.date.today())
for e in employments
]
e.start_date <= (data.get("end_date") or datetime.date.today())
and data.get("start_date") <= (e.end_date or datetime.date.today())
for e in employments
):
raise ValidationError(
_("A user can't have multiple employments at the same time")
Expand All @@ -116,7 +114,7 @@ def clean(self):
class Meta:
"""Meta information for the employment form."""

fields = "__all__"
fields = "__all__" # noqa: DJ007
model = models.Employment


Expand Down Expand Up @@ -146,22 +144,22 @@ class AbsenceCreditInline(admin.TabularInline):
class UserAdmin(UserAdmin):
"""Timed specific user admin."""

inlines = [
inlines = (
SupervisorInline,
SuperviseeInline,
EmploymentInline,
OvertimeCreditInline,
AbsenceCreditInline,
]
)
list_display = ("username", "first_name", "last_name", "is_staff", "is_active")
search_fields = ["username"]
search_fields = ("username",)

actions = [
actions = (
"disable_users",
"enable_users",
"disable_staff_status",
"enable_staff_status",
]
)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
Expand Down Expand Up @@ -197,8 +195,8 @@ def has_delete_permission(self, request, obj=None):
class LocationAdmin(admin.ModelAdmin):
"""Location admin view."""

list_display = ["name"]
search_fields = ["name"]
list_display = ("name",)
search_fields = ("name",)

def has_delete_permission(self, request, obj=None):
return obj and not obj.employments.exists()
Expand All @@ -208,15 +206,15 @@ def has_delete_permission(self, request, obj=None):
class PublicHolidayAdmin(admin.ModelAdmin):
"""Public holiday admin view."""

list_display = ["__str__", "date", "location"]
list_filter = ["location"]
list_display = ("__str__", "date", "location")
list_filter = ("location",)


@admin.register(models.AbsenceType)
class AbsenceTypeAdmin(admin.ModelAdmin):
"""Absence type admin view."""

list_display = ["name"]
list_display = ("name",)

def has_delete_permission(self, request, obj=None):
return obj and not obj.absences.exists() and not obj.absencecredit_set.exists()
Loading

0 comments on commit 4bc7c86

Please sign in to comment.