Skip to content

Commit b0e78f9

Browse files
committed
linting
1 parent 2136aa9 commit b0e78f9

File tree

7 files changed

+42
-36
lines changed

7 files changed

+42
-36
lines changed

src/django_security_keys/backends.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,7 @@ def authenticate(
4444
if not username or not credential:
4545
return
4646

47-
has_credentials = SecurityKey.credentials(
48-
username, for_login=True
49-
)
47+
has_credentials = SecurityKey.credentials(username, for_login=True)
5048

5149
# no credential supplied
5250

src/django_security_keys/ext/two_factor/views.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import json
34
import time
45
from typing import Any
56

@@ -10,12 +11,13 @@
1011
from django.http.response import HttpResponse, HttpResponseRedirect
1112
from django.template.response import TemplateResponse
1213
from django.views.generic import FormView
14+
from webauthn.helpers import base64url_to_bytes
1315

1416
from django_security_keys.ext.two_factor import forms
1517
from django_security_keys.ext.two_factor.forms import SecurityKeyDeviceValidation
1618
from django_security_keys.models import SecurityKey, SecurityKeyDevice, UserHandle
17-
import json
18-
from webauthn.helpers import base64url_to_bytes
19+
20+
1921
class DisableView(two_factor.views.DisableView):
2022
def dispatch(self, *args: Any, **kwargs: Any) -> HttpResponse:
2123
self.success_url = "/"
@@ -37,10 +39,7 @@ def has_security_key_step(self) -> bool:
3739
if token_step_data:
3840
return False
3941

40-
return (
41-
len(SecurityKey.credentials(self.get_user().username))
42-
> 0
43-
)
42+
return len(SecurityKey.credentials(self.get_user().username)) > 0
4443

4544
condition_dict = {
4645
"backup": two_factor.views.LoginView.has_backup_step,
@@ -74,10 +73,12 @@ def attempt_passkey_auth(
7473
try:
7574
credential = request.POST.get("credential")
7675
try:
77-
user_handle = base64url_to_bytes(json.loads(credential)['response']['userHandle']).decode('utf-8')
76+
user_handle = base64url_to_bytes(
77+
json.loads(credential)["response"]["userHandle"]
78+
).decode("utf-8")
7879
username = UserHandle.objects.get(handle=user_handle).user.username
79-
except:
80-
raise Exception("Failed login using passkey")
80+
except Exception as exc:
81+
raise Exception(f"Failed login using passkey: {exc}")
8182
# support passkey login using webauthn
8283
if username and credential:
8384
user = authenticate(

src/django_security_keys/migrations/0004_remove_securitykey_passwordless_login_and_more.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
from django.db import migrations, models
22

3+
34
def migrate_passwordless_login_to_passkey_login(apps, schema_editor):
45
model = apps.get_model("django_security_keys", "SecurityKey")
56
try:
67
model._meta.get_field("updated").auto_now = False
78
for key in model.objects.all():
89
key.passkey_login = key.passwordless_login
9-
key.save(update_fields=['passkey_login'])
10+
key.save(update_fields=["passkey_login"])
1011
finally:
1112
model._meta.get_field("updated").auto_now = False
1213

14+
1315
class Migration(migrations.Migration):
1416

1517
dependencies = [

src/django_security_keys/models.py

+14-10
Original file line numberDiff line numberDiff line change
@@ -197,14 +197,16 @@ def generate_registration(cls, user: User, session: SessionStore) -> str:
197197
198198
- `str` JSON string
199199
"""
200-
existing_credentials = SecurityKey.credentials(user.username,ignore_credential_filter=True)
200+
existing_credentials = SecurityKey.credentials(
201+
user.username, ignore_credential_filter=True
202+
)
201203
opts = webauthn.generate_registration_options(
202204
rp_id=settings.WEBAUTHN_RP_ID,
203205
rp_name=settings.WEBAUTHN_RP_NAME,
204206
user_id=UserHandle.require_for_user(user).handle,
205207
user_name=user.username,
206208
attestation=getattr(settings, "WEBAUTHN_ATTESTATION", "none"),
207-
exclude_credentials=existing_credentials
209+
exclude_credentials=existing_credentials,
208210
)
209211

210212
cls.set_challenge(session, opts.challenge)
@@ -282,10 +284,12 @@ def verify_registration(
282284
SecurityKeyDevice.require_for_user(user)
283285
return key
284286

285-
286287
@classmethod
287288
def credentials(
288-
cls, username: User | str, for_login: bool = False, ignore_credential_filter = False
289+
cls,
290+
username: User | str,
291+
for_login: bool = False,
292+
ignore_credential_filter=False,
289293
) -> list[PublicKeyCredentialDescriptor]:
290294
"""
291295
Returns a list of credentials for the specified username
@@ -305,8 +309,8 @@ def credentials(
305309
"""
306310

307311
qset = cls.objects.filter(user__username=username)
308-
# ignore credential_filter to get all credentials data
309-
# example: used for excludeCredentials to prevent duplication of keys in 1 account in the same key
312+
# ignore credential_filter to get all credentials data
313+
# example: used for excludeCredentials to prevent duplication of keys in 1 account in the same key
310314
if not ignore_credential_filter:
311315
# if to be used for passkey login, exclude
312316
# credentials that are not enabled for that.
@@ -338,12 +342,12 @@ def generate_authentication(
338342
- `str` JSON
339343
"""
340344
options = {
341-
"rp_id":settings.WEBAUTHN_RP_ID,
345+
"rp_id": settings.WEBAUTHN_RP_ID,
342346
}
343347
if not for_login:
344-
options.update({
345-
"allow_credentials":cls.credentials(username, for_login=for_login)
346-
})
348+
options.update(
349+
{"allow_credentials": cls.credentials(username, for_login=for_login)}
350+
)
347351
opts = webauthn.generate_authentication_options(**options)
348352
cls.set_challenge(session, opts.challenge)
349353
return webauthn.options_to_json(opts)

src/django_security_keys/views.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import json
4+
import traceback
45
from typing import Any
56

67
from django.conf import settings
@@ -14,11 +15,12 @@
1415
from django.urls import reverse
1516
from django.utils.http import url_has_allowed_host_and_scheme
1617
from django.utils.translation import gettext_lazy as _
18+
from webauthn.helpers import base64url_to_bytes
1719

1820
from django_security_keys.forms import LoginForm, RegisterKeyForm
1921
from django_security_keys.models import SecurityKey, UserHandle
2022
from django_security_keys.utils import convert_to_bool
21-
from webauthn.helpers import base64url_to_bytes
23+
2224

2325
def basic_logout(request: WSGIRequest) -> HttpResponseRedirect:
2426
"""
@@ -51,13 +53,14 @@ def basic_login(request: WSGIRequest) -> HttpResponse | HttpResponseRedirect:
5153
if credential and not (username or password):
5254
# credential is set and not set username, password, check username in credential.response.userHandle
5355
try:
54-
user_handle = base64url_to_bytes(json.loads(credential)['response']['userHandle']).decode('utf-8')
56+
user_handle = base64url_to_bytes(
57+
json.loads(credential)["response"]["userHandle"]
58+
).decode("utf-8")
5559
username = UserHandle.objects.get(handle=user_handle).user.username
5660
user = authenticate(
5761
request, username=username, u2f_credential=credential
5862
)
59-
except:
60-
import traceback
63+
except Exception:
6164
print(traceback.format_exc())
6265
form.add_error("__all__", "Failed login using passkey")
6366
else:
@@ -121,9 +124,9 @@ def request_authentication(request: WSGIRequest, **kwargs: Any) -> JsonResponse:
121124
"""
122125

123126
username = request.POST.get("username")
124-
for_login = convert_to_bool(request.POST.get("for_login",False))
127+
for_login = convert_to_bool(request.POST.get("for_login", False))
125128
if not for_login and not username:
126-
return JsonResponse({"non_field_errors": _("No username supplied")}, status=403)
129+
return JsonResponse({"non_field_errors": _("No username supplied")}, status=403)
127130
return JsonResponse(
128131
json.loads(
129132
SecurityKey.generate_authentication(

tests/fixtures.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ def invalid_test_credential():
5252
def test_auth_credential():
5353
return _test_auth_credential()
5454

55+
5556
@pytest.fixture
5657
def test_auth_credential_passkey():
5758
return _test_auth_credential_passkey()
@@ -79,7 +80,7 @@ def security_key_passkey():
7980

8081

8182
def _test_credential():
82-
from django_security_keys.models import SecurityKey, UserHandle
83+
from django_security_keys.models import SecurityKey
8384

8485
user = get_user_model().objects.create_user("bob", password="user")
8586
session = SessionStore()
@@ -169,10 +170,9 @@ def _test_auth_credential_passkey():
169170
),
170171
)
171172
UserHandle.objects.create(
172-
user=user,
173-
handle="xyW3XGlevvnRg2XgN7CeBuLKr_YJwmS2i_GM9eLt330"
173+
user=user, handle="xyW3XGlevvnRg2XgN7CeBuLKr_YJwmS2i_GM9eLt330"
174174
)
175-
175+
176176
cred = json.dumps(
177177
{
178178
"id": "ZoIKP1JQvKdrYj1bTUPJ2eTUsbLeFkv-X5xJQNr4k6s",

tests/test_views.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,7 @@ def test_passkey_login_failure_invalid_signature(invalid_auth_credential):
5858
SecurityKey.set_challenge(client_session, SecurityKey.get_challenge(session))
5959
client_session.save()
6060

61-
response = c.post(
62-
reverse("login"), {"credential": cred}
63-
)
61+
response = c.post(reverse("login"), {"credential": cred})
6462

6563
response = c.get(reverse("security-keys:manage-keys"))
6664
assert "Your keys" not in response.content.decode("utf-8")

0 commit comments

Comments
 (0)