Exemplo n.º 1
0
        def wrapper(request, *args, **kwargs):

            if askbot_settings.USE_AKISMET and askbot_settings.AKISMET_API_KEY == "":
                raise ImproperlyConfigured('You have not set AKISMET_API_KEY')

            if askbot_settings.USE_AKISMET and request.method == "POST":
                comment = smart_str(request.POST[field])
                data = {
                    'user_ip': request.META.get('REMOTE_ADDR'),
                    'user_agent': request.environ['HTTP_USER_AGENT'],
                    'comment_author': smart_str(request.user.username),
                }
                if request.user.is_authenticated():
                    data.update({'comment_author_email': request.user.email})

                from akismet import Akismet
                api = Akismet(askbot_settings.AKISMET_API_KEY,
                              smart_str(site_url(reverse('questions'))),
                              "Askbot/%s" % get_version())

                if api.comment_check(comment, data, build_data=False):
                    logging.debug('Spam detected in %s post at: %s',
                                  request.user.username,
                                  datetime.datetime.now())
                    spam_message = _('Spam was detected on your post, sorry '
                                     'for if this is a mistake')
                    if request.is_ajax():
                        return HttpResponseForbidden(
                            spam_message, mimetype="application/json")
                    else:
                        request.user.message_set.create(message=spam_message)
                        return HttpResponseRedirect(reverse('index'))

            return view_func(request, *args, **kwargs)
Exemplo n.º 2
0
    def comment_check(self):
        '''
        Check a comment.
        Return True for ham, False for spam.
        Use this function before save a comment.
        '''
        try:
            if hasattr(settings, 'BAN_NON_CJK') and settings.BAN_NON_CJK:
                import re
                if not re.search("[\u4E00-\u9FC3\u3041-\u30FF]", self.comment):
                    raise Exception()

            if hasattr(settings,
                       'AKISMET_API_KEY') and settings.AKISMET_API_KEY:
                from akismet import Akismet
                akismet_api = Akismet(key=settings.AKISMET_API_KEY,
                                      blog_url='http://%s/' %
                                      Site.objects.get_current().domain)
                if akismet_api.verify_key():
                    akismet_data = {
                        'comment_type': 'comment',
                        'user_ip': self.ip_address,
                        'user_agent': self.user_agent,
                        'referrer': '',
                    }
                    return not akismet_api.comment_check(
                        self.comment.encode("utf8"),
                        data=akismet_data,
                        build_data=True)
            else:
                return True
        except:
            return False
Exemplo n.º 3
0
 def setUp(self):
     try:
         akismet_api_key = os.environ['AKISMET_API_KEY']
     except KeyError:
         raise EnvironmentError(
             'Provide AKISMET_API_KEY environment setting.')
     self.akismet = Akismet(akismet_api_key, is_test=True)
Exemplo n.º 4
0
def on_comment_was_posted(sender, comment, request, *args, **kwargs):
    try:
        from akismet import Akismet
        from akismet import AkismetError
    except:
        return

    if hasattr(settings, 'AKISMET_API_KEY'):
        ak = Akismet(key=settings.AKISMET_API_KEY,
                     blog_url='http://%s/' %
                     Site.objects.get(pk=settings.SITE_ID).domain)
    else:
        return

    try:
        if ak.verify_key():
            data = {
                'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'),
                'user_agent': request.META.get('HTTP_USER_AGENT', ''),
                'referrer': request.META.get('HTTP_REFERER', ''),
                'comment_type': 'comment',
                'comment_author': comment.user_name.encode('utf-8'),
            }

            if ak.comment_check(comment.content.encode('utf-8'),
                                data=data,
                                build_data=True):
                comment.is_public = False
                comment.save()
    except AkismetError:
        comment.save()
