/src/commonutils/nospamform.py

https://github.com/omat/kimlerdensin · Python · 40 lines · 32 code · 7 blank · 1 comment · 4 complexity · 5efbd00759e6db9e6803a9da606c94ed MD5 · raw file

  1. # based on http://www.djangosnippets.org/snippets/417/
  2. from django.newforms.util import ValidationError
  3. from django.utils.translation import ugettext as _
  4. from time import time
  5. from django.conf import settings
  6. from Crypto.Cipher import Blowfish
  7. from base64 import b64encode, b64decode
  8. from django import newforms as forms
  9. def get_key():
  10. cobj = Blowfish.new(settings.SECRET_KEY)
  11. text = unicode(time())
  12. text += "".join(["_" for i in xrange(8-len(text)%8)])
  13. return b64encode(cobj.encrypt(text))
  14. class FormWithKeyField(forms.Form):
  15. def __init__(self, *args, **kwargs):
  16. self.base_fields['key'] = forms.CharField(max_length=100,
  17. widget=forms.widgets.HiddenInput(),
  18. initial=get_key())
  19. super(FormWithKeyField, self).__init__(*args, **kwargs)
  20. def clean_key(self):
  21. def validation_error():
  22. self.data['key'] = get_key()
  23. raise ValidationError(_('Incorrect key.'))
  24. cobj = Blowfish.new(settings.SECRET_KEY)
  25. text = cobj.decrypt(b64decode(self.cleaned_data['key'])).rstrip('_')
  26. try:
  27. key = float(text)
  28. except:
  29. validation_error()
  30. now = time()
  31. if now - key < 10 or now - key > 60*60*6: # valid for 6 hours
  32. validation_error()
  33. return