forms.py 7.8 KB

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