Exemplo n.º 5
0
    def handle_noargs(self, **options):

        comments = Comment.objects.filter(is_public=True,
                                          is_removed=False,
                                          submit_date__gte=datetime.date(
                                              2010, 07, 01))
        for comment in comments:
            a = Akismet(AKISMET_KEY,
                        blog_url='http://%s/' %
                        Site.objects.get_current().domain)

            akismet_data = {
                'user_ip':
                comment.ip_address,
                'user_agent':
                'Mozilla/5.0 (X11; U; Linux x86_64; de; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8',
                'comment_author':
                comment.user_name.encode('ascii', 'ignore'),
                'comment_author_email':
                comment.user_email.encode('ascii', 'ignore'),
                'comment_author_url':
                comment.user_url.encode('ascii', 'ignore'),
                'comment_type':
                'comment',
            }

            is_spam = a.comment_check(
                comment.comment.encode('ascii', 'ignore'), akismet_data)

            if is_spam:
                post = Post.objects.get(pk=comment.object_pk)
                #print comment.user_name.encode('ascii', 'ignore'), post.get_absolute_url() + '#' + str(comment.pk)
                comment.is_removed = True
                comment.is_public = False
                comment.save()
Exemplo n.º 6
0
 def clean_body(self):
     """
     Perform Akismet validation of the message.
     
     """
     if 'body' in self.cleaned_data and getattr(settings, 'AKISMET_API_KEY',
                                                ''):
         from akismet import Akismet
         from django.utils.encoding import smart_str
         akismet_api = Akismet(key=settings.AKISMET_API_KEY,
                               blog_url='http://%s/' %
                               Site.objects.get_current().domain)
         if akismet_api.verify_key():
             akismet_data = {
                 'comment_type': 'comment',
                 'referer': self.request.META.get('HTTP_REFERER', ''),
                 'user_ip': self.request.META.get('REMOTE_ADDR', ''),
                 'user_agent': self.request.META.get('HTTP_USER_AGENT', '')
             }
             if akismet_api.comment_check(smart_str(
                     self.cleaned_data['body']),
                                          data=akismet_data,
                                          build_data=True):
                 raise forms.ValidationError(
                     u"Akismet thinks this message is spam")
     return self.cleaned_data['body']
Exemplo n.º 7
0
def on_comment_was_posted(sender, comment, request, *args, **kwargs):
    # spam checking can be enabled/disabled per the comment's target Model
    # if comment.content_type.model_class() != Entry:
    #    return

    from django.contrib.sites.models import Site
    from django.conf import settings

    try:
        from akismet import Akismet
    except:
        return

    ak = Akismet(key=settings.AKISMET_API_KEY,
                 blog_url='http://%s/' %
                 Site.objects.get(pk=settings.SITE_ID).domain)

    if ak.verify_key():
        data = {
            'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'),
            'user_agent': request.META.get('HTTP_USER_AGENT', ''),
            'referrer': request.META.get('HTTP_REFERER', ''),
            'comment_type': 'comment',
            'comment_author': comment.user_name.encode('utf-8'),
        }

        if ak.comment_check(comment.comment.encode('utf-8'),
                            data=data,
                            build_data=True):
            comment.flags.create(user=comment.content_object.author,
                                 flag='spam')
            comment.is_public = False
            comment.save()
Exemplo n.º 8
0
def is_spam(request, comment):

    # If request user has uploaded sounds, we don't check for spam
    if request.user.sounds.count() > 0:
        return False

    domain = "http://%s" % Site.objects.get_current().domain
    api = Akismet(key=settings.AKISMET_KEY, blog_url=domain)
    
    data = {
        'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'),
        'user_agent': request.META.get('HTTP_USER_AGENT', ''),
        'referrer': request.META.get('HTTP_REFERER', ''),
        'comment_type': 'comment',
        'comment_author': request.user.username.encode("utf-8") if request.user.is_authenticated else '',
    }
    
    if False: # set this to true to force a spam detection
        data['comment_author'] = "viagra-test-123"
    
    try:
        if api.comment_check(comment.encode('utf-8'), data=data, build_data=True):
            if request.user.is_authenticated:
                AkismetSpam.objects.create(user=request.user, spam=comment)
            return True
        else:
            return False
    except AkismetError: # failed to contact akismet...
        return False
    except HTTPError: # failed to contact akismet...
        return False
    except URLError: # failed to contact akismet...
        return False
