Skip to content

Commit

Permalink
Merge pull request #376 from pinax/fix-deepsource-complaints
Browse files Browse the repository at this point in the history
Fix deepsource complaints
  • Loading branch information
uhurusurfa authored Sep 16, 2023
2 parents 8c7fe02 + 06be2cd commit 75eaad8
Show file tree
Hide file tree
Showing 11 changed files with 94 additions and 61 deletions.
3 changes: 2 additions & 1 deletion account/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,6 @@ class AccountAppConf(AppConf):
TIMEZONES = TIMEZONES
LANGUAGES = LANGUAGES

def configure_hookset(self, value):
@staticmethod
def configure_hookset(value):
return load_path_attr(value)()
2 changes: 1 addition & 1 deletion account/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ def __init__(self, *args, **kwargs):
"blank": True,
}
defaults.update(kwargs)
return super(TimeZoneField, self).__init__(*args, **defaults)
super(TimeZoneField, self).__init__(*args, **defaults)
9 changes: 6 additions & 3 deletions account/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,12 @@ def clean_email(self):
raise forms.ValidationError(_("A user is registered with this email address."))

def clean(self):
if "password" in self.cleaned_data and "password_confirm" in self.cleaned_data:
if self.cleaned_data["password"] != self.cleaned_data["password_confirm"]:
raise forms.ValidationError(_("You must type the same password each time."))
if (
"password" in self.cleaned_data and
"password_confirm" in self.cleaned_data and
self.cleaned_data["password"] != self.cleaned_data["password_confirm"]
):
raise forms.ValidationError(_("You must type the same password each time."))
return self.cleaned_data


Expand Down
31 changes: 20 additions & 11 deletions account/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,37 @@
from account.conf import settings


class AccountDefaultHookSet(object):
class AccountDefaultHookSet:

def send_invitation_email(self, to, ctx):
@staticmethod
def send_invitation_email(to, ctx):
subject = render_to_string("account/email/invite_user_subject.txt", ctx)
message = render_to_string("account/email/invite_user.txt", ctx)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, to)

def send_confirmation_email(self, to, ctx):
@staticmethod
def send_confirmation_email(to, ctx):
subject = render_to_string("account/email/email_confirmation_subject.txt", ctx)
subject = "".join(subject.splitlines()) # remove superfluous line breaks
message = render_to_string("account/email/email_confirmation_message.txt", ctx)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, to)

def send_password_change_email(self, to, ctx):
@staticmethod
def send_password_change_email(to, ctx):
subject = render_to_string("account/email/password_change_subject.txt", ctx)
subject = "".join(subject.splitlines())
message = render_to_string("account/email/password_change.txt", ctx)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, to)

def send_password_reset_email(self, to, ctx):
@staticmethod
def send_password_reset_email(to, ctx):
subject = render_to_string("account/email/password_reset_subject.txt", ctx)
subject = "".join(subject.splitlines())
message = render_to_string("account/email/password_reset.txt", ctx)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, to)

def generate_random_token(self, extra=None, hash_func=hashlib.sha256):
@staticmethod
def generate_random_token(extra=None, hash_func=hashlib.sha256):
if extra is None:
extra = []
bits = extra + [str(random.SystemRandom().getrandbits(512))]
Expand All @@ -49,26 +54,30 @@ def generate_signup_code_token(self, email=None):
def generate_email_confirmation_token(self, email):
return self.generate_random_token([email])

def get_user_credentials(self, form, identifier_field):
@staticmethod
def get_user_credentials(form, identifier_field):
return {
"username": form.cleaned_data[identifier_field],
"password": form.cleaned_data["password"],
}

def clean_password(self, password_new, password_new_confirm):
@staticmethod
def clean_password(password_new, password_new_confirm):
if password_new != password_new_confirm:
raise forms.ValidationError(_("You must type the same password each time."))
return password_new

def account_delete_mark(self, deletion):
@staticmethod
def account_delete_mark(deletion):
deletion.user.is_active = False
deletion.user.save()

def account_delete_expunge(self, deletion):
@staticmethod
def account_delete_expunge(deletion):
deletion.user.delete()


