summaryrefslogtreecommitdiff
path: root/accounts
diff options
context:
space:
mode:
authordjango-bot <ops@djangoproject.com>2022-11-26 16:30:44 +0530
committerPaolo Melchiorre <paolo@melchiorre.org>2022-11-30 12:54:36 +0100
commit3045b338de791118962df4db370411247413eca6 (patch)
treebb222ffb7e4b938dfe9e0386c617ad1835a3ded6 /accounts
parent40b0da2c241ea471f70eb9c4fbe6da396253f363 (diff)
Refs #1184 -- Reformatted code with Black.
Diffstat (limited to 'accounts')
-rw-r--r--accounts/forms.py17
-rw-r--r--accounts/hashers.py8
-rw-r--r--accounts/migrations/0001_initial.py24
-rw-r--r--accounts/migrations/0002_migrate_sha1_passwords.py12
-rw-r--r--accounts/test_hashers.py15
-rw-r--r--accounts/tests.py17
-rw-r--r--accounts/urls.py14
-rw-r--r--accounts/views.py43
8 files changed, 83 insertions, 67 deletions
diff --git a/accounts/forms.py b/accounts/forms.py
index f773d404..58cec8b8 100644
--- a/accounts/forms.py
+++ b/accounts/forms.py
@@ -10,29 +10,28 @@ class ProfileForm(forms.ModelForm):
Assumes that the Profile instance passed in has an associated User
object. The view (see views.py) takes care of that.
"""
+
name = forms.CharField(
- required=False,
- widget=forms.TextInput(attrs={'placeholder': 'Name'})
+ required=False, widget=forms.TextInput(attrs={"placeholder": "Name"})
)
email = forms.EmailField(
- required=False,
- widget=forms.TextInput(attrs={'placeholder': 'Email'})
+ required=False, widget=forms.TextInput(attrs={"placeholder": "Email"})
)
class Meta:
model = Profile
- fields = ['name']
+ fields = ["name"]
def __init__(self, *args, **kwargs):
- instance = kwargs.get('instance', None)
+ instance = kwargs.get("instance", None)
if instance:
- kwargs.setdefault('initial', {}).update({'email': instance.user.email})
+ kwargs.setdefault("initial", {}).update({"email": instance.user.email})
super().__init__(*args, **kwargs)
def save(self, commit=True):
instance = super().save(commit=commit)
- if 'email' in self.cleaned_data:
- instance.user.email = self.cleaned_data['email']
+ if "email" in self.cleaned_data:
+ instance.user.email = self.cleaned_data["email"]
if commit:
instance.user.save()
return instance
diff --git a/accounts/hashers.py b/accounts/hashers.py
index 36034e46..59d0d7e1 100644
--- a/accounts/hashers.py
+++ b/accounts/hashers.py
@@ -1,14 +1,12 @@
-from django.contrib.auth.hashers import (
- PBKDF2PasswordHasher, SHA1PasswordHasher,
-)
+from django.contrib.auth.hashers import PBKDF2PasswordHasher, SHA1PasswordHasher
class PBKDF2WrappedSHA1PasswordHasher(PBKDF2PasswordHasher):
- algorithm = 'pbkdf2_wrapped_sha1'
+ algorithm = "pbkdf2_wrapped_sha1"
def encode_sha1_hash(self, sha1_hash, salt, iterations=None):
return super().encode(sha1_hash, salt, iterations)
def encode(self, password, salt, iterations=None):
- _, _, sha1_hash = SHA1PasswordHasher().encode(password, salt).split('$', 2)
+ _, _, sha1_hash = SHA1PasswordHasher().encode(password, salt).split("$", 2)
return self.encode_sha1_hash(sha1_hash, salt, iterations)
diff --git a/accounts/migrations/0001_initial.py b/accounts/migrations/0001_initial.py
index 693d7a6d..bf9e50c6 100644
--- a/accounts/migrations/0001_initial.py
+++ b/accounts/migrations/0001_initial.py
@@ -13,14 +13,26 @@ class Migration(migrations.Migration):
operations = [
migrations.CreateModel(
- name='Profile',
+ name="Profile",
fields=[
- ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
- ('name', models.CharField(max_length=200, blank=True)),
- ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)),
+ (
+ "id",
+ models.AutoField(
+ verbose_name="ID",
+ serialize=False,
+ auto_created=True,
+ primary_key=True,
+ ),
+ ),
+ ("name", models.CharField(max_length=200, blank=True)),
+ (
+ "user",
+ models.OneToOneField(
+ to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE
+ ),
+ ),
],
- options={
- },
+ options={},
bases=(models.Model,),
),
]
diff --git a/accounts/migrations/0002_migrate_sha1_passwords.py b/accounts/migrations/0002_migrate_sha1_passwords.py
index b82480c2..3aa786b4 100644
--- a/accounts/migrations/0002_migrate_sha1_passwords.py
+++ b/accounts/migrations/0002_migrate_sha1_passwords.py
@@ -4,20 +4,20 @@ from ..hashers import PBKDF2WrappedSHA1PasswordHasher
def forwards_func(apps, schema_editor):
- User = apps.get_model('auth', 'User')
- users = User.objects.filter(password__startswith='sha1$')
+ User = apps.get_model("auth", "User")
+ users = User.objects.filter(password__startswith="sha1$")
hasher = PBKDF2WrappedSHA1PasswordHasher()
for user in users:
- algorithm, salt, sha1_hash = user.password.split('$', 2)
+ algorithm, salt, sha1_hash = user.password.split("$", 2)
user.password = hasher.encode_sha1_hash(sha1_hash, salt)
- user.save(update_fields=['password'])
+ user.save(update_fields=["password"])
class Migration(migrations.Migration):
dependencies = [
- ('accounts', '0001_initial'),
- ('auth', '0007_alter_validators_add_error_messages'),
+ ("accounts", "0001_initial"),
+ ("auth", "0007_alter_validators_add_error_messages"),
]
operations = [
diff --git a/accounts/test_hashers.py b/accounts/test_hashers.py
index 8708826b..1cd73d05 100644
--- a/accounts/test_hashers.py
+++ b/accounts/test_hashers.py
@@ -6,11 +6,16 @@ from .hashers import PBKDF2WrappedSHA1PasswordHasher
class TestHasher(SimpleTestCase):
def test(self):
iterations = 10 # low value for testing
- password = 'a'
- sha1_encoded = 'sha1$YoBzLZeL3w2R$757b56ad30c5fac1b552f58ad3acfddb07b674e2'
- expected_pbkdf2_encoded = 'pbkdf2_wrapped_sha1$10$YoBzLZeL3w2R$djfB2Y51/PwFdzcMoIlwUXglb2wMBz2L+LZ8Hjs2wnk='
- _, salt, sha1_hash = sha1_encoded.split('$', 3)
+ password = "a"
+ sha1_encoded = "sha1$YoBzLZeL3w2R$757b56ad30c5fac1b552f58ad3acfddb07b674e2"
+ expected_pbkdf2_encoded = (
+ "pbkdf2_wrapped_sha1$10$YoBzLZeL3w2R$djfB2Y51/"
+ "PwFdzcMoIlwUXglb2wMBz2L+LZ8Hjs2wnk="
+ )
+ _, salt, sha1_hash = sha1_encoded.split("$", 3)
hasher = PBKDF2WrappedSHA1PasswordHasher()
pbkdf2_hash = hasher.encode_sha1_hash(sha1_hash, salt, iterations)
self.assertEqual(pbkdf2_hash, expected_pbkdf2_encoded)
- self.assertEqual(hasher.encode(password, salt, iterations), expected_pbkdf2_encoded)
+ self.assertEqual(
+ hasher.encode(password, salt, iterations), expected_pbkdf2_encoded
+ )
diff --git a/accounts/tests.py b/accounts/tests.py
index b7a89336..2805ae16 100644
--- a/accounts/tests.py
+++ b/accounts/tests.py
@@ -6,25 +6,24 @@ from django_hosts.resolvers import reverse
class ViewTests(TestCase):
-
def setUp(self):
- self.credentials = {'username': 'a-user', 'password': 'password'}
+ self.credentials = {"username": "a-user", "password": "password"}
self.user = User.objects.create_user(**self.credentials)
- @mock.patch('accounts.views.get_user_stats')
+ @mock.patch("accounts.views.get_user_stats")
def test_user_profile(self, mock_user_stats):
- response = self.client.get(reverse('user_profile', host='www', args=['a-user']))
- self.assertContains(response, 'a-user')
+ response = self.client.get(reverse("user_profile", host="www", args=["a-user"]))
+ self.assertContains(response, "a-user")
mock_user_stats.assert_called_once_with(self.user)
def test_login_redirect(self):
- response = self.client.post(reverse('login'), self.credentials)
- self.assertRedirects(response, '/accounts/edit/')
+ response = self.client.post(reverse("login"), self.credentials)
+ self.assertRedirects(response, "/accounts/edit/")
def test_profile_view_reversal(self):
"""
The profile view can be reversed for usernames containing "weird" but
valid username characters.
"""
- for username in ['asdf', '@asdf', 'asd-f', 'as.df', 'as+df']:
- reverse('user_profile', host='www', args=[username])
+ for username in ["asdf", "@asdf", "asd-f", "as.df", "as+df"]:
+ reverse("user_profile", host="www", args=[username])
diff --git a/accounts/urls.py b/accounts/urls.py
index 3c27bfa2..ff576127 100644
--- a/accounts/urls.py
+++ b/accounts/urls.py
@@ -6,16 +6,16 @@ from . import views as account_views
urlpatterns = [
path(
- 'register/',
+ "register/",
RegistrationView.as_view(form_class=RegistrationFormUniqueEmail),
- name='registration_register',
+ name="registration_register",
),
path(
- 'edit/',
+ "edit/",
account_views.edit_profile,
- name='edit_profile',
+ name="edit_profile",
),
- path('_trac/userinfo/', account_views.json_user_info),
- path('', include('django.contrib.auth.urls')),
- path('', include('registration.backends.default.urls')),
+ path("_trac/userinfo/", account_views.json_user_info),
+ path("", include("django.contrib.auth.urls")),
+ path("", include("registration.backends.default.urls")),
]
diff --git a/accounts/views.py b/accounts/views.py
index 8332a392..b287d31f 100644
--- a/accounts/views.py
+++ b/accounts/views.py
@@ -16,12 +16,16 @@ from .models import Profile
def user_profile(request, username):
user = get_object_or_404(User, username=username)
- return render(request, "accounts/user_profile.html", {
- 'user_obj': user,
- 'email_hash': hashlib.md5(user.email.encode('ascii', 'ignore')).hexdigest(),
- 'user_can_commit': user.has_perm('auth.commit'),
- 'stats': get_user_stats(user),
- })
+ return render(
+ request,
+ "accounts/user_profile.html",
+ {
+ "user_obj": user,
+ "email_hash": hashlib.md5(user.email.encode("ascii", "ignore")).hexdigest(),
+ "user_can_commit": user.has_perm("auth.commit"),
+ "stats": get_user_stats(user),
+ },
+ )
@login_required
@@ -30,8 +34,8 @@ def edit_profile(request):
form = ProfileForm(request.POST or None, instance=profile)
if form.is_valid():
form.save()
- return redirect('user_profile', request.user.username)
- return render(request, "accounts/edit_profile.html", {'form': form})
+ return redirect("user_profile", request.user.username)
+ return render(request, "accounts/edit_profile.html", {"form": form})
def json_user_info(request):
@@ -50,17 +54,16 @@ def json_user_info(request):
De-duplication on GET['user'] is performed since I don't want to have to
think about how best to do it in JavaScript :)
"""
- userinfo = dict([
- (name, get_user_info(name))
- for name in set(request.GET.getlist('user'))
- ])
+ userinfo = dict(
+ [(name, get_user_info(name)) for name in set(request.GET.getlist("user"))]
+ )
return JSONResponse(userinfo)
def get_user_info(username):
- c = caches['default']
- username = username.encode('ascii', 'ignore')
- key = 'trac_user_info:%s' % hashlib.md5(username).hexdigest()
+ c = caches["default"]
+ username = username.encode("ascii", "ignore")
+ key = "trac_user_info:%s" % hashlib.md5(username).hexdigest()
info = c.get(key)
if info is None:
try:
@@ -69,16 +72,16 @@ def get_user_info(username):
info = {"core": False, "cla": False}
else:
info = {
- "core": u.has_perm('auth.commit'),
+ "core": u.has_perm("auth.commit"),
}
c.set(key, info, 60 * 60)
return info
def get_user_stats(user):
- c = caches['default']
- username = user.username.encode('ascii', 'ignore')
- key = 'user_vital_status:%s' % hashlib.md5(username).hexdigest()
+ c = caches["default"]
+ username = user.username.encode("ascii", "ignore")
+ key = "user_vital_status:%s" % hashlib.md5(username).hexdigest()
info = c.get(key)
if info is None:
info = trac_stats.get_user_stats(user.username)
@@ -95,5 +98,5 @@ class JSONResponse(HttpResponse):
def __init__(self, obj):
super().__init__(
json.dumps(obj, indent=(2 if settings.DEBUG else None)),
- content_type='application/json',
+ content_type="application/json",
)