Exemplo n.º 9
0
def check_with_akismet(comment=None, request=None, **kwargs):
    if config_value("PRODUCT", "AKISMET_ENABLE"):
        key = config_value("PRODUCT", "AKISMET_KEY")
        if key:
            site = Site.objects.get_current()
            shop = urlresolvers.reverse('satchmo_shop_home')
            from akismet import Akismet
            akismet = Akismet(key=settings.AKISMET_API_KEY,
                              blog_url='http://%s' %
                              url_join(site.domain, shop))
            if akismet.verify_key():
                akismet_data = {
                    'comment_type': 'comment',
                    'referrer': request.META.get('HTTP_REFERER', ""),
                    'user_ip': comment.ip_address,
                    'user_agent': ''
                }
                if akismet.comment_check(smart_str(comment.comment),
                                         data=akismet_data,
                                         build_data=True):
                    comment.is_public = False
                    comment.save()
                    log.info("Akismet marked comment #%i as spam", comment.id)
                else:
                    log.debug("Akismet accepted comment #%i", comment.id)
            else:
                log.warn("Akismet key '%s' not accepted by akismet service.",
                         key)
        else:
            log.info(
                "Akismet enabled, but no key found.  Please put in your admin settings."
            )
Exemplo n.º 10
0
def backend(comment, content_object, request):
    """
    Akismet spam checker backend for Zinnia.
    """
    blog_url = '%s://%s/' % (PROTOCOL, Site.objects.get_current().domain)

    akismet = Akismet(key=AKISMET_API_KEY, blog_url=blog_url)

    if not akismet.verify_key():
        raise APIKeyError('Your Akismet API key is invalid.')

    akismet_data = {
        'user_ip': request.META.get('REMOTE_ADDR', ''),
        'user_agent': request.META.get('HTTP_USER_AGENT', ''),
        'referrer': request.META.get('HTTP_REFERER', 'unknown'),
        'permalink': content_object.get_absolute_url(),
        'comment_type': 'comment',
        'comment_author': smart_str(comment.name),
        'comment_author_email': smart_str(comment.email),
        'comment_author_url': smart_str(comment.url),
    }
    is_spam = akismet.comment_check(smart_str(comment.comment),
                                    data=akismet_data,
                                    build_data=True)
    return is_spam
Exemplo n.º 11
0
def filter_spam(ctx):

    site_url = settings.DEFAULT_BACKEND_PROTOCOL + \
        "://"+settings.DEFAULT_BACKEND_DOMAIN

    if site_url.find("localhost") != -1:
        return

    Comment = apps.get_model('projects.Comment')
    PublishingRule = apps.get_model('projects.PublishingRule')
    comment = Comment.objects.get(id=ctx.get("comment_id"))

    if ctx.get("method"
               ) == 'POST' and comment.publish.type != PublishingRule.DRAFT:
        akismet_api = Akismet(key=settings.AKISMET_API_KEY, blog_url=site_url)

        is_spam = akismet_api.comment_check(
            user_ip=ctx.get("REMOTE_ADDR"),
            user_agent=ctx.get("HTTP_USER_AGENT"),
            comment_type='comment',
            comment_content=ctx.get("text"),
            blog_lang=ctx.get("lang"),
        )

        if is_spam:
            comment.publish.type = PublishingRule.DRAFT
            comment.publish.publisher_id = None  ## Set publisher_id to none when zubhub system unpublished a comment.
            comment.save()

            staffs_and_mods = Creator.objects.filter(is_staff=True)
            staffs_and_mods = staffs.union(
                Creator.objects.filter(tags__name="moderator"))

            send_spam_notification(ctx.get("comment_id"), staffs_and_mods)
