PageRenderTime 69ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/src/baruwa/accounts/forms.py

https://github.com/sandroden/baruwa
Python | 235 lines | 158 code | 36 blank | 41 comment | 21 complexity | f76990a9d53d71534f25fd8efb51f7ef MD5 | raw file
Possible License(s): GPL-2.0
  1. #
  2. # Baruwa - Web 2.0 MailScanner front-end.
  3. # Copyright (C) 2010-2011 Andrew Colin Kissa <andrew@topdog.za.net>
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License along
  16. # with this program; if not, write to the Free Software Foundation, Inc.,
  17. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. #
  19. # vim: ai ts=4 sts=4 et sw=4
  20. #
  21. from django import forms
  22. from django.forms.util import ErrorList
  23. from django.contrib.auth.models import User
  24. from django.contrib.auth.forms import PasswordResetForm
  25. from django.utils.translation import ugettext as _
  26. from baruwa.accounts.models import UserProfile, UserAddresses
  27. from baruwa.utils.regex import DOM_RE
  28. try:
  29. from django.forms.fields import email_re
  30. except ImportError:
  31. from django.core.validators import email_re
  32. from baruwa.utils.regex import ADDRESS_RE
  33. class PwResetForm(PasswordResetForm):
  34. """
  35. Overload the password reset form to prevent admin and
  36. external accounts from being reset via the interface
  37. """
  38. def clean_email(self):
  39. """
  40. Validates that a user exists with the given e-mail address.
  41. and the user is not an external auth user or admin user
  42. """
  43. email = self.cleaned_data["email"]
  44. self.users_cache = User.objects.filter(email__iexact=email)
  45. if len(self.users_cache) == 0:
  46. raise forms.ValidationError(_("That e-mail address doesn't have"
  47. " an associated user account. Are you sure you've registered?"))
  48. for user in self.users_cache:
  49. if not user.has_usable_password():
  50. raise forms.ValidationError(_("That e-mail address belongs to"
  51. " an externally authenticated account. Please change the"
  52. " password on that external system."))
  53. break
  54. if user.is_superuser:
  55. raise forms.ValidationError(_("That e-mail address belongs to"
  56. " an admin account. Please use the manage.py command to reset"))
  57. break
  58. return email
  59. class UserProfileForm(forms.ModelForm):
  60. id = forms.CharField(widget=forms.HiddenInput)
  61. user_id = forms.CharField(widget=forms.HiddenInput)
  62. class Meta:
  63. model = UserProfile
  64. exclude = ('user',)
  65. class OrdUserProfileForm(forms.ModelForm):
  66. id = forms.CharField(widget=forms.HiddenInput)
  67. user_id = forms.CharField(widget=forms.HiddenInput)
  68. class Meta:
  69. model = UserProfile
  70. exclude = ('user', 'account_type')
  71. class UserCreateForm(forms.ModelForm):
  72. username = forms.RegexField(
  73. label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
  74. help_text = _(
  75. "Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
  76. error_messages = {'invalid': _(
  77. "This value may contain only letters, numbers and @/./+/-/_ characters.")})
  78. password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
  79. def clean_username(self):
  80. username = self.cleaned_data["username"]
  81. try:
  82. User.objects.get(username=username)
  83. except User.DoesNotExist:
  84. return username
  85. raise forms.ValidationError(
  86. _("A user with that username already exists."))
  87. def save(self, commit=True):
  88. user = super(UserCreateForm, self).save(commit=False)
  89. user.set_password(self.cleaned_data["password"])
  90. if commit:
  91. user.save()
  92. return user
  93. class Meta:
  94. model = User
  95. exclude = ('is_staff', 'last_login', 'date_joined',
  96. 'groups', 'user_permissions',)
  97. class UserAddressForm(forms.ModelForm):
  98. """
  99. Used by admin to associate addresses or domains.
  100. """
  101. address = forms.RegexField(regex=ADDRESS_RE,
  102. widget=forms.TextInput(attrs={'size': '50'}))
  103. def clean(self):
  104. """clean_address"""
  105. if self._errors:
  106. return
  107. cleaned_data = self.cleaned_data
  108. address = cleaned_data['address']
  109. user = cleaned_data['user']
  110. if user.is_superuser:
  111. error_msg = _('Super users do not use addresses')
  112. self._errors["address"] = ErrorList([error_msg])
  113. del cleaned_data['address']
  114. account = UserProfile.objects.get(user=user)
  115. if account.account_type == 2:
  116. if not DOM_RE.match(address):
  117. error_msg = _('provide a valid domain address')
  118. self._errors["address"] = ErrorList([error_msg])
  119. del cleaned_data['address']
  120. else:
  121. if not email_re.match(address):
  122. error_msg = _('provide a valid email address')
  123. self._errors["address"] = ErrorList([error_msg])
  124. del cleaned_data['address']
  125. return cleaned_data
  126. class Meta:
  127. model = UserAddresses
  128. exclude = ('id', 'address_type')
  129. class EditAddressForm(forms.ModelForm):
  130. "Edit address"
  131. address = forms.RegexField(
  132. regex=ADDRESS_RE, widget=forms.TextInput(attrs={'size': '50'}))
  133. def clean(self):
  134. """clean_address"""
  135. if self._errors:
  136. return
  137. cleaned_data = self.cleaned_data
  138. address = cleaned_data['address']
  139. user = cleaned_data['user']
  140. if user.is_superuser:
  141. error_msg = _('Super users do not use addresses')
  142. self._errors["address"] = ErrorList([error_msg])
  143. del cleaned_data['address']
  144. account = UserProfile.objects.get(user=user)
  145. if account.account_type == 2:
  146. if not DOM_RE.match(address):
  147. error_msg = _('provide a valid domain address')
  148. self._errors["address"] = ErrorList([error_msg])
  149. del cleaned_data['address']
  150. else:
  151. if not email_re.match(address):
  152. error_msg = _('provide a valid email address')
  153. self._errors["address"] = ErrorList([error_msg])
  154. del cleaned_data['address']
  155. return cleaned_data
  156. class Meta:
  157. model = UserAddresses
  158. exclude = ('id', 'address_type')
  159. class DeleteAddressForm(forms.ModelForm):
  160. "Delete address"
  161. id = forms.CharField(widget=forms.HiddenInput)
  162. class Meta:
  163. model = UserAddresses
  164. exclude = ('address', 'enabled', 'user')
  165. class UserUpdateForm(forms.ModelForm):
  166. """
  167. Allows users to update thier account info.
  168. """
  169. id = forms.CharField(widget=forms.HiddenInput)
  170. class Meta:
  171. model = User
  172. exclude = ('last_login', 'date_joined', 'username',
  173. 'groups', 'is_superuser', 'user_permissions',
  174. 'is_staff', 'password', 'is_active')
  175. class AdminUserUpdateForm(forms.ModelForm):
  176. """
  177. Allows the admins to manage account info
  178. """
  179. username = forms.RegexField(label=_("Username"),
  180. max_length=30, regex=r'^[\w.@+-]+$',
  181. help_text = _(
  182. "Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
  183. error_messages = {'invalid': _(
  184. "This value may contain only letters, numbers and @/./+/-/_ characters.")})
  185. id = forms.CharField(widget=forms.HiddenInput)
  186. class Meta:
  187. model = User
  188. fields = ('id', 'username', 'first_name',
  189. 'last_name', 'email', 'is_superuser', 'is_active')
  190. class DeleteUserForm(forms.ModelForm):
  191. """DeleteUserForm"""
  192. id = forms.CharField(widget=forms.HiddenInput)
  193. class Meta:
  194. model = User
  195. exclude = ('last_login', 'date_joined', 'username',
  196. 'groups', 'is_superuser', 'user_permissions',
  197. 'is_staff', 'password', 'is_active', 'first_name',
  198. 'last_name', 'email')
  199. #fields = ('id')