Beispiel #1
0
    def test_comments_post(self):
        self.setup_sample_course()
        self.create_discussion(self.sample_course, self.instructor_one)
        discussion = get_course_discussions(self.sample_course)[0]

        url = reverse('comments-post-comment')
        data = {
            u'comment': [u'posted'],
            u'parent': [discussion.id],  # threadedcomment
            u'name': [],
            u'title': [u''],
            u'url': [u'']
        }

        frm = CommentSecurityForm(target_object=discussion.content_object)
        data.update(frm.generate_security_data())

        self.client.login(username=self.instructor_one.username,
                          password='******')
        self.switch_course(self.client, self.sample_course)
        response = self.client.post(url, data)
        self.assertEquals(response.status_code, 302)

        comment_id = re.search(r'\d+', response.url).group()
        obj = Comment.objects.get(id=comment_id)
        self.assertEquals(obj.comment, 'posted')
        self.assertEquals(obj.content_object, discussion.content_object)
        self.assertEquals(obj.user_name, 'Instructor One')
Beispiel #2
0
    def test_comments_post(self):
        self.setup_sample_course()
        self.create_discussion(self.sample_course, self.instructor_one)
        discussion = get_course_discussions(self.sample_course)[0]

        url = reverse('comments-post-comment')
        data = {
            u'comment': [u'posted'],
            u'parent': [discussion.id],  # threadedcomment
            u'name': [],
            u'title': [u''],
            u'url': [u'']
        }

        frm = CommentSecurityForm(target_object=discussion.content_object)
        data.update(frm.generate_security_data())

        self.client.login(username=self.instructor_one.username,
                          password='******')
        self.switch_course(self.client, self.sample_course)
        response = self.client.post(url, data)
        self.assertEquals(response.status_code, 302)

        comment_id = re.search(r'\d+', response.url).group()
        obj = Comment.objects.get(id=comment_id)
        self.assertEquals(obj.comment, 'posted')
        self.assertEquals(obj.content_object, discussion.content_object)
        self.assertEquals(obj.user_name, 'Instructor One')
    def _add_comment(self, discussion, author):
        url = reverse('comments-post-comment')
        data = {
            u'comment': [u'posted'],
            u'parent': [discussion.id],  # threadedcomment
            u'name': [],
            u'title': [u''],
            u'url': [u'']
        }

        frm = CommentSecurityForm(target_object=discussion.content_object)
        data.update(frm.generate_security_data())

        self.client.login(username=author.username, password='******')
        self.switch_course(self.client, self.sample_course)
        response = self.client.post(url, data)
        self.assertEquals(response.status_code, 302)