Exemplo n.º 12
0
    def check_spam(self, request, comment, key, blog_url=None, base_url=None):
        try:
            from akismet import Akismet
        except:
            return False

        if blog_url is None:
            blog_url = 'http://%s/' % Site.objects.get_current().domain

        ak = Akismet(key=key, blog_url=blog_url)

        if base_url is not None:
            ak.baseurl = base_url

        if ak.verify_key():
            data = {
                'user_ip': request.META.get('HTTP_X_FORWARDED_FOR',
                                            '127.0.0.1'),
                'user_agent': request.META.get('HTTP_USER_AGENT', ''),
                'referrer': request.META.get('HTTP_REFERER', ''),
                'comment_type': 'comment',
                'comment_author': comment.user_name.encode('utf-8')
            }

            if ak.comment_check(comment.comment.encode('utf-8'),
                                data=data,
                                build_data=True):
                return True

        return False
 def moderate(self, comment, content_object):
     """
     Determine whether a given comment on a given object should be
     allowed to show up immediately, or should be marked non-public
     and await approval.
     
     Return ``True`` if the comment should be moderated (marked
     non-public), ``False`` otherwise.
     
     """
     if self.auto_moderate_field and self.moderate_after:
         if self._get_delta(
                 datetime.datetime.now(),
                 getattr(
                     content_object,
                     self.auto_moderate_field)).days >= self.moderate_after:
             return True
     if self.akismet:
         from akismet import Akismet
         from django.utils.encoding import smart_str
         akismet_api = Akismet(key=settings.AKISMET_API_KEY,
                               blog_url='http://%s/' %
                               Site.objects.get_current().domain)
         if akismet_api.verify_key():
             akismet_data = {
                 'comment_type': 'comment',
                 'referrer': '',
                 'user_ip': comment.ip_address,
                 'user_agent': ''
             }
             if akismet_api.comment_check(smart_str(comment.comment),
                                          data=akismet_data,
                                          build_data=True):
                 return True
     return False
Exemplo n.º 14
0
    def clean_body(self):
        """
        Check spam against Akismet.

        Backported from django-contact-form pre-1.0; 1.0 dropped built-in
        Akismet support.
        """
        if 'body' in self.cleaned_data and hasattr(
                settings, 'AKISMET_API_KEY') and settings.AKISMET_API_KEY:
            akismet_api = Akismet(key=settings.AKISMET_API_KEY,
                                  blog_url='http://%s/' %
                                  Site.objects.get_current().domain)
            if akismet_api.verify_key():
                akismet_data = {
                    'comment_type': 'comment',
                    'referer': self.request.META.get('HTTP_REFERER', ''),
                    'user_ip': self.request.META.get('REMOTE_ADDR', ''),
                    'user_agent': self.request.META.get('HTTP_USER_AGENT', '')
                }
                comment = force_bytes(
                    self.cleaned_data['body'])  # workaround for #21444
                if akismet_api.comment_check(comment,
                                             data=akismet_data,
                                             build_data=True):
                    raise forms.ValidationError(
                        "Akismet thinks this message is spam")
        return self.cleaned_data['body']
Exemplo n.º 15
0
def akismet_check_spam(text, request):
    """Returns True if spam found, false if not,
    May raise exceptions if something is not right with
    the Akismet account/service/setup"""
    if not askbot_settings.USE_AKISMET:
        return False
    try:
        if askbot_settings.USE_AKISMET and askbot_settings.AKISMET_API_KEY == "":
            raise ImproperlyConfigured('You have not set AKISMET_API_KEY')
        data = {'user_ip': request.META.get('REMOTE_ADDR'),
                'user_agent': request.environ['HTTP_USER_AGENT'],
                'comment_author': smart_str(request.user.username)
                }
        if request.user.is_authenticated():
            data.update({'comment_author_email': request.user.email})

        api = Akismet(
            askbot_settings.AKISMET_API_KEY,
            smart_str(site_url(reverse('questions'))),
            "Askbot/%s" % get_version()
        )
        return api.comment_check(text, data, build_data=False)
    except APIKeyError:
        logging.critical('Akismet Key is missing')
    except AkismetError:
        logging.critical('Akismet error: Invalid Akismet key or Akismet account issue!')
    except Exception as e:
        logging.critical((u'Akismet error: %s' % unicode(e)).encode('utf-8'))
    return False
