Kevin Veroneau avatar Kevin Veroneau committed 680a6b4 Draft

Initial code import.

Comments (0)

Files changed (7)

Empty file added.

+import random
+import hashlib
+from django.conf import settings
+from django.core.cache import cache
+from django.utils.safestring import mark_safe
+
+class myForm(object):
+    def __init__(self, request):
+        self.form = {}
+        self.request = request
+        self.auth = ""
+        self.posted = False
+    def genName(self):
+        dat = ""
+        for i in range(0,9):
+            dat += chr(random.randint(65,90))
+        return dat
+    def addField(self, typ, key, value=''):
+        self.form[key] = {'type':typ, 'value':value, 'name':self.genName()}
+        self.auth += key
+    def setValue(self, key, value):
+        self.form[key]['value'] = value
+    def __getitem__(self, item):
+        if item in self.form:
+            self.request.session[item] = self.form[item]['name']
+            if self.form[item]['type'] == 'textarea':
+                return mark_safe('<textarea name="%s" id="id_comment" cols="80" rows="10">%s</textarea>' % (self.form[item]['name'], self.form[item]['value']))
+            return mark_safe('<input name="%s" value="%s" type="%s" />' % (self.form[item]['name'], self.form[item]['value'], self.form[item]['type']))
+        if item == 'auth':
+            hash = hashlib.md5(self.auth+settings.SECRET_KEY).hexdigest()
+            cache_key = self.genName()
+            cache.set(cache_key, hash, 600)
+            self.request.session[item] = cache_key
+            return mark_safe('<input type="hidden" name="auth" value="%s" />' % hash)
+        raise KeyError
+    def is_valid(self):
+        self.posted = True
+        if self.request.method == 'GET':
+            self.error = "Use POST method"
+            return False
+        if 'auth' not in self.request.session:
+            self.error = "auth not in session"
+            return False
+        cache_key = self.request.session['auth']
+        cache_auth = cache.get(cache_key, 'expired')
+        for key in self.form:
+            if key not in self.request.session:
+                self.error = "%s not in session" % key
+                return False
+            self.form[key]['name'] = self.request.session[key]
+            del self.request.session[key]
+            if self.form[key]['name'] not in self.request.POST:
+                self.error = "%s not in POST data." % self.form[key]['name']
+                return False
+            self.form[key]['value'] = self.request.POST[self.form[key]['name']]
+        if cache_auth == 'expired':
+            self.error = "Token expired, you have exactly 10 minutes to fill in a comment."
+            return False
+        if self.request.POST['auth'] != cache_auth:
+            self.error = "Auth doesn't match Token."
+            return False
+        return True
+    def getField(self, key):
+        return self.request.POST[self.form[key]['name']]
+    def getFields(self):
+        post_vars = {}
+        for key in self.form:
+            post_vars[key] = self.request.POST[self.form[key]['name']]
+            if post_vars[key] == '': del post_vars[key]
+        return post_vars
+
+def NexGenCommentForm(req, initial=None):
+    frm = myForm(req)
+    frm.addField('hidden', 'next')
+    frm.addField('hidden', 'content_type')
+    frm.addField('hidden', 'object_pk')
+    frm.addField('hidden', 'timestamp')
+    frm.addField('hidden', 'security_hash')
+    frm.addField('text', 'name')
+    frm.addField('text', 'email')
+    frm.addField('text', 'url')
+    frm.addField('textarea', 'comment')
+    frm.addField('hidden','honeypot')
+    if initial is not None:
+        for key in initial:
+            frm.setValue(key, initial[key])
+    return frm
+from django.db import models
+
+# Create your models here.
Add a comment to this file

templatetags/__init__.py

Empty file added.

templatetags/antibot_comments_tags.py