class HookProxy(object):
class HookProxy:

def __getattr__(self, attr):
return getattr(settings.ACCOUNT_HOOKSET, attr)
Expand Down
17 changes: 10 additions & 7 deletions account/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ class LocaleMiddleware(BaseMiddleware):
(if the language is available, of course).
"""

def get_language_for_user(self, request):
@staticmethod
def get_language_for_user(request):
if request.user.is_authenticated:
try:
account = Account.objects.get(user=request.user)
Expand All @@ -37,7 +38,8 @@ def process_request(self, request):
translation.activate(self.get_language_for_user(request))
request.LANGUAGE_CODE = translation.get_language()

def process_response(self, request, response):
@staticmethod
def process_response(request, response):
patch_vary_headers(response, ("Accept-Language",))
response["Content-Language"] = translation.get_language()
translation.deactivate()
Expand All @@ -50,7 +52,8 @@ class TimezoneMiddleware(BaseMiddleware):
templates to the user's timezone.
"""

def process_request(self, request):
@staticmethod
def process_request(request):
try:
account = getattr(request.user, "account", None)
except Account.DoesNotExist:
Expand All @@ -69,10 +72,10 @@ def process_request(self, request):
# Authenticated users must be allowed to access
# "change password" page and "log out" page.
# even if password is expired.
if next_url not in [settings.ACCOUNT_PASSWORD_CHANGE_REDIRECT_URL,
settings.ACCOUNT_LOGOUT_URL,
]:
if check_password_expired(request.user):
if next_url not in [
settings.ACCOUNT_PASSWORD_CHANGE_REDIRECT_URL,
settings.ACCOUNT_LOGOUT_URL,
] and check_password_expired(request.user):
signals.password_expired.send(sender=self, user=request.user)
messages.add_message(
request,
Expand Down
18 changes: 18 additions & 0 deletions account/migrations/0007_alter_emailconfirmation_sent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.2.5 on 2023-09-12 21:58

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('account', '0006_alter_signupcode_max_uses'),
]

operations = [
migrations.AlterField(
model_name='emailconfirmation',
name='sent',
field=models.DateTimeField(blank=True, null=True),
),
]
2 changes: 1 addition & 1 deletion account/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from account.utils import handle_redirect_to_login


class LoginRequiredMixin(object):
class LoginRequiredMixin:

redirect_field_name = REDIRECT_FIELD_NAME
login_url = None
Expand Down
9 changes: 4 additions & 5 deletions account/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def localtime(self, value):


@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def user_post_save(sender, **kwargs):
def user_post_save(*args, **kwargs):
"""
After User.save is called we check to see if it was a created user. If so,
we check if the User object wants account creation. If all passes we
Expand Down Expand Up @@ -149,8 +149,7 @@ class Meta:
def __str__(self):
if self.email:
return "{0} [{1}]".format(self.email, self.code)
else:
return self.code
return self.code

@classmethod
def exists(cls, code=None, email=None):
Expand Down Expand Up @@ -310,7 +309,7 @@ class EmailConfirmation(models.Model):

email_address = models.ForeignKey(EmailAddress, on_delete=models.CASCADE)
created = models.DateTimeField(default=timezone.now)
sent = models.DateTimeField(null=True)
sent = models.DateTimeField(blank=True, null=True)
key = models.CharField(max_length=64, unique=True)

objects = EmailConfirmationManager()
Expand Down Expand Up @@ -388,7 +387,7 @@ def expunge(cls, hours_ago=None):

@classmethod
def mark(cls, user):
account_deletion, created = cls.objects.get_or_create(user=user)
account_deletion, created = cls.objects.get_or_create(user=user) # skipcq: PYL-W0612
account_deletion.email = user.email
account_deletion.save()
hookset.account_delete_mark(account_deletion)
Expand Down
19 changes: 10 additions & 9 deletions account/templatetags/account_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def render(self, context):


@register.tag(name="user_display")
def do_user_display(parser, token):
def do_user_display(parser, token): # skipcq: PYL-W0613
"""
Example usage::
Expand All @@ -51,16 +51,18 @@ def do_user_display(parser, token):