Exemplo n.º 16
0
    def _akismet_check(self, comment, content_object, request):
        """
        Connects to Akismet and returns True if Akismet marks this comment as
        spam. Otherwise returns False.
        """
        # Get Akismet data
        AKISMET_API_KEY = appsettings.AKISMET_API_KEY
        if not AKISMET_API_KEY:
            raise ImproperlyConfigured(
                'You must set AKISMET_API_KEY to use comment moderation with Akismet.'
            )

        current_domain = get_current_site(request).domain
        auto_blog_url = '{0}://{1}/'.format(
            request.is_secure() and 'https' or 'http', current_domain)
        blog_url = appsettings.AKISMET_BLOG_URL or auto_blog_url

        akismet = Akismet(
            AKISMET_API_KEY,
            blog=blog_url,
            is_test=int(bool(appsettings.AKISMET_IS_TEST)),
            application_user_agent='django-fluent-comments/{0}'.format(
                fluent_comments.__version__),
        )

        akismet_data = self._get_akismet_data(blog_url, comment,
                                              content_object, request)
        return akismet.check(
            **akismet_data)  # raises AkismetServerError when key is invalid
Exemplo n.º 17
0
def on_comment_was_posted(sender, *args, **kwargs):
    article = instance.article
    approved = instance.approved
    _model = instance._meta.model
    try:
        from akismet import Akismet
    except:
        from pykismet3 import Akismet
    except:
        return
        
    AKISMET_API_KEY = getattr(settings, 'AKISMET_API_KEY', 'd7719929047a')
    SITE_URL = getattr(settings, 'SITE_URL', 'http://www.iloxp.com/')
    akismet = Akismet(AKISMET_API_KEY, SITE_URL, user_agent='Mozilla/5.0')
    verify = akismet.check({
        'referrer': '127.0.0.1',
        'comment_type': 'reply' if instance.parent else 'comment',
        'user_ip': instance.author_ip,
        'user_agent':  instance.agent,
        'comment_content': instance.content,
        'is_test': 1,
        if instance.author_email:
            'comment_author_email': instance.author_email,
        if instance.author_name:
            'comment_author': instance.author_name,
    })
Exemplo n.º 18
0
def verify_installation(request):
    try:
        from akismet import Akismet
    except ImportError:
        print >> sys.stderr, "Missing module 'akismet'.",
        return False

    config = request.get_configuration()

    # try to check to se make sure that the config file has a key
    if not config.has_key("akismet_api_key"):
        print >> sys.stderr, "Missing required configuration value 'akismet_key'",
        return False

    try:
        from akismet import Akismet
        a = Akismet(config['akismet_api_key'],
                    config['base_url'],
                    agent='PyBlosxom/1.3')
        if not a.verify_key():
            print >> sys.stderr, "Could not verify akismet API key.",
            return False
    except ImportError:
        print "Unknown error loading Akismet module!",
        return False

    return True
Exemplo n.º 19
0
    def _akismet_check(self, comment, content_object, request):
        """
        Connects to Akismet and returns True if Akismet marks this comment as
        spam. Otherwise returns False.
        """
        # Get Akismet data
        AKISMET_API_KEY = appsettings.AKISMET_API_KEY
        if not AKISMET_API_KEY:
            raise ImproperlyConfigured(
                'You must set AKISMET_API_KEY to use comment moderation with Akismet.'
            )

        current_domain = get_current_site(request).domain
        auto_blog_url = '{0}://{1}/'.format(
            request.is_secure() and 'https' or 'http', current_domain)
        blog_url = appsettings.AKISMET_BLOG_URL or auto_blog_url

        akismet_api = Akismet(key=AKISMET_API_KEY, blog_url=blog_url)

        if akismet_api.verify_key():
            akismet_data = self._get_akismet_data(blog_url, comment,
                                                  content_object, request)
            if akismet_api.comment_check(smart_str(comment.comment),
                                         data=akismet_data,
                                         build_data=True):
                return True

        return False
Exemplo n.º 20
0
    def _check_akismet(self):
        def add_error(error):
            self._add_error('akismet_api_key', error)

        try:
            from akismet import Akismet
        except ImportError:
            self._add_error(
                'spam_protection_method',
                _('Akismet library is not installed. Use '
                  '"easy_install akismet" or "pip install '
                  'akismet".'))

        api_key = getattr(settings, "AKISMET_API_KEY",
                          self.cleaned_data['akismet_api_key'])

        if not hasattr(settings, "AKISMET_API_KEY"):
            if not api_key:
                add_error(Field.default_error_messages['required'])
            else:
                ak = Akismet(key=api_key,
                             blog_url='http://%s/' %
                             (Site.objects.get(pk=settings.SITE_ID).domain))
                if not ak.verify_key():
                    add_error(_('The API Key is not valid.'))
