Update syntax for relative imports
[pgweb/local.git] / pgweb / account / forms.py
blob8196c543c16b779c97498ea73654ab12e2381843
1 from django import forms
2 from django.contrib.auth.forms import AuthenticationForm
4 import re
6 from django.contrib.auth.models import User
7 from pgweb.core.models import UserProfile
8 from pgweb.contributors.models import Contributor
10 from .recaptcha import ReCaptchaField
12 import logging
13 log = logging.getLogger(__name__)
16 def _clean_username(username):
17 username = username.lower()
19 if not re.match('^[a-z0-9\.-]+$', username):
20 raise forms.ValidationError("Invalid character in user name. Only a-z, 0-9, . and - allowed for compatibility with third party software.")
21 try:
22 User.objects.get(username=username)
23 except User.DoesNotExist:
24 return username
25 raise forms.ValidationError("This username is already in use")
28 # Override some error handling only in the default authentication form
29 class PgwebAuthenticationForm(AuthenticationForm):
30 def clean(self):
31 try:
32 return super(PgwebAuthenticationForm, self).clean()
33 except ValueError as e:
34 if e.message.startswith('Unknown password hashing algorithm'):
35 # This is *probably* a user trying to log in with an account that has not
36 # been set up properly yet. It could be an actually unsupported hashing
37 # algorithm, but we'll deal with that when we get there.
38 self._errors["__all__"] = self.error_class(["This account appears not to be properly initialized. Make sure you complete the signup process with the instructions in the email received before trying to use the account."])
39 log.warning("User {0} tried to log in with invalid hash, probably because signup was completed.".format(self.cleaned_data['username']))
40 return self.cleaned_data
41 raise e
44 class CommunityAuthConsentForm(forms.Form):
45 consent = forms.BooleanField(help_text='Consent to sharing this data')
46 next = forms.CharField(widget=forms.widgets.HiddenInput())
48 def __init__(self, orgname, *args, **kwargs):
49 self.orgname = orgname
50 super(CommunityAuthConsentForm, self).__init__(*args, **kwargs)
52 self.fields['consent'].label = 'Consent to sharing data with {0}'.format(self.orgname)
55 class SignupForm(forms.Form):
56 username = forms.CharField(max_length=30)
57 first_name = forms.CharField(max_length=30)
58 last_name = forms.CharField(max_length=30)
59 email = forms.EmailField()
60 email2 = forms.EmailField(label="Repeat email")
61 captcha = ReCaptchaField()
63 def __init__(self, remoteip, *args, **kwargs):
64 super(SignupForm, self).__init__(*args, **kwargs)
65 self.fields['captcha'].set_ip(remoteip)
67 def clean_email2(self):
68 # If the primary email checker had an exception, the data will be gone
69 # from the cleaned_data structure
70 if 'email' not in self.cleaned_data:
71 return self.cleaned_data['email2']
72 email1 = self.cleaned_data['email'].lower()
73 email2 = self.cleaned_data['email2'].lower()
75 if email1 != email2:
76 raise forms.ValidationError("Email addresses don't match")
77 return email2
79 def clean_username(self):
80 return _clean_username(self.cleaned_data['username'])
82 def clean_email(self):
83 email = self.cleaned_data['email'].lower()
85 try:
86 User.objects.get(email=email)
87 except User.DoesNotExist:
88 return email
89 raise forms.ValidationError("A user with this email address is already registered")
92 class SignupOauthForm(forms.Form):
93 username = forms.CharField(max_length=30)
94 first_name = forms.CharField(max_length=30, required=False)
95 last_name = forms.CharField(max_length=30, required=False)
96 email = forms.EmailField()
97 captcha = ReCaptchaField()
99 def __init__(self, *args, **kwargs):
100 super(SignupOauthForm, self).__init__(*args, **kwargs)
101 self.fields['first_name'].widget.attrs['readonly'] = True
102 self.fields['first_name'].widget.attrs['disabled'] = True
103 self.fields['last_name'].widget.attrs['readonly'] = True
104 self.fields['last_name'].widget.attrs['disabled'] = True
105 self.fields['email'].widget.attrs['readonly'] = True
106 self.fields['email'].widget.attrs['disabled'] = True
108 def clean_username(self):
109 return _clean_username(self.cleaned_data['username'])
111 def clean_email(self):
112 return self.cleaned_data['email'].lower()
115 class UserProfileForm(forms.ModelForm):
116 class Meta:
117 model = UserProfile
118 exclude = ('user',)
121 class UserForm(forms.ModelForm):
122 def __init__(self, *args, **kwargs):
123 super(UserForm, self).__init__(*args, **kwargs)
124 self.fields['first_name'].required = True
125 self.fields['last_name'].required = True
127 class Meta:
128 model = User
129 fields = ('first_name', 'last_name', )
132 class ContributorForm(forms.ModelForm):
133 class Meta:
134 model = Contributor
135 exclude = ('ctype', 'lastname', 'firstname', 'user', )
138 class ChangeEmailForm(forms.Form):
139 email = forms.EmailField()
140 email2 = forms.EmailField(label="Repeat email")
142 def __init__(self, user, *args, **kwargs):
143 super(ChangeEmailForm, self).__init__(*args, **kwargs)
144 self.user = user
146 def clean_email(self):
147 email = self.cleaned_data['email'].lower()
149 if email == self.user.email:
150 raise forms.ValidationError("This is your existing email address!")
152 if User.objects.filter(email=email).exists():
153 raise forms.ValidationError("A user with this email address is already registered")
155 return email
157 def clean_email2(self):
158 # If the primary email checker had an exception, the data will be gone
159 # from the cleaned_data structure
160 if 'email' not in self.cleaned_data:
161 return self.cleaned_data['email2'].lower()
162 email1 = self.cleaned_data['email'].lower()
163 email2 = self.cleaned_data['email2'].lower()
165 if email1 != email2:
166 raise forms.ValidationError("Email addresses don't match")
167 return email2
170 class PgwebPasswordResetForm(forms.Form):
171 email = forms.EmailField()