Beispiel #4
0
 def test_post_comment(self):
     self.client.login(username=self.user.username, password='******')
     response = self.client.get(
         reverse('astroobject-detail', args=(self.ao.id, )))
     post_time = int(time.time())
     data = {
         'content_type': 'objects.astroobject',
         'object_pk': self.ao.id,
         'timestamp': str(post_time),
     }
     form = CommentSecurityForm(self.ao)
     data['security_hash'] = form.initial_security_hash(post_time)
     data['comment'] = 'super secure comment'
     data['honeypot'] = ''
     response = self.client.post(reverse('comments-post-comment'),
                                 data,
                                 follow=True)
     self.assertContains(response, 'Thank you for your comment.')
 def render(self, context):
     obj = self.obj.resolve(context)
     form = CommentSecurityForm(obj)
     ctype = ContentType.objects.get_for_model(obj)
     queryset = XtdComment.objects.filter(content_type=ctype,
                                          object_pk=obj.pk,
                                          site__pk=settings.SITE_ID,
                                          is_public=True)
     ctype_slug = "%s-%s" % (ctype.app_label, ctype.model)
     d = {
         "comment_count": queryset.count(),
         "allow_comments": True,
         "current_user": "******",
         "request_name": False,
         "request_email_address": False,
         "is_authenticated": False,
         "allow_flagging": False,
         "allow_feedback": False,
         "show_feedback": False,
         "can_moderate": False,
         "poll_interval": 2000,
         "feedback_url": reverse("comments-xtd-api-feedback"),
         "delete_url": reverse("comments-delete", args=(0,)),
         "reply_url": reverse("comments-xtd-reply", kwargs={'cid': 0}),
         "flag_url": reverse("comments-flag", args=(0,)),
         "list_url": reverse('comments-xtd-api-list',
                             kwargs={'content_type': ctype_slug,
                                     'object_pk': obj.id}),
         "count_url": reverse('comments-xtd-api-count',
                              kwargs={'content_type': ctype_slug,
                                      'object_pk': obj.id}),
         "send_url": reverse("comments-xtd-api-create"),
         "form": {
             "content_type": form['content_type'].value(),
             "object_pk": form['object_pk'].value(),
             "timestamp": form['timestamp'].value(),
             "security_hash": form['security_hash'].value()
         }
     }
     user = context.get('user', None)
     try:
         user_is_authenticated = user.is_authenticated()
     except TypeError:  # Django >= 1.11
         user_is_authenticated = user.is_authenticated
     if user and user_is_authenticated:
         d['current_user'] = "******" % (
             user.pk, settings.COMMENTS_XTD_API_USER_REPR(user))
         d['is_authenticated'] = True
         d['can_moderate'] = user.has_perm("django_comments.can_moderate")
         d['request_name'] = True if not len(user.get_full_name()) else False
         d['request_email_address'] = True if not user.email else False
     else:
         d['login_url'] = "/admin/login/"
         d['like_url'] = reverse("comments-xtd-like", args=(0,))
         d['dislike_url'] = reverse("comments-xtd-dislike", args=(0,))
     return json.dumps(d)
    def validate(self, data):
        ctype = data.get("content_type")
        object_pk = data.get("object_pk")
        if ctype is None or object_pk is None:
            return serializers.ValidationError("Missing content_type or "
                                               "object_pk field.")
        try:
            model = apps.get_model(*ctype.split(".", 1))
            target = model._default_manager.get(pk=object_pk)
            whocan = get_app_model_options(content_type=ctype)['who_can_post']
        except (AttributeError, TypeError, LookupError):
            raise serializers.ValidationError("Invalid content_type value: %r"
                                              % escape(ctype))
        except model.ObjectDoesNotExist:
            raise serializers.ValidationError(
                "No object matching content-type %r and object PK %r exists."
                % (escape(ctype), escape(object_pk)))
        except (ValueError, serializers.ValidationError) as e:
            raise serializers.ValidationError(
                "Attempting to get content-type %r and object PK %r exists "
                "raised %s" % (escape(ctype), escape(object_pk),
                               e.__class__.__name__))
        else:
            if whocan == "users" and not self.request.user.is_authenticated:
                raise serializers.ValidationError("User not authenticated")

        # Signal that the request allows to be authorized.
        responses = should_request_be_authorized.send(
            sender=target.__class__,
            comment=target,
            request=self.request
        )

        for (receiver, response) in responses:
            if response is True:
                # A positive response indicates that the POST request
                # must be trusted. So inject the CommentSecurityForm values
                # to pass the form validation step.
                secform = CommentSecurityForm(target)
                data.update({
                    "honeypot": "",
                    "timestamp": secform['timestamp'].value(),
                    "security_hash": secform['security_hash'].value()
                })
                break
        self.form = get_form()(target, data=data)

        # Check security information.
        if self.form.security_errors():
            raise exceptions.PermissionDenied()
        if self.form.errors:
            raise serializers.ValidationError(self.form.errors)
        return data
