You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

forms.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import string
  2. import urlparse
  3. import random
  4. from django import forms
  5. from django.conf import settings
  6. from django.contrib.auth import forms as auth_forms
  7. from django.contrib.auth.forms import AuthenticationForm
  8. from django.contrib.auth.tokens import default_token_generator
  9. from django.contrib.sites.models import get_current_site
  10. from django.core import validators
  11. from django.core.exceptions import ObjectDoesNotExist
  12. from django.core.exceptions import ValidationError
  13. from django.db.models import get_model
  14. from django.utils.translation import ugettext_lazy as _
  15. from oscar.core.loading import get_profile_class, get_class
  16. from oscar.core.compat import get_user_model
  17. from oscar.apps.customer.utils import get_password_reset_url, normalise_email
  18. Dispatcher = get_class('customer.utils', 'Dispatcher')
  19. CommunicationEventType = get_model('customer', 'communicationeventtype')
  20. ProductAlert = get_model('customer', 'ProductAlert')
  21. User = get_user_model()
  22. def generate_username():
  23. uname = ''.join([random.choice(string.letters + string.digits + '_') for i in range(30)])
  24. try:
  25. User.objects.get(username=uname)
  26. return generate_username()
  27. except User.DoesNotExist:
  28. return uname
  29. class PasswordResetForm(auth_forms.PasswordResetForm):
  30. communication_type_code = "PASSWORD_RESET"
  31. def save(self, domain_override=None,
  32. subject_template_name='registration/password_reset_subject.txt',
  33. email_template_name='registration/password_reset_email.html',
  34. use_https=False, token_generator=default_token_generator,
  35. from_email=None, request=None, **kwargs):
  36. """
  37. Generates a one-use only link for resetting password and sends to the
  38. user.
  39. """
  40. site = get_current_site(request)
  41. if domain_override is not None:
  42. site.domain = site.name = domain_override
  43. for user in self.users_cache:
  44. # Build reset url
  45. reset_url = "%s://%s%s" % (
  46. 'https' if use_https else 'http',
  47. site.domain,
  48. get_password_reset_url(user))
  49. ctx = {
  50. 'user': user,
  51. 'site': site,
  52. 'reset_url': reset_url}
  53. messages = CommunicationEventType.objects.get_and_render(
  54. code=self.communication_type_code, context=ctx)
  55. Dispatcher().dispatch_user_messages(user, messages)
  56. class EmailAuthenticationForm(AuthenticationForm):
  57. """
  58. Extends the standard django AuthenticationForm, to support 75 character
  59. usernames. 75 character usernames are needed to support the EmailOrUsername
  60. auth backend.
  61. """
  62. username = forms.EmailField(label=_('Email Address'))
  63. redirect_url = forms.CharField(
  64. widget=forms.HiddenInput, required=False)
  65. def __init__(self, host, *args, **kwargs):
  66. self.host = host
  67. super(EmailAuthenticationForm, self).__init__(*args, **kwargs)
  68. def clean_redirect_url(self):
  69. url = self.cleaned_data['redirect_url'].strip()
  70. if not url:
  71. return settings.LOGIN_REDIRECT_URL
  72. host = urlparse.urlparse(url)[1]
  73. if host and host != self.host:
  74. return settings.LOGIN_REDIRECT_URL
  75. return url
  76. class CommonPasswordValidator(validators.BaseValidator):
  77. # See http://www.smartplanet.com/blog/business-brains/top-20-most-common-passwords-of-all-time-revealed-8216123456-8216princess-8216qwerty/4519
  78. forbidden_passwords = [
  79. 'password',
  80. '1234',
  81. '12345'
  82. '123456',
  83. '123456y',
  84. '123456789',
  85. 'iloveyou',
  86. 'princess',
  87. 'monkey',
  88. 'rockyou',
  89. 'babygirl',
  90. 'monkey',
  91. 'qwerty',
  92. '654321',
  93. 'dragon',
  94. 'pussy',
  95. 'baseball',
  96. 'football',
  97. 'letmein',
  98. 'monkey',
  99. '696969',
  100. 'abc123',
  101. 'qwe123',
  102. 'qweasd',
  103. 'mustang',
  104. 'michael',
  105. 'shadow',
  106. 'master',
  107. 'jennifer',
  108. '111111',
  109. '2000',
  110. 'jordan',
  111. 'superman'
  112. 'harley'
  113. ]
  114. message = _("Please choose a less common password")
  115. code = 'password'
  116. def __init__(self, password_file=None):
  117. self.limit_value = password_file
  118. def clean(self, value):
  119. return value.strip()
  120. def compare(self, value, limit):
  121. return value in self.forbidden_passwords
  122. def get_forbidden_passwords(self):
  123. if self.limit_value is None:
  124. return self.forbidden_passwords
  125. class EmailUserCreationForm(forms.ModelForm):
  126. email = forms.EmailField(label=_('Email address'))
  127. password1 = forms.CharField(
  128. label=_('Password'), widget=forms.PasswordInput,
  129. validators=[validators.MinLengthValidator(6),
  130. CommonPasswordValidator()])
  131. password2 = forms.CharField(
  132. label=_('Confirm password'), widget=forms.PasswordInput)
  133. redirect_url = forms.CharField(
  134. widget=forms.HiddenInput, required=False)
  135. class Meta:
  136. model = User
  137. fields = ('email',)
  138. def __init__(self, host=None, *args, **kwargs):
  139. self.host = host
  140. super(EmailUserCreationForm, self).__init__(*args, **kwargs)
  141. def clean_email(self):
  142. email = normalise_email(self.cleaned_data['email'])
  143. if User._default_manager.filter(email=email).exists():
  144. raise forms.ValidationError(
  145. _("A user with that email address already exists."))
  146. return email
  147. def clean_password2(self):
  148. password1 = self.cleaned_data.get('password1', '')
  149. password2 = self.cleaned_data.get('password2', '')
  150. if password1 != password2:
  151. raise forms.ValidationError(
  152. _("The two password fields didn't match."))
  153. return password2
  154. def clean_redirect_url(self):
  155. url = self.cleaned_data['redirect_url'].strip()
  156. if not url:
  157. return settings.LOGIN_REDIRECT_URL
  158. host = urlparse.urlparse(url)[1]
  159. if host and self.host and host != self.host:
  160. return settings.LOGIN_REDIRECT_URL
  161. return url
  162. def save(self, commit=True):
  163. user = super(EmailUserCreationForm, self).save(commit=False)
  164. user.set_password(self.cleaned_data['password1'])
  165. if 'username' in [f.name for f in User._meta.fields]:
  166. user.username = generate_username()
  167. if commit:
  168. user.save()
  169. return user
  170. class SearchByDateRangeForm(forms.Form):
  171. date_from = forms.DateField(required=False, label=_("From"))
  172. date_to = forms.DateField(required=False, label=_("To"))
  173. def clean(self):
  174. if self.is_valid() and not self.cleaned_data['date_from'] and not self.cleaned_data['date_to']:
  175. raise forms.ValidationError(_("At least one date field is required."))
  176. return super(SearchByDateRangeForm, self).clean()
  177. def description(self):
  178. if not self.is_bound or not self.is_valid():
  179. return _('All orders')
  180. date_from = self.cleaned_data['date_from']
  181. date_to = self.cleaned_data['date_to']
  182. if date_from and date_to:
  183. return _('Orders placed between %(date_from)s and %(date_to)s') % {
  184. 'date_from': date_from,
  185. 'date_to': date_to}
  186. elif date_from:
  187. return _('Orders placed since %s') % date_from
  188. elif date_to:
  189. return _('Orders placed until %s') % date_to
  190. def get_filters(self):
  191. date_from = self.cleaned_data['date_from']
  192. date_to = self.cleaned_data['date_to']
  193. if date_from and date_to:
  194. return {'date_placed__range': [date_from, date_to]}
  195. elif date_from and not date_to:
  196. return {'date_placed__gt': date_from}
  197. elif not date_from and date_to:
  198. return {'date_placed__lt': date_to}
  199. return {}
  200. class UserForm(forms.ModelForm):
  201. def __init__(self, user, *args, **kwargs):
  202. self.user = user
  203. kwargs['instance'] = user
  204. super(UserForm, self).__init__(*args, **kwargs)
  205. if 'email' in self.fields:
  206. self.fields['email'].required = True
  207. def clean_email(self):
  208. """
  209. Make sure that the email address is aways unique as it is
  210. used instead of the username. This is necessary because the
  211. unique-ness of email addresses is *not* enforced on the model
  212. level in ``django.contrib.auth.models.User``.
  213. """
  214. email = normalise_email(self.cleaned_data['email'])
  215. if User._default_manager.filter(
  216. email=email).exclude(id=self.user.id).exists():
  217. raise ValidationError(
  218. _("A user with this email address already exists"))
  219. return email
  220. class Meta:
  221. model = User
  222. exclude = ('username', 'password', 'is_staff', 'is_superuser',
  223. 'is_active', 'last_login', 'date_joined',
  224. 'user_permissions', 'groups')
  225. Profile = get_profile_class()
  226. if Profile:
  227. class UserAndProfileForm(forms.ModelForm):
  228. email = forms.EmailField(label=_('Email address'), required=True)
  229. def __init__(self, user, *args, **kwargs):
  230. self.user = user
  231. try:
  232. instance = Profile.objects.get(user=user)
  233. except ObjectDoesNotExist:
  234. # User has no profile, try a blank one
  235. instance = Profile(user=user)
  236. kwargs['instance'] = instance
  237. super(UserAndProfileForm, self).__init__(*args, **kwargs)
  238. # Get a list of profile fields to help with ordering later
  239. profile_field_names = self.fields.keys()
  240. del profile_field_names[profile_field_names.index('email')]
  241. self.fields['email'].initial = self.instance.user.email
  242. # Add user fields (we look for core user fields first)
  243. core_field_names = set([f.name for f in User._meta.fields])
  244. user_field_names = ['email']
  245. for field_name in ('first_name', 'last_name'):
  246. if field_name in core_field_names:
  247. user_field_names.append(field_name)
  248. user_field_names.extend(User._meta.additional_fields)
  249. # Store user fields so we know what to save later
  250. self.user_field_names = user_field_names
  251. # Add additional user fields
  252. additional_fields = forms.fields_for_model(
  253. User, fields=user_field_names)
  254. self.fields.update(additional_fields)
  255. # Set initial values
  256. for field_name in user_field_names:
  257. self.fields[field_name].initial = getattr(user, field_name)
  258. # Ensure order of fields is email, user fields then profile fields
  259. self.fields.keyOrder = user_field_names + profile_field_names
  260. class Meta:
  261. model = Profile
  262. exclude = ('user',)
  263. def clean_email(self):
  264. email = normalise_email(self.cleaned_data['email'])
  265. if User._default_manager.filter(
  266. email=email).exclude(id=self.user.id).exists():
  267. raise ValidationError(
  268. _("A user with this email address already exists"))
  269. return email
  270. def save(self, *args, **kwargs):
  271. user = self.instance.user
  272. # Save user also
  273. for field_name in self.user_field_names:
  274. setattr(user, field_name, self.cleaned_data[field_name])
  275. user.save()
  276. return super(ProfileForm, self).save(*args, **kwargs)
  277. ProfileForm = UserAndProfileForm
  278. else:
  279. ProfileForm = UserForm
  280. class ProductAlertForm(forms.ModelForm):
  281. email = forms.EmailField(required=True, label=_(u'Send notification to'),
  282. widget=forms.TextInput(attrs={
  283. 'placeholder': _('Enter your email')
  284. }))
  285. def __init__(self, user, product, *args, **kwargs):
  286. self.user = user
  287. self.product = product
  288. super(ProductAlertForm, self).__init__(*args, **kwargs)
  289. # Only show email field to unauthenticated users
  290. if user and user.is_authenticated():
  291. self.fields['email'].widget = forms.HiddenInput()
  292. self.fields['email'].required = False
  293. def save(self, commit=True):
  294. alert = super(ProductAlertForm, self).save(commit=False)
  295. if self.user.is_authenticated():
  296. alert.user = self.user
  297. alert.product = self.product
  298. if commit:
  299. alert.save()
  300. return alert
  301. def clean(self):
  302. cleaned_data = self.cleaned_data
  303. email = cleaned_data.get('email')
  304. if email:
  305. try:
  306. ProductAlert.objects.get(
  307. product=self.product, email=email,
  308. status=ProductAlert.ACTIVE)
  309. except ProductAlert.DoesNotExist:
  310. pass
  311. else:
  312. raise forms.ValidationError(_(
  313. "There is already an active stock alert for %s") % email)
  314. elif self.user.is_authenticated():
  315. try:
  316. ProductAlert.objects.get(product=self.product,
  317. user=self.user,
  318. status=ProductAlert.ACTIVE)
  319. except ProductAlert.DoesNotExist:
  320. pass
  321. else:
  322. raise forms.ValidationError(_(
  323. "You already have an active alert for this product"))
  324. return cleaned_data
  325. class Meta:
  326. model = ProductAlert
  327. exclude = ('user', 'key',
  328. 'status', 'date_confirmed', 'date_cancelled', 'date_closed',
  329. 'product')