Exemplo n.º 21
0
    def test_timeout(self):
        self.akismet = Akismet(os.environ['AKISMET_API_KEY'],
                               timeout=0.000001,
                               is_test=True)

        with self.assertRaises(requests.ConnectionError):
            self.akismet.submit_ham('127.0.0.1',
                                    USER_AGENT,
                                    blog='http://127.0.0.1')
Exemplo n.º 22
0
 def moderate(self, comment, content_object, request):
     already_moderated = super(EntryModerator, self).moderate(comment, content_object)
     if already_moderated:
         return True
     akismet_api = Akismet(key=settings.AKISMET_API_KEY, blog_url="http:/%s/" % Site.objects.get_current().domain)
     if akismet_api.verify_key():
         akismet_data = { 'comment_type': 'comment', 'referrer': request.META['HTTP_REFERER'], 'user_ip': comment.ip_address, 'user-agent': request.META['HTTP_USER_AGENT']}
         return akismet_api.comment_check(smart_str(comment.comment), akismet_data, build_data=True)
     return False
Exemplo n.º 23
0
def akismet_check(request=None,
                  comment_author='',
                  comment_author_email='',
                  comment_author_url='',
                  comment_content='',
                  akismet_api_key=None):
    """
    Connects to Akismet and returns True if Akismet marks this content as
    spam. Otherwise returns False.
    """

    # Check if the akismet library is installed
    try:
        from akismet import Akismet
    except ImportError:
        raise ImportError(
            'Akismet library is not installed. "easy_install akismet" does the job.'
        )

    # Check if the akismet api key is set, fail silently if
    # settings.DEBUG is False and return False (not moderated)
    AKISMET_API_KEY = akismet_api_key or getattr(settings, 'AKISMET_API_KEY',
                                                 False)
    if not AKISMET_API_KEY:
        raise ImproperlyConfigured(
            'You must set AKISMET_API_KEY with your api key in your settings file.'
        )

    ak = Akismet(key=AKISMET_API_KEY,
                 blog_url='http://%s/' %
                 Site.objects.get(pk=settings.SITE_ID).domain)

    if ak.verify_key():
        if request is not None:
            data = {
                'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'),
                'user_agent': request.META.get('HTTP_USER_AGENT', ''),
                'referrer': request.META.get('HTTP_REFERER', ''),
            }
        else:
            data = {
                'user_ip': '',
                'user_agent': '',
                'referrer': '',
            }
        data.update({'comment_author': comment_author.encode('utf-8')})
        data.update(
            {'comment_author_email': comment_author_email.encode('utf-8')})
        data.update({'comment_author_url': comment_author_url.encode('utf-8')})
        # Send the request to Akismet
        if ak.comment_check(comment_content.encode('utf-8'),
                            data=data,
                            build_data=True):
            return True

    return False
Exemplo n.º 24
0
def is_spam(text, request):
    """Generic spam checker interface."""
    if settings.AKISMET_API_KEY:
        from akismet import Akismet
        akismet = Akismet(settings.AKISMET_API_KEY, get_site_url())
        return akismet.comment_check(get_ip_address(request),
                                     request.META.get('HTTP_USER_AGENT', ''),
                                     comment_content=text,
                                     comment_type='comment')
    return False
Exemplo n.º 25
0
def check_spam(ip, ua, author, content) -> int:
    # 0 means okay
    token = os.getenv("askismet")
    if token:
        with contextlib.suppress(Exception):
            akismet = Akismet(token, blog="https://yyets.dmesg.app/")

            return akismet.check(ip, ua, comment_author=author, blog_lang="zh_cn",
                                 comment_type="comment",
                                 comment_content=content)
    return 0
Exemplo n.º 26
0
def get_akismet():
    if not settings.AKISMET_API_KEY:
        return None

    from akismet import Akismet

    return Akismet(
        api_key=settings.AKISMET_API_KEY,
        blog=get_site_url(),
        application_user_agent=USER_AGENT,
    )