def commentbox_props(obj, user, request=None):
    """
    Returns a JSON object with the initial props for the CommentBox component.

    The returned JSON object contains the following attributes::
        {
            comment_count: <int>,  // Count of comments posted to the object.
            allow_comments: <bool>,  // Whether to allow comments to this post.
            current_user: <str as "user_id:user_name">,
            is_authenticated: <bool>,  // Whether current_user is authenticated.
            request_name: <bool>,  // True when auth user has no actual name.
            request_email_address: <bool>,  // True when auth user has no email.
            allow_flagging: false,
            allow_feedback: false,
            show_feedback: false,
            can_moderate: <bool>,  // Whether current_user can moderate.
            poll_interval: 2000, // Check for new comments every 2 seconds.
            feedback_url: <api-url-to-send-like/dislike-feedback>,
            delete_url: <api-url-for-moderators-to-remove-comment>,
            login_url: settings.LOGIN_URL,
            reply_url: <api-url-to-reply-comments>,
            flag_url: <api-url-to-suggest-comment-removal>,
            list_url: <api-url-to-list-comments>,
            count_url: <api-url-to-count-comments>,
            send_url: <api-irl-to-send-a-comment>,
            form: {
                content_type: <value>,
                object_pk: <value>,
                timestamp: <value>,
                security_hash: <value>
            },
            login_url: <only_when_user_is_not_authenticated>,
            like_url: <only_when_user_is_not_authenticated>,
            dislike_url: <only_when_user_is_not_authenticated>
        }
    """
    def _reverse(*args, **kwargs):
        """do not inject request to avoid http:// urls on https:// only sites"""
        return reverse(*args, **kwargs)

    form = CommentSecurityForm(obj)
    ctype = ContentType.objects.get_for_model(obj)
    queryset = XtdComment.objects.filter(content_type=ctype,
                                         object_pk=obj.pk,
                                         site__pk=get_current_site_id(request),
                                         is_public=True)
    ctype_slug = "%s-%s" % (ctype.app_label, ctype.model)
    d = {
        "comment_count":
        queryset.count(),
        "allow_comments":
        True,
        "current_user":
        "******",
        "request_name":
        False,
        "request_email_address":
        False,
        "is_authenticated":
        False,
        "allow_flagging":
        False,
        "allow_feedback":
        False,
        "show_feedback":
        False,
        "can_moderate":
        False,
        "poll_interval":
        2000,
        "feedback_url":
        _reverse("comments-xtd-api-feedback"),
        "delete_url":
        _reverse("comments-delete", args=(0, )),
        "delete_url_own":
        _reverse("comments-xtd-delete-own-comment", args=(0, )),
        "reply_url":
        _reverse("comments-xtd-reply", kwargs={'cid': 0}),
        "edit_url":
        _reverse("comments-xtd-reply", kwargs={'cid': 0}),
        "flag_url":
        _reverse("comments-flag", args=(0, )),
        "list_url":
        _reverse('comments-xtd-api-list',
                 kwargs={
                     'content_type': ctype_slug,
                     'object_pk': obj.id
                 }),
        "count_url":
        _reverse('comments-xtd-api-count',
                 kwargs={
                     'content_type': ctype_slug,
                     'object_pk': obj.id
                 }),
        "send_url":
        _reverse("comments-xtd-api-create"),
        "form": {
            "content_type": form['content_type'].value(),
            "object_pk": form['object_pk'].value(),
            "timestamp": form['timestamp'].value(),
            "security_hash": form['security_hash'].value()
        }
    }
    try:
        user_is_authenticated = user.is_authenticated()
    except TypeError:  # Django >= 1.11
        user_is_authenticated = user.is_authenticated
    if user and user_is_authenticated:
        d['current_user'] = "******" % (
            user.pk, settings.COMMENTS_XTD_API_USER_REPR(user))
        d['is_authenticated'] = True
        d['can_moderate'] = user.has_perm("django_comments.can_moderate")
        d['request_name'] = True if not len(user.get_full_name()) else False
        d['request_email_address'] = True if not user.email else False
    else:
        d['login_url'] = "/admin/login/"
        d['like_url'] = reverse("comments-xtd-like", args=(0, ))
        d['dislike_url'] = reverse("comments-xtd-dislike", args=(0, ))

    return d