From be218a1e0d5405541f30ac5b5acea4f982d1796c Mon Sep 17 00:00:00 2001 From: Samuel Gaist <samuel.gaist@idiap.ch> Date: Fri, 11 Sep 2020 14:43:33 +0200 Subject: [PATCH] [ui][registration][all] Pre-commit cleanup --- beat/web/ui/registration/admin.py | 2 +- beat/web/ui/registration/forms.py | 372 +++++++++++++++++----------- beat/web/ui/registration/signals.py | 1 - beat/web/ui/registration/views.py | 56 +++-- 4 files changed, 257 insertions(+), 174 deletions(-) diff --git a/beat/web/ui/registration/admin.py b/beat/web/ui/registration/admin.py index 6768db83d..0180c5f66 100644 --- a/beat/web/ui/registration/admin.py +++ b/beat/web/ui/registration/admin.py @@ -27,8 +27,8 @@ from django.contrib import admin -from .models import RegistrationProfile from .models import PreregistrationProfile +from .models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): diff --git a/beat/web/ui/registration/forms.py b/beat/web/ui/registration/forms.py index 6bcb3a391..99b3d3306 100644 --- a/beat/web/ui/registration/forms.py +++ b/beat/web/ui/registration/forms.py @@ -29,25 +29,22 @@ Forms and validation code for user registration. """ - import datetime -from django.contrib.auth.models import User from django import forms -from django.conf import settings +from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ -from .models import RegistrationProfile -from .models import PreregistrationProfile - -from ...accounts.models import SupervisionTrack from ...accounts.models import Profile +from ...accounts.models import SupervisionTrack +from .models import PreregistrationProfile +from .models import RegistrationProfile # I put this on all required fields, because it's easier to pick up # on them with CSS or JavaScript if they have a class of "required" # in the HTML. Your mileage may vary. If/when Django ticket #3515 # lands in trunk, this will no longer be necessary. -attrs_dict = { 'class': 'required' } +attrs_dict = {"class": "required"} class RegistrationForm(forms.Form): @@ -63,30 +60,42 @@ class RegistrationForm(forms.Form): """ - username = forms.RegexField(regex=r'^\w+$', - max_length=30, - widget=forms.TextInput(attrs=attrs_dict), - label=_(u'Username')) - first_name = forms.RegexField(regex=r'^[\w ]+$', - max_length=30, - widget=forms.TextInput(attrs=attrs_dict), - label=_(u'First name')) - last_name = forms.RegexField(regex=r'^[\w ]+$', - max_length=30, - widget=forms.TextInput(attrs=attrs_dict), - label=_(u'Last name')) - email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, - maxlength=75)), - label=_(u'Institutional E-mail address')) - password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), - label=_(u'Password')) - password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), - label=_(u'Password (again)')) - supervisor = forms.RegexField(regex=r'^\w+$', - max_length=30, - widget=forms.TextInput(attrs=attrs_dict), - label=_(u'Supervisor Username')) - + username = forms.RegexField( + regex=r"^\w+$", + max_length=30, + widget=forms.TextInput(attrs=attrs_dict), + label=_(u"Username"), + ) + first_name = forms.RegexField( + regex=r"^[\w ]+$", + max_length=30, + widget=forms.TextInput(attrs=attrs_dict), + label=_(u"First name"), + ) + last_name = forms.RegexField( + regex=r"^[\w ]+$", + max_length=30, + widget=forms.TextInput(attrs=attrs_dict), + label=_(u"Last name"), + ) + email = forms.EmailField( + widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), + label=_(u"Institutional E-mail address"), + ) + password1 = forms.CharField( + widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), + label=_(u"Password"), + ) + password2 = forms.CharField( + widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), + label=_(u"Password (again)"), + ) + supervisor = forms.RegexField( + regex=r"^\w+$", + max_length=30, + widget=forms.TextInput(attrs=attrs_dict), + label=_(u"Supervisor Username"), + ) def clean_username(self): """ @@ -94,11 +103,13 @@ class RegistrationForm(forms.Form): in use. """ - try: - user = User.objects.get(username__iexact=self.cleaned_data['username']) - except User.DoesNotExist: - return self.cleaned_data['username'] - raise forms.ValidationError(_(u'This username is already taken. Please choose another.')) + username = self.cleaned_data["username"] + if User.objects.filter(username__iexact=username).exists(): + raise forms.ValidationError( + _(u"This username is already taken. Please choose another.") + ) + + return username def clean_supervisor(self): """ @@ -106,17 +117,22 @@ class RegistrationForm(forms.Form): """ try: - user = User.objects.get(username__iexact=self.cleaned_data['supervisor']) + user = User.objects.get(username__iexact=self.cleaned_data["supervisor"]) if user.profile.status == Profile.BLOCKED: - raise forms.ValidationError(_(u'This user is not a valid supervisor. Please choose another.')) + raise forms.ValidationError( + _(u"This user is not a valid supervisor. Please choose another.") + ) except User.DoesNotExist: - raise forms.ValidationError(_(u'This supervisor username does not exist. Please choose another.')) + raise forms.ValidationError( + _(u"This supervisor username does not exist. Please choose another.") + ) if not user.profile.is_supervisor: - raise forms.ValidationError(_(u'This user is not a recognized supervisor. Please choose another.')) - - return self.cleaned_data['supervisor'] + raise forms.ValidationError( + _(u"This user is not a recognized supervisor. Please choose another.") + ) + return self.cleaned_data["supervisor"] def clean(self): """ @@ -126,9 +142,11 @@ class RegistrationForm(forms.Form): field. """ - if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: - if self.cleaned_data['password1'] != self.cleaned_data['password2']: - self._errors["password2"] = self.error_class([_(u'You must type the same password each time')]) + if "password1" in self.cleaned_data and "password2" in self.cleaned_data: + if self.cleaned_data["password1"] != self.cleaned_data["password2"]: + self._errors["password2"] = self.error_class( + [_(u"You must type the same password each time")] + ) del self.cleaned_data["password1"] del self.cleaned_data["password2"] @@ -143,23 +161,23 @@ class RegistrationForm(forms.Form): """ new_user = RegistrationProfile.objects.create_inactive_user( - username=self.cleaned_data['username'], - first_name=self.cleaned_data['first_name'], - last_name=self.cleaned_data['last_name'], - password=self.cleaned_data['password1'], - email=self.cleaned_data['email'], + username=self.cleaned_data["username"], + first_name=self.cleaned_data["first_name"], + last_name=self.cleaned_data["last_name"], + password=self.cleaned_data["password1"], + email=self.cleaned_data["email"], ) - #Create and assign key - new_user.profile.supervision_key = new_user.profile._generate_current_supervision_key() - supervisor = User.objects.get(username = self.cleaned_data['supervisor']) + # Create and assign key + new_user.profile.supervision_key = ( + new_user.profile._generate_current_supervision_key() + ) + supervisor = User.objects.get(username=self.cleaned_data["supervisor"]) supervisiontrack = SupervisionTrack.objects.create( - supervisee = new_user, - supervisor = supervisor, - is_valid = False, + supervisee=new_user, supervisor=supervisor, is_valid=False, ) - #Assign key to supervision track + # Assign key to supervision track supervisiontrack.supervision_key = new_user.profile.supervision_key supervisiontrack.save() new_user.profile.is_supervisor = False @@ -168,7 +186,6 @@ class RegistrationForm(forms.Form): new_user.profile.supervision.add(supervisiontrack) new_user.save() - return new_user @@ -176,23 +193,29 @@ class PreregistrationForm(forms.Form): """ Form for pre-registering a new user account. """ - first_name = forms.RegexField(regex=r'^[\w ]+$', - max_length=30, - widget=forms.TextInput(attrs=attrs_dict), - label=_(u'First name')) - last_name = forms.RegexField(regex=r'^[\w ]+$', - max_length=30, - widget=forms.TextInput(attrs=attrs_dict), - label=_(u'Last name')) - email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, - maxlength=75)), - label=_(u'E-mail address')) + + first_name = forms.RegexField( + regex=r"^[\w ]+$", + max_length=30, + widget=forms.TextInput(attrs=attrs_dict), + label=_(u"First name"), + ) + last_name = forms.RegexField( + regex=r"^[\w ]+$", + max_length=30, + widget=forms.TextInput(attrs=attrs_dict), + label=_(u"Last name"), + ) + email = forms.EmailField( + widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), + label=_(u"E-mail address"), + ) def save(self): profile = PreregistrationProfile() - profile.first_name = self.cleaned_data['first_name'] - profile.last_name = self.cleaned_data['last_name'] - profile.email = self.cleaned_data['email'] + profile.first_name = self.cleaned_data["first_name"] + profile.last_name = self.cleaned_data["last_name"] + profile.email = self.cleaned_data["email"] profile.save() return profile @@ -204,10 +227,13 @@ class RegistrationFormTermsOfService(RegistrationForm): for agreeing to a site's Terms of Service. """ + tos = forms.BooleanField( widget=forms.CheckboxInput(attrs=attrs_dict), label=u'I have carefully read the <a href="">Terms of Service</a>, which include the Privacy and Data Protection Terms of Use, and fully agree and undertake to comply with all provisions therein by checking this box.', - error_messages=dict(required=u"You must agree to the Terms of Service in order to register"), + error_messages=dict( + required=u"You must agree to the Terms of Service in order to register" + ), ) @@ -217,15 +243,20 @@ class RegistrationFormUniqueEmail(RegistrationForm): email addresses. """ + def clean_email(self): """ Validate that the supplied email address is unique for the site. """ - if User.objects.filter(email__iexact=self.cleaned_data['email']): - raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.')) - return self.cleaned_data['email'] + if User.objects.filter(email__iexact=self.cleaned_data["email"]): + raise forms.ValidationError( + _( + u"This email address is already in use. Please supply a different email address." + ) + ) + return self.cleaned_data["email"] class RegistrationFormNoFreeEmail(RegistrationForm): @@ -238,9 +269,20 @@ class RegistrationFormNoFreeEmail(RegistrationForm): override the attribute ``bad_domains``. """ - bad_domains = ['aim.com', 'aol.com', 'email.com', 'gmail.com', - 'googlemail.com', 'hotmail.com', 'hushmail.com', - 'msn.com', 'mail.ru', 'mailinator.com', 'live.com'] + + bad_domains = [ + "aim.com", + "aol.com", + "email.com", + "gmail.com", + "googlemail.com", + "hotmail.com", + "hushmail.com", + "msn.com", + "mail.ru", + "mailinator.com", + "live.com", + ] def clean_email(self): """ @@ -248,10 +290,14 @@ class RegistrationFormNoFreeEmail(RegistrationForm): webmail domains. """ - email_domain = self.cleaned_data['email'].split('@')[1] + email_domain = self.cleaned_data["email"].split("@")[1] if email_domain in self.bad_domains: - raise forms.ValidationError(_(u'Registration using free email addresses is prohibited. Please supply a different email address.')) - return self.cleaned_data['email'] + raise forms.ValidationError( + _( + u"Registration using free email addresses is prohibited. Please supply a different email address." + ) + ) + return self.cleaned_data["email"] class BlockedUserRevalidationForm(forms.Form): @@ -267,28 +313,36 @@ class BlockedUserRevalidationForm(forms.Form): """ - username = forms.RegexField(regex=r'^\w+$', - max_length=30, - widget=forms.TextInput(attrs=attrs_dict), - label=_(u'Username')) - password = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), - label=_(u'Password')) - supervisor = forms.RegexField(regex=r'^\w+$', - max_length=30, - widget=forms.TextInput(attrs=attrs_dict), - label=_(u'Supervisor Username (Your account needs to be re-validated by a recognized person)')) - + username = forms.RegexField( + regex=r"^\w+$", + max_length=30, + widget=forms.TextInput(attrs=attrs_dict), + label=_(u"Username"), + ) + password = forms.CharField( + widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), + label=_(u"Password"), + ) + supervisor = forms.RegexField( + regex=r"^\w+$", + max_length=30, + widget=forms.TextInput(attrs=attrs_dict), + label=_( + u"Supervisor Username (Your account needs to be re-validated by a recognized person)" + ), + ) def clean_username(self): """ Validate that the username is alphanumeric and user exists """ - try: - user = User.objects.get(username__iexact=self.cleaned_data['username']) - return self.cleaned_data['username'] - except User.DoesNotExist: - raise forms.ValidationError(_(u'This username has not been recognized')) + username = self.cleaned_data["username"] + + if not User.objects.filter(username__iexact=username).exists(): + raise forms.ValidationError(_(u"This username has not been recognized")) + + return username def clean_supervisor(self): """ @@ -296,15 +350,18 @@ class BlockedUserRevalidationForm(forms.Form): """ try: - user = User.objects.get(username__iexact=self.cleaned_data['supervisor']) + user = User.objects.get(username__iexact=self.cleaned_data["supervisor"]) except User.DoesNotExist: - raise forms.ValidationError(_(u'This supervisor username does not exist. Please choose another.')) + raise forms.ValidationError( + _(u"This supervisor username does not exist. Please choose another.") + ) if not user.profile.is_supervisor: - raise forms.ValidationError(_(u'This user is not a recognized supervisor. Please choose another.')) - - return self.cleaned_data['supervisor'] + raise forms.ValidationError( + _(u"This user is not a recognized supervisor. Please choose another.") + ) + return self.cleaned_data["supervisor"] def clean(self): """ @@ -314,9 +371,11 @@ class BlockedUserRevalidationForm(forms.Form): field. """ - if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: - if self.cleaned_data['password1'] != self.cleaned_data['password2']: - self._errors["password2"] = self.error_class([_(u'You must type the same password each time')]) + if "password1" in self.cleaned_data and "password2" in self.cleaned_data: + if self.cleaned_data["password1"] != self.cleaned_data["password2"]: + self._errors["password2"] = self.error_class( + [_(u"You must type the same password each time")] + ) del self.cleaned_data["password1"] del self.cleaned_data["password2"] @@ -336,25 +395,36 @@ class RegistrationSupervisorForm(forms.Form): """ - username = forms.RegexField(regex=r'^\w+$', - max_length=30, - widget=forms.TextInput(attrs=attrs_dict), - label=_(u'Username')) - first_name = forms.RegexField(regex=r'^[\w ]+$', - max_length=30, - widget=forms.TextInput(attrs=attrs_dict), - label=_(u'First name')) - last_name = forms.RegexField(regex=r'^[\w ]+$', - max_length=30, - widget=forms.TextInput(attrs=attrs_dict), - label=_(u'Last name')) - email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, - maxlength=75)), - label=_(u'Institutional E-mail address')) - password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), - label=_(u'Password')) - password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), - label=_(u'Password (again)')) + username = forms.RegexField( + regex=r"^\w+$", + max_length=30, + widget=forms.TextInput(attrs=attrs_dict), + label=_(u"Username"), + ) + first_name = forms.RegexField( + regex=r"^[\w ]+$", + max_length=30, + widget=forms.TextInput(attrs=attrs_dict), + label=_(u"First name"), + ) + last_name = forms.RegexField( + regex=r"^[\w ]+$", + max_length=30, + widget=forms.TextInput(attrs=attrs_dict), + label=_(u"Last name"), + ) + email = forms.EmailField( + widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), + label=_(u"Institutional E-mail address"), + ) + password1 = forms.CharField( + widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), + label=_(u"Password"), + ) + password2 = forms.CharField( + widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), + label=_(u"Password (again)"), + ) def clean_username(self): """ @@ -362,11 +432,12 @@ class RegistrationSupervisorForm(forms.Form): in use. """ - try: - user = User.objects.get(username__iexact=self.cleaned_data['username']) - except User.DoesNotExist: - return self.cleaned_data['username'] - raise forms.ValidationError(_(u'This username is already taken. Please choose another.')) + username = self.cleaned_data["username"] + if User.objects.get(username__iexact=username).exists(): + raise forms.ValidationError( + _(u"This username is already taken. Please choose another.") + ) + return username def clean(self): """ @@ -376,9 +447,11 @@ class RegistrationSupervisorForm(forms.Form): field. """ - if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: - if self.cleaned_data['password1'] != self.cleaned_data['password2']: - self._errors["password2"] = self.error_class([_(u'You must type the same password each time')]) + if "password1" in self.cleaned_data and "password2" in self.cleaned_data: + if self.cleaned_data["password1"] != self.cleaned_data["password2"]: + self._errors["password2"] = self.error_class( + [_(u"You must type the same password each time")] + ) del self.cleaned_data["password1"] del self.cleaned_data["password2"] @@ -393,31 +466,36 @@ class RegistrationSupervisorForm(forms.Form): """ new_user = RegistrationProfile.objects.create_inactive_user( - username=self.cleaned_data['username'], - first_name=self.cleaned_data['first_name'], - last_name=self.cleaned_data['last_name'], - password=self.cleaned_data['password1'], - email=self.cleaned_data['email'], - ) + username=self.cleaned_data["username"], + first_name=self.cleaned_data["first_name"], + last_name=self.cleaned_data["last_name"], + password=self.cleaned_data["password1"], + email=self.cleaned_data["email"], + ) - #Create and assign key - new_user.profile.supervision_key = new_user.profile._generate_current_supervision_key() + # Create and assign key + new_user.profile.supervision_key = ( + new_user.profile._generate_current_supervision_key() + ) new_user.profile.is_supervisor = True new_user.profile.status = Profile.NEWUSER new_user.profile.registration_date = datetime.datetime.now() new_user.save() - return new_user + class RegistrationFormTermsOfServiceSupervisor(RegistrationSupervisorForm): """ Subclass of ``RegistrationForm`` which adds a required checkbox for agreeing to a site's Terms of Service. """ + tos = forms.BooleanField( - widget=forms.CheckboxInput(attrs=attrs_dict), - label=u'I have carefully read the <a href="">Terms of Service</a>, which include the Privacy and Data Protection Terms of Use, and fully agree and undertake to comply with all provisions therein by checking this box.', - error_messages=dict(required=u"You must agree to the Terms of Service in order to register"), - ) + widget=forms.CheckboxInput(attrs=attrs_dict), + label=u'I have carefully read the <a href="">Terms of Service</a>, which include the Privacy and Data Protection Terms of Use, and fully agree and undertake to comply with all provisions therein by checking this box.', + error_messages=dict( + required=u"You must agree to the Terms of Service in order to register" + ), + ) diff --git a/beat/web/ui/registration/signals.py b/beat/web/ui/registration/signals.py index 96209135f..099307c21 100644 --- a/beat/web/ui/registration/signals.py +++ b/beat/web/ui/registration/signals.py @@ -27,7 +27,6 @@ from django.dispatch import Signal - # A new user has registered. user_registered = Signal(providing_args=["user"]) diff --git a/beat/web/ui/registration/views.py b/beat/web/ui/registration/views.py index c706167c7..ace307d40 100644 --- a/beat/web/ui/registration/views.py +++ b/beat/web/ui/registration/views.py @@ -29,12 +29,10 @@ Views which allow users to create and activate accounts. """ - - from django.conf import settings -from django.urls import reverse from django.http import HttpResponseRedirect from django.shortcuts import render +from django.urls import reverse from django.views.decorators.csrf import csrf_protect from .forms import RegistrationFormTermsOfService @@ -43,9 +41,12 @@ from .forms import RegistrationSupervisorForm from .models import RegistrationProfile -def activate(request, activation_key, - template_name='registration/activate.html', - extra_context=None): +def activate( + request, + activation_key, + template_name="registration/activate.html", + extra_context=None, +): """ Activate a ``User``'s account from an activation key, if their key is valid and hasn't expired. @@ -89,11 +90,10 @@ def activate(request, activation_key, registration/activate.html or ``template_name`` keyword argument. """ - activationKey = activation_key.lower() # Normalize before trying anything with it. + account = RegistrationProfile.objects.activate_user(activation_key) - context = { 'account': account, - 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS } + context = {"account": account, "expiration_days": settings.ACCOUNT_ACTIVATION_DAYS} if extra_context is not None: for key, value in extra_context.items(): @@ -103,10 +103,13 @@ def activate(request, activation_key, @csrf_protect -def register(request, success_url=None, - form_class=RegistrationFormTermsOfService, - template_name='registration/registration_form.html', - extra_context=None): +def register( + request, + success_url=None, + form_class=RegistrationFormTermsOfService, + template_name="registration/registration_form.html", + extra_context=None, +): """ Allow a new user to register an account. @@ -164,17 +167,19 @@ def register(request, success_url=None, supervisor_form_active = False - if request.GET.get('registration') == "supervisor": + if request.GET.get("registration") == "supervisor": supervisor_form_active = True - if request.method == 'POST': + if request.method == "POST": # Check the form - if 'supervisor' not in request.POST: + if "supervisor" not in request.POST: supervisor_form_active = True - form_supervisor = RegistrationSupervisorForm(data=request.POST, files=request.FILES) + form_supervisor = RegistrationSupervisorForm( + data=request.POST, files=request.FILES + ) form = form_class() if form_supervisor.is_valid(): - new_user = form_supervisor.save() + form_supervisor.save() # success_url needs to be dynamically generated here; setting a # a default value using reverse() will cause circular-import # problems with the default URLConf for this application, which @@ -185,7 +190,7 @@ def register(request, success_url=None, form = form_class(data=request.POST, files=request.FILES) form_supervisor = RegistrationSupervisorForm() if form.is_valid(): - new_user = form.save() + form.save() # success_url needs to be dynamically generated here; setting a # a default value using reverse() will cause circular-import # problems with the default URLConf for this application, which @@ -195,12 +200,13 @@ def register(request, success_url=None, form = form_class() form_supervisor = RegistrationFormTermsOfServiceSupervisor() - - context = { 'form': form, - 'form_supervisor': form_supervisor, - 'supervisor_form_active': supervisor_form_active, - 'documentation_link': settings.DOCUMENTATION_LINK, - 'url_prefix':settings.URL_PREFIX } + context = { + "form": form, + "form_supervisor": form_supervisor, + "supervisor_form_active": supervisor_form_active, + "documentation_link": settings.DOCUMENTATION_LINK, + "url_prefix": settings.URL_PREFIX, + } if extra_context is not None: for key, value in extra_context.items(): -- GitLab