PageRenderTime 53ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/servicios_web/gae/django-guestbook/src/django/contrib/comments/forms.py

https://github.com/enlaces/curso_python_dga_11
Python | 206 lines | 195 code | 6 blank | 5 comment | 3 complexity | 5786d1d3b2621bcdbd4311439dd3f516 MD5 | raw file
  1. import time
  2. import datetime
  3. from django import forms
  4. from django.forms.util import ErrorDict
  5. from django.conf import settings
  6. from django.contrib.contenttypes.models import ContentType
  7. from models import Comment
  8. from django.utils.crypto import salted_hmac, constant_time_compare
  9. from django.utils.encoding import force_unicode
  10. from django.utils.hashcompat import sha_constructor
  11. from django.utils.text import get_text_list
  12. from django.utils.translation import ungettext, ugettext_lazy as _
  13. COMMENT_MAX_LENGTH = getattr(settings,'COMMENT_MAX_LENGTH', 3000)
  14. class CommentSecurityForm(forms.Form):
  15. """
  16. Handles the security aspects (anti-spoofing) for comment forms.
  17. """
  18. content_type = forms.CharField(widget=forms.HiddenInput)
  19. object_pk = forms.CharField(widget=forms.HiddenInput)
  20. timestamp = forms.IntegerField(widget=forms.HiddenInput)
  21. security_hash = forms.CharField(min_length=40, max_length=40, widget=forms.HiddenInput)
  22. def __init__(self, target_object, data=None, initial=None):
  23. self.target_object = target_object
  24. if initial is None:
  25. initial = {}
  26. initial.update(self.generate_security_data())
  27. super(CommentSecurityForm, self).__init__(data=data, initial=initial)
  28. def security_errors(self):
  29. """Return just those errors associated with security"""
  30. errors = ErrorDict()
  31. for f in ["honeypot", "timestamp", "security_hash"]:
  32. if f in self.errors:
  33. errors[f] = self.errors[f]
  34. return errors
  35. def clean_security_hash(self):
  36. """Check the security hash."""
  37. security_hash_dict = {
  38. 'content_type' : self.data.get("content_type", ""),
  39. 'object_pk' : self.data.get("object_pk", ""),
  40. 'timestamp' : self.data.get("timestamp", ""),
  41. }
  42. expected_hash = self.generate_security_hash(**security_hash_dict)
  43. actual_hash = self.cleaned_data["security_hash"]
  44. if not constant_time_compare(expected_hash, actual_hash):
  45. # Fallback to Django 1.2 method for compatibility
  46. # PendingDeprecationWarning <- here to remind us to remove this
  47. # fallback in Django 1.5
  48. expected_hash_old = self._generate_security_hash_old(**security_hash_dict)
  49. if not constant_time_compare(expected_hash_old, actual_hash):
  50. raise forms.ValidationError("Security hash check failed.")
  51. return actual_hash
  52. def clean_timestamp(self):
  53. """Make sure the timestamp isn't too far (> 2 hours) in the past."""
  54. ts = self.cleaned_data["timestamp"]
  55. if time.time() - ts > (2 * 60 * 60):
  56. raise forms.ValidationError("Timestamp check failed")
  57. return ts
  58. def generate_security_data(self):
  59. """Generate a dict of security data for "initial" data."""
  60. timestamp = int(time.time())
  61. security_dict = {
  62. 'content_type' : str(self.target_object._meta),
  63. 'object_pk' : str(self.target_object._get_pk_val()),
  64. 'timestamp' : str(timestamp),
  65. 'security_hash' : self.initial_security_hash(timestamp),
  66. }
  67. return security_dict
  68. def initial_security_hash(self, timestamp):
  69. """
  70. Generate the initial security hash from self.content_object
  71. and a (unix) timestamp.
  72. """
  73. initial_security_dict = {
  74. 'content_type' : str(self.target_object._meta),
  75. 'object_pk' : str(self.target_object._get_pk_val()),
  76. 'timestamp' : str(timestamp),
  77. }
  78. return self.generate_security_hash(**initial_security_dict)
  79. def generate_security_hash(self, content_type, object_pk, timestamp):
  80. """
  81. Generate a HMAC security hash from the provided info.
  82. """
  83. info = (content_type, object_pk, timestamp)
  84. key_salt = "django.contrib.forms.CommentSecurityForm"
  85. value = "-".join(info)
  86. return salted_hmac(key_salt, value).hexdigest()
  87. def _generate_security_hash_old(self, content_type, object_pk, timestamp):
  88. """Generate a (SHA1) security hash from the provided info."""
  89. # Django 1.2 compatibility
  90. info = (content_type, object_pk, timestamp, settings.SECRET_KEY)
  91. return sha_constructor("".join(info)).hexdigest()
  92. class CommentDetailsForm(CommentSecurityForm):
  93. """
  94. Handles the specific details of the comment (name, comment, etc.).
  95. """
  96. name = forms.CharField(label=_("Name"), max_length=50)
  97. email = forms.EmailField(label=_("Email address"))
  98. url = forms.URLField(label=_("URL"), required=False)
  99. comment = forms.CharField(label=_('Comment'), widget=forms.Textarea,
  100. max_length=COMMENT_MAX_LENGTH)
  101. def get_comment_object(self):
  102. """
  103. Return a new (unsaved) comment object based on the information in this
  104. form. Assumes that the form is already validated and will throw a
  105. ValueError if not.
  106. Does not set any of the fields that would come from a Request object
  107. (i.e. ``user`` or ``ip_address``).
  108. """
  109. if not self.is_valid():
  110. raise ValueError("get_comment_object may only be called on valid forms")
  111. CommentModel = self.get_comment_model()
  112. new = CommentModel(**self.get_comment_create_data())
  113. new = self.check_for_duplicate_comment(new)
  114. return new
  115. def get_comment_model(self):
  116. """
  117. Get the comment model to create with this form. Subclasses in custom
  118. comment apps should override this, get_comment_create_data, and perhaps
  119. check_for_duplicate_comment to provide custom comment models.
  120. """
  121. return Comment
  122. def get_comment_create_data(self):
  123. """
  124. Returns the dict of data to be used to create a comment. Subclasses in
  125. custom comment apps that override get_comment_model can override this
  126. method to add extra fields onto a custom comment model.
  127. """
  128. return dict(
  129. content_type = ContentType.objects.get_for_model(self.target_object),
  130. object_pk = force_unicode(self.target_object._get_pk_val()),
  131. user_name = self.cleaned_data["name"],
  132. user_email = self.cleaned_data["email"],
  133. user_url = self.cleaned_data["url"],
  134. comment = self.cleaned_data["comment"],
  135. submit_date = datetime.datetime.now(),
  136. site_id = settings.SITE_ID,
  137. is_public = True,
  138. is_removed = False,
  139. )
  140. def check_for_duplicate_comment(self, new):
  141. """
  142. Check that a submitted comment isn't a duplicate. This might be caused
  143. by someone posting a comment twice. If it is a dup, silently return the *previous* comment.
  144. """
  145. possible_duplicates = self.get_comment_model()._default_manager.using(
  146. self.target_object._state.db
  147. ).filter(
  148. content_type = new.content_type,
  149. object_pk = new.object_pk,
  150. user_name = new.user_name,
  151. user_email = new.user_email,
  152. user_url = new.user_url,
  153. )
  154. for old in possible_duplicates:
  155. if old.submit_date.date() == new.submit_date.date() and old.comment == new.comment:
  156. return old
  157. return new
  158. def clean_comment(self):
  159. """
  160. If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't
  161. contain anything in PROFANITIES_LIST.
  162. """
  163. comment = self.cleaned_data["comment"]
  164. if settings.COMMENTS_ALLOW_PROFANITIES == False:
  165. bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()]
  166. if bad_words:
  167. plural = len(bad_words) > 1
  168. raise forms.ValidationError(ungettext(
  169. "Watch your mouth! The word %s is not allowed here.",
  170. "Watch your mouth! The words %s are not allowed here.", plural) % \
  171. get_text_list(['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in bad_words], 'and'))
  172. return comment
  173. class CommentForm(CommentDetailsForm):
  174. honeypot = forms.CharField(required=False,
  175. label=_('If you enter anything in this field '\
  176. 'your comment will be treated as spam'))
  177. def clean_honeypot(self):
  178. """Check that nothing's been entered into the honeypot."""
  179. value = self.cleaned_data["honeypot"]
  180. if value:
  181. raise forms.ValidationError(self.fields["honeypot"].label)
  182. return value