+from django import template
+from django.template import TemplateSyntaxError
+from nexgen_comments.forms import NexGenCommentForm
+from django.conf import settings
+from django.utils.hashcompat import sha_constructor
+import time
+
+register = template.Library()
+
+def generate_initial(obj):
+    timestamp = int(time.time())
+    initial = {'content_type':obj._meta, 'object_pk':obj._get_pk_val(), 'timestamp':str(timestamp)}
+    info = (str(obj._meta), str(obj._get_pk_val()), str(timestamp), settings.SECRET_KEY)
+    initial.update({'security_hash':sha_constructor("".join(info)).hexdigest()})
+    #initial.update({'next':'/comments/done/'})
+    return initial
+
+@register.inclusion_tag("comments/form.html", takes_context=True)
+def comment_form(context,obj):
+    frm = NexGenCommentForm(context['request'], initial=generate_initial(obj))
+    return {'frm':frm}
+"""
+This file demonstrates two different styles of tests (one doctest and one
+unittest). These will both pass when you run "manage.py test".
+
+Replace these with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+class SimpleTest(TestCase):
+    def test_basic_addition(self):
+        """
+        Tests that 1 + 1 always equals 2.
+        """
+        self.failUnlessEqual(1 + 1, 2)
+
+__test__ = {"doctest": """
+Another way to test that 1 + 1 is equal to 2.
+
+>>> 1 + 1 == 2
+True
+"""}
+
+from django.views.decorators.csrf import csrf_protect
+from django.views.decorators.http import require_POST
+from nexgen_comments.forms import NexGenCommentForm
+from django.core.mail import mail_admins
+from django.contrib.comments.views.comments import CommentPostBadRequest,\
+    comment_done
+from django.db import models
+from django.utils.html import escape
+from django.core.exceptions import ObjectDoesNotExist, ValidationError
+from django.contrib import comments
+from django.shortcuts import render_to_response
+from django.template.context import RequestContext
+from django.contrib.comments import signals
+from django.contrib.comments.views.utils import next_redirect
+from django.http import HttpResponse
+
+@csrf_protect
+@require_POST
+def post_comment(request, next=None, using=None):
+    frm = NexGenCommentForm(request)
+    if not frm.is_valid():
+        try:
+            comment = frm.getField('comment')
+        except:
+            comment = "Comment lost in transit, hit the back button and cross your fingers..."
+        mail_admins("Comment post failed", "Error: %s<br/>Comment: %s" % (frm.error, comment), fail_silently=True)
+        return HttpResponse("There was a problem with submitting your comment: %s<br/>Please copy and paste your comment below and try again...<hr/>%s" % (frm.error, comment))
+    try:
+        next = frm.getField('next')
+    except:
+        next = '/comments/posted/'
+    if next == '': next = '/comments/posted/'
+    try:
+        ctype = frm.getField("content_type")
+        object_pk = frm.getField("object_pk")
+    except:
+        return CommentPostBadRequest("Missing content_type or object_pk field.")
+    try:
+        model = models.get_model(*ctype.split(".", 1))
+        target = model._default_manager.using(using).get(pk=object_pk)
+    except TypeError:
+        return CommentPostBadRequest(
+            "Invalid content_type value: %r" % escape(ctype))
+    except AttributeError:
+        return CommentPostBadRequest(
+            "The given content-type %r does not resolve to a valid model." % \
+                escape(ctype))
+    except ObjectDoesNotExist:
+        return CommentPostBadRequest(
+            "No object matching content-type %r and object PK %r exists." % \
+                (escape(ctype), escape(object_pk)))
+    except (ValueError, ValidationError), e:
+        return CommentPostBadRequest(
+            "Attempting go get content-type %r and object PK %r exists raised %s" % \
+                (escape(ctype), escape(object_pk), e.__class__.__name__))
+    form = comments.get_form()(target, data=frm.getFields())
+
+    if form.security_errors():
+        return CommentPostBadRequest(
+            "The comment form failed security verification: %s" % \
+                escape(str(form.security_errors())))
+
+    # If there are errors or if we requested a preview show the comment
+    if form.errors:
+        template_list = [
+            # These first two exist for purely historical reasons.
+            # Django v1.0 and v1.1 allowed the underscore format for
+            # preview templates, so we have to preserve that format.
+            "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.module_name),
+            "comments/%s_preview.html" % model._meta.app_label,
+            # Now the usual directory based template heirarchy.
+            "comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.module_name),
+            "comments/%s/preview.html" % model._meta.app_label,
+            "comments/preview.html",
+        ]
+        return render_to_response(
+            template_list, {
+                "comment" : form.data.get("comment", ""),
+                "frm" : frm,
+                "next": next,
+            },
+            RequestContext(request, {})
+        )
+
+    # Otherwise create the comment
+    comment = form.get_comment_object()
+    comment.ip_address = request.META.get("REMOTE_ADDR", None)
+    if request.user.is_authenticated():
+        comment.user = request.user
+
+    # Signal that the comment is about to be saved
+    responses = signals.comment_will_be_posted.send(
+        sender  = comment.__class__,
+        comment = comment,
+        request = request
+    )
+
+    for (receiver, response) in responses:
+        if response == False:
+            return CommentPostBadRequest(
+                "comment_will_be_posted receiver %r killed the comment" % receiver.__name__)
+
+    # Save the comment and signal that it was saved
+    comment.save()
+    signals.comment_was_posted.send(
+        sender  = comment.__class__,
+        comment = comment,
+        request = request
+    )
+
+    return next_redirect(frm.getFields(), next, comment_done)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.