class URLNextNode(URLNode):

def add_next(self, url, context):
@staticmethod
def add_next(url, context):
"""
With both `redirect_field_name` and `redirect_field_value` available in
the context, add on a querystring to handle "next" redirecting.
"""
if all([key in context for key in ["redirect_field_name", "redirect_field_value"]]):
if context["redirect_field_value"]:
url += "?" + urlencode({
context["redirect_field_name"]: context["redirect_field_value"],
})
if all(
key in context for key in ["redirect_field_name", "redirect_field_value"]
) and context["redirect_field_value"]:
url += "?" + urlencode({
context["redirect_field_name"]: context["redirect_field_value"],
})
return url

def render(self, context):
Expand All @@ -72,8 +74,7 @@ def render(self, context):
if self.asvar:
context[self.asvar] = url
return ""
else:
return url
return url


@register.tag
Expand Down
30 changes: 13 additions & 17 deletions account/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,18 @@ def default_redirect(request, fallback_url, **kwargs):
)
if next_url and is_safe(next_url):
return next_url
else:
try:
fallback_url = reverse(fallback_url)
except NoReverseMatch:
if callable(fallback_url):
raise
if "/" not in fallback_url and "." not in fallback_url:
raise
# assert the fallback URL is safe to return to caller. if it is
# determined unsafe then raise an exception as the fallback value comes
# from the a source the developer choose.
is_safe(fallback_url, raise_on_fail=True)
return fallback_url
try:
fallback_url = reverse(fallback_url)
except NoReverseMatch:
if callable(fallback_url):
raise
if "/" not in fallback_url and "." not in fallback_url:
raise
# assert the fallback URL is safe to return to caller. if it is
# determined unsafe then raise an exception as the fallback value comes
# from the a source the developer choose.
is_safe(fallback_url, raise_on_fail=True)
return fallback_url


def user_display(user):
Expand Down Expand Up @@ -142,7 +141,4 @@ def check_password_expired(user):
now = timezone.now()
expiration = latest.timestamp + datetime.timedelta(seconds=expiry)

if expiration < now:
return True
else:
return False
return bool(expiration < now)
15 changes: 9 additions & 6 deletions account/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
from account.utils import default_redirect, get_form_data, is_ajax


class PasswordMixin(object):
class PasswordMixin:
"""
Mixin handling common elements of password change.
Expand Down Expand Up @@ -274,7 +274,7 @@ def create_user(self, form, commit=True, model=None, **kwargs):
user.save()
return user

def create_account(self, form):
def create_account(self, form): # skipcq: PYL-W0613
return Account.create(request=self.request, user=self.created_user, create_email=False)

def generate_username(self, form):
Expand All @@ -283,7 +283,7 @@ def generate_username(self, form):
"Override SignupView.generate_username in a subclass."
)

def create_email_address(self, form, **kwargs):
def create_email_address(self, form, **kwargs): # skipcq: PYL-W0613
kwargs.setdefault("primary", True)
kwargs.setdefault("verified", False)
if self.signup_code:
Expand Down Expand Up @@ -409,7 +409,8 @@ def form_valid(self, form):
self.after_login(form)
return redirect(self.get_success_url())

def after_login(self, form):
@staticmethod
def after_login(form):
signals.user_logged_in.send(sender=LoginView, user=form.user, form=form)

def get_success_url(self, fallback_url=None, **kwargs):
Expand Down Expand Up @@ -533,7 +534,8 @@ def get_object(self, queryset=None):
except EmailConfirmation.DoesNotExist:
raise Http404()

def get_queryset(self):
@staticmethod
def get_queryset():
qs = EmailConfirmation.objects.all()
qs = qs.select_related("email_address__user")
return qs
Expand All @@ -550,7 +552,8 @@ def get_redirect_url(self):
return settings.ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL
return settings.ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL

def after_confirmation(self, confirmation):
@staticmethod
def after_confirmation(confirmation):
user = confirmation.email_address.user
user.is_active = True
user.save()
Expand Down

0 comments on commit 75eaad8

Please sign in to comment.