~widelands-dev/widelands-website/django_staticfiles

« back to all changes in this revision

Viewing changes to check_input/models.py

  • Committer: Holger Rapp
  • Date: 2009-02-19 15:31:42 UTC
  • Revision ID: sirver@h566336-20090219153142-dc8xuabldnw5t395
Initial commit of new widelands homepage

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
from django.db import models
2
 
from django.contrib.auth.models import User
3
 
from django.contrib.contenttypes.models import ContentType
4
 
from django.contrib.contenttypes.fields import GenericForeignKey
5
 
from django.conf import settings
6
 
import re
7
 
 
8
 
 
9
 
class SuspiciousInput(models.Model):
10
 
    """Model for collecting suspicios user input.
11
 
 
12
 
        Call the check_input method with this attributes:
13
 
        content_object = Model instance of a saved(!) object
14
 
        user = user
15
 
        text = text to check for suspicious content
16
 
 
17
 
        Example:
18
 
        is_suspicous = SuspiciousInput.check_input(content_object=post,
19
 
    user=post.user, text=post.body)
20
 
 
21
 
    """
22
 
 
23
 
    text = models.CharField(
24
 
        max_length=200, verbose_name='suspicious user input')
25
 
    user = models.ForeignKey(User, verbose_name='related user')
26
 
    content_type = models.ForeignKey(ContentType, verbose_name='related model')
27
 
    object_id = models.PositiveIntegerField()
28
 
    content_object = GenericForeignKey('content_type', 'object_id')
29
 
 
30
 
    class Meta:
31
 
        ordering = ['content_type_id']
32
 
        default_permissions = ('change', 'delete',)
33
 
 
34
 
    def __unicode__(self):
35
 
        return self.text
36
 
 
37
 
    def clean(self):
38
 
        # Cleaning fields
39
 
        max_chars = self._meta.get_field('text').max_length
40
 
        if len(self.text) >= max_chars:
41
 
            # Truncate the text to fit with max_length of field
42
 
            # otherwise a Database error is thrown
43
 
            self.text = self.text[:max_chars]
44
 
 
45
 
    def is_suspicious(self):
46
 
        if any(x in self.text.lower() for x in settings.ANTI_SPAM_KWRDS):
47
 
            return True
48
 
        if re.search(settings.ANTI_SPAM_PHONE_NR, self.text):
49
 
            return True
50
 
        return False
51
 
 
52
 
    @classmethod
53
 
    def check_input(cls, *args, **kwargs):
54
 
        user_input = cls(*args, **kwargs)
55
 
        is_spam = user_input.is_suspicious()
56
 
        if is_spam:
57
 
            try:
58
 
                user_input.clean()
59
 
                user_input.save()
60
 
            except:
61
 
                pass
62
 
 
63
 
        return is_spam