Exemplo n.º 27
0
def moderate_comment(sender, comment, request, *args, **kwargs):
    try:
        from akismet import Akismet
    except:
        # TODO: log this "can't find akismet in your Python path"
        return

    # use TypePad's AntiSpam if the key is specified in settings.py
    if hasattr(settings, 'TYPEPAD_ANTISPAM_API_KEY'):
        ak = Akismet(
            key=settings.TYPEPAD_ANTISPAM_API_KEY,
            blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain
        )
        ak.baseurl = 'api.antispam.typepad.com/1.1/'
    elif hasattr(settings, 'AKISMET_API_KEY'):
        ak = Akismet(
            key=settings.AKISMET_API_KEY,
            blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain
        )
    else:
        #"AKISMET_API_KEY required in settings file to use this feature"
        return

    if ak.verify_key():
        data = {
            'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'),
            'user_agent': request.META.get('HTTP_USER_AGENT', ''),
            'referrer': request.META.get('HTTP_REFERRER', ''),
            'comment_type': 'comment',
            'comment_author': smart_str(comment.user_name),
        }
        if ak.comment_check(smart_str(comment.comment.encode('utf-8')), data=data, build_data=True):
            comment.flags.create(
                user =comment.content_object.user,
                flag = 'spam'
            )
            comment.is_public = False
            comment.save()
    else:
        #TODO: log this "invalid Akismet key"
        return
Exemplo n.º 28
0
def report_spam(text, user_ip, user_agent):
    if not settings.AKISMET_API_KEY:
        return
    from akismet import Akismet, ProtocolError

    akismet = Akismet(settings.AKISMET_API_KEY, get_site_url())
    try:
        akismet.submit_spam(
            user_ip, user_agent, comment_content=text, comment_type="comment"
        )
    except (ProtocolError, OSError):
        report_error()
Exemplo n.º 29
0
def report_spam(text, user_ip, user_agent):
    if not settings.AKISMET_API_KEY:
        return
    from akismet import Akismet, ProtocolError
    akismet = Akismet(settings.AKISMET_API_KEY, get_site_url())
    try:
        akismet.submit_spam(user_ip,
                            user_agent,
                            comment_content=text,
                            comment_type='comment')
    except ProtocolError as error:
        report_error(error, sys.exc_info())
Exemplo n.º 30
0
def text_is_spam(text, request):
    # Based on a blog post by 'sciyoshi':
    # http://sciyoshi.com/blog/2008/aug/27/using-akismet-djangos-new-comments-framework/
    # This will return 'True' is the given text is deemed to be spam, or
    # False if it is not spam. If it cannot be checked for some reason, we
    # assume it isn't spam.
    from django.contrib.sites.models import Site
    from django.core.exceptions import ImproperlyConfigured
    try:
        from akismet import Akismet
    except ImportError:
        return False
    try:
        site = Site.objects.get_current()
    except ImproperlyConfigured:
        site = Site(domain='configure-django-sites.com')

    # see https://akismet.readthedocs.io/en/latest/overview.html#using-akismet

    apikey = None

    if hasattr(settings, 'TYPEPAD_ANTISPAM_API_KEY'):
        apikey = settings.TYPEPAD_ANTISPAM_API_KEY
    elif hasattr(settings, 'PYTHON_AKISMET_API_KEY'):
        # new env var expected by python-akismet package
        apikey = settings.PYTHON_AKISMET_API_KEY
    elif hasattr(settings, 'AKISMET_API_KEY'):
        # deprecated, but kept for backward compatibility
        apikey = settings.AKISMET_API_KEY
    else:
        return False

    ak = Akismet(
        blog_url='http://%s/' % site.domain,
        key=apikey,
    )

    if hasattr(settings, 'TYPEPAD_ANTISPAM_API_KEY'):
        ak.baseurl = 'api.antispam.typepad.com/1.1/'

    if ak.verify_key():
        ak_data = {
            'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'),
            'user_agent': request.META.get('HTTP_USER_AGENT', ''),
            'referrer': request.META.get('HTTP_REFERER', ''),
            'comment_type': 'comment',
            'comment_author': '',
        }

        return ak.comment_check(smart_text(text), data=ak_data)

    return False