Exemplo n.º 1
0
def postView(request, id):

    # We could check to see if the user has permission to view this post in here
    # Based on the privacy setting etc.

    # This is our post object with the given ID
    # If the post doesn't exist it instantly 404's
    # This way we won't have to do any taxing database math
    post = get_object_or_404(Post, pk=id)  #pk is primary key

    # Do not display an image if the image does not exist
    imageExists = False
    if post.image_link != "":
        imageExists = True

    # Perform privacy calculations
    # Has permission will be passed in
    # If its False we could either display a 404 or a "you do not have permission"
    hasPermission = Services.has_permission_to_see_post(request.user.id, post)

    if post.is_markdown:
        post.body = markdownify(post.body)

    # Post is the post data
    # imageExists is whether or not there is an image to display
    # markDown is whether or not to display the plaintext or markdown contents
    # Has permission determines whether or not to display content to the user
    post.privacy_setting = Services.get_privacy_string_for_post(
        post.privacy_setting)
    return render(request, 'post/post.html', {
        "post": post,
        "imageExists": imageExists,
        "hasPermission": hasPermission
    })
Exemplo n.º 2
0
 def test_permissions_work_with_non_uuid(self):
     # essentially test that we can pass in a string (instead of a UUID) without the function crashing
     myPost = Post.objects.get(id="9c4f71d9-fcc5-48b0-8092-9b775969bc9f")
     hasPermission = Services.has_permission_to_see_post(
         "8c4f71d9-fcc5-48b0-8092-9b775969bc9e", myPost)
     # if we get here, there hasn't been an error
     self.assertEqual(True, hasPermission)
Exemplo n.º 3
0
 def test_fofof_cant_see_fof_posts(self):
     friendOfFriendOfSomeUser = UserModels.CustomUser.objects.get(
         id="8c4f71d9-fcc5-48b0-8092-9b775969bc9a")
     myPost = Post.objects.get(id="9c4f71d9-fcc5-48b0-8092-9b775969bc9a")
     hasPermission = Services.has_permission_to_see_post(
         friendOfFriendOfSomeUser.id, myPost)
     self.assertEqual(False, hasPermission)
Exemplo n.º 4
0
 def test_user_cannot_see_another_author_posts_when_not_allowed(self):
     """Users cannot see Another Author posts if they aren't authorized"""
     strangerUser = UserModels.CustomUser.objects.get(
         id="8c4f71d9-fcc5-48b0-8092-9b775969bc9e")
     myPost = Post.objects.get(id="9c4f71d9-fcc5-48b0-8092-9b775969bc9d")
     hasPermission = Services.has_permission_to_see_post(
         strangerUser.id, myPost)
     self.assertEqual(False, hasPermission)
Exemplo n.º 5
0
 def test_user_can_see_another_author_posts_when_allowed(self):
     """Authorized users can see the post when the post privacy is set to Another Author"""
     someUser = UserModels.CustomUser.objects.get(
         id="8c4f71d9-fcc5-48b0-8092-9b775969bc9d")
     myPost = Post.objects.get(id="9c4f71d9-fcc5-48b0-8092-9b775969bc9d")
     hasPermission = Services.has_permission_to_see_post(
         someUser.id, myPost)
     self.assertEqual(True, hasPermission)
Exemplo n.º 6
0
    def test_user_can_see_their_own_posts(self):
        """Users can see their own posts"""
        author = UserModels.CustomUser.objects.get(
            id="8c4f71d9-fcc5-48b0-8092-9b775969bc9c")
        myPost = Post.objects.get(id="9c4f71d9-fcc5-48b0-8092-9b775969bc9c")

        hasPermission = Services.has_permission_to_see_post(author.id, myPost)
        self.assertEqual(True, hasPermission)
Exemplo n.º 7
0
 def test_user_can_see_public_posts(self):
     """Users can see public posts"""
     strangerUser = UserModels.CustomUser.objects.get(
         id="8c4f71d9-fcc5-48b0-8092-9b775969bc9e")
     myPost = Post.objects.get(id="9c4f71d9-fcc5-48b0-8092-9b775969bc9f")
     hasPermission = Services.has_permission_to_see_post(
         strangerUser.id, myPost)
     self.assertEqual(True, hasPermission)
Exemplo n.º 8
0
 def test_users_should_be_able_to_see_unlisted(self):
     # has_permission_to_see_post wouldn't be called if they didn't know the url
     strangerUser = UserModels.CustomUser.objects.get(
         id="8c4f71d9-fcc5-48b0-8092-9b775969bc9e")
     myPost = Post.objects.get(id="9c4f71d9-fcc5-48b0-8092-9b775969bc9b")
     hasPermission = Services.has_permission_to_see_post(
         strangerUser.id, myPost)
     self.assertEqual(True, hasPermission)
Exemplo n.º 9
0
 def test_user_cannot_see_friends_posts_of_non_friends(self):
     """Users can't see My Friends posts when they aren't friends"""
     strangerUser = UserModels.CustomUser.objects.get(
         id="8c4f71d9-fcc5-48b0-8092-9b775969bc9e")
     myPost = Post.objects.get(id="9c4f71d9-fcc5-48b0-8092-9b775969bc9e")
     hasPermission = Services.has_permission_to_see_post(
         strangerUser.id, myPost)
     self.assertEqual(False, hasPermission)
Exemplo n.º 10
0
 def test_user_can_see_their_friends_posts_when_allowed(self):
     """Users can see their friends' posts when the posts are set to My Friends"""
     someUser = UserModels.CustomUser.objects.get(
         id="8c4f71d9-fcc5-48b0-8092-9b775969bc9d")
     myPost = Post.objects.get(id="9c4f71d9-fcc5-48b0-8092-9b775969bc9e")
     hasPermission = Services.has_permission_to_see_post(
         someUser.id, myPost)
     self.assertEqual(True, hasPermission)
Exemplo n.º 11
0
 def test_permissions_work_with_uuid(self):
     # essentially test that we can pass in a UUID without the function crashing
     # This is currently the same as an above test and uuid functionality is implicitly tested by other tests
     # but I want to make sure this is explicitly tested in case the above tests change
     strangerUser = UserModels.CustomUser.objects.get(
         id="8c4f71d9-fcc5-48b0-8092-9b775969bc9e")
     myPost = Post.objects.get(id="9c4f71d9-fcc5-48b0-8092-9b775969bc9f")
     hasPermission = Services.has_permission_to_see_post(
         strangerUser.id, myPost)
     self.assertEqual(True, hasPermission)
Exemplo n.º 12
0
    def retrieve(self, request, pk=None):
        # permission_classes = (IsAuthenticated,)
        queryset = Post.objects.filter(pk=pk)
        # serializer_class = PostSerializer(queryset, many=True)
        post = getPostData(request, pk=pk)
        requested_post = Post.objects.get(pk=pk)
        response = OrderedDict()
        response.update({"query": "getPost"})
        response.update({"posts": post})

        request_user_id = getAuthorIdForApiRequest(request)
        if request_user_id == None:
            raise ParseError(
                "No correct X-User header or authentication were provided.")

        if not Services.has_permission_to_see_post(request_user_id,
                                                   requested_post):
            return Response("403", status=403)

        # return Response(serializer_class.data)
        return Response(response)
Exemplo n.º 13
0
def profileView(request, username):
    author = CustomUser.objects.get(username=username)

    # will probably change the edit profile functionality later, and check if profile author == logged in user here
    # get the profile author
    if request.user.username == username:
        profile_posts = Post.objects.filter(
            author=author.id).order_by('-published')
    else:
        profile_posts_all = Post.objects.filter(
            author=author.id).order_by('-published')
        profile_posts = []
        for post in profile_posts_all:
            if Services.has_permission_to_see_post(request.user.id, post):
                profile_posts.append(post)
    for p in profile_posts:
        if p.is_markdown:
            p.body = markdownify(p.body)

    return render(request, 'profile/profile.html', {
        'author': author,
        "posts": profile_posts
    })
Exemplo n.º 14
0
    def userPosts(self, request, pk=None):
        author_id = self.kwargs['pk']
        author_id = str(author_id)
        # uname = request.user
        # uid = uname.id
        uid = getAuthorIdForApiRequest(request)
        if uid == None:
            raise ParseError(
                "No correct X-User header or authentication were provided.")
        uid = str(uid)

        # allowed_posts = Post.objects.raw(' \
        # WITH posts AS (SELECT id FROM API_post WHERE author_id in  \
        # (SELECT f2.friend_a_id AS fofid \
        #     FROM API_friendship f \
        #     JOIN API_friendship f2 ON f.friend_a_id = f2.friend_b_id \
        #     WHERE fofid NOT IN (SELECT friend_a_ID FROM API_friendship  \
        #     WHERE friend_b_id = %s) AND f.friend_b_id = %s AND fofid != %s) AND privacy_setting = 4 \
        # UNION \
        #     SELECT id FROM API_post WHERE (author_id in  \
        #     (WITH friends(fid) AS (SELECT friend_b_id FROM API_friendship WHERE friend_a_id=%s) \
        #     SELECT * FROM friends WHERE fid != %s GROUP BY fid)  \
        #     AND (privacy_setting = 3 OR privacy_setting = 4)) OR author_id = %s OR  privacy_setting = 6) \
        #     SELECT * FROM API_post WHERE id in posts \
        #     AND author_id = %s \
        #     ORDER BY published DESC', [str(uid)]*6 + [author_id])

        # Instead of this big boy query, just query for all our posts
        # Then for each post, check to see if the user has permission
        allowed_posts = []
        allPosts = Post.objects.filter(author=author_id).order_by(
            '-published')  # I think this returns them all
        for post in allPosts:
            if Services.has_permission_to_see_post(uid, post):
                allowed_posts.append(post)

        paginator = PostsPagination()
        paginated_posts = paginator.paginate_queryset(allowed_posts, request)
        serialized_posts = PostSerializer(paginated_posts, many=True)

        response = OrderedDict()
        response.update({"query": "posts"})
        response.update({"count": len(allowed_posts)})
        response.update({"size": Services.get_page_size(request, paginator)})
        response.update({"next": None})
        response.update({"previous": None})
        # response.update({"posts": serialized_posts.data})

        posts = []

        for post in serialized_posts.data:
            # Get single post information
            postId = str(post["id"])
            posts.append(getPostData(request, pk=postId))

        # response.update({"posts":serialized_posts.data})
        response.update({"posts": posts})

        if paginator.get_next_link() is not None:
            response["next"] = paginator.get_next_link()
        if paginator.get_previous_link() is not None:
            response["previous"] = paginator.get_previous_link()
        return Response(response)
Exemplo n.º 15
0
    def userPostComments(self, request, pk=None):
        permission_classes = (IsAuthenticated, )
        post_id = pk

        # does the post exist?
        try:
            requested_post = Post.objects.get(id=post_id)
        except:
            response = {
                'query': 'addComment',
                'success': False,
                'message': "Comment not allowed"
            }
            return Response(response, status=403)

        if request.method == "POST":
            # check that we're allowed to see the post - for now just check if the posts are public
            # for right now, just return comments from public posts
            # should we check if post visibility is serveronly/private?
            request_user_id = getAuthorIdForApiRequest(request)
            if request_user_id == None:
                raise ParseError(
                    "No correct X-User header or authentication were provided."
                )

            if Services.has_permission_to_see_post(request_user_id,
                                                   requested_post):
                body = json.loads(request.body.decode('utf-8'))

                if Services.addComment(body, post_id):

                    response = {
                        'query': 'addComment',
                        'success': True,
                        'message': "Comment Added"
                    }
                    return Response(response, status=200)
                else:
                    response = {
                        'query': 'addComment',
                        'success': False,
                        'message': "Comment not allowed"
                    }
                    return Response(response, status=403)

        elif request.method == "GET":  # this handles "GET" methods
            # check that we're allowed to see the post - for now just check if the posts are public
            # for right now, just return comments from public posts
            paginator = PostsPagination()
            # if requested_post.privacy_setting == "6":
            request_user_id = getAuthorIdForApiRequest(request)
            if request_user_id == None:
                raise ParseError(
                    "No correct X-User header or authentication were provided."
                )

            if Services.has_permission_to_see_post(request_user_id,
                                                   requested_post):
                queryset = Comment.objects.filter(
                    post=pk).order_by('-datetime')
                comments = CommentSerializer(queryset, many=True).data
                comments_response = []

                for comment in comments:
                    comments_response.append(
                        getCommentData(request, pk=comment["id"]))

                paginated_comments = paginator.paginate_queryset(
                    comments_response, request)

                response = OrderedDict()
                response.update({"query": "comments"})
                response.update({"count": len(queryset)})
                response.update(
                    {"size": Services.get_page_size(request, paginator)})
                response.update({"next": None})
                response.update({"previous": None})
                response.update({"comments": paginated_comments})

                if paginator.get_next_link() is not None:
                    response["next"] = paginator.get_next_link()
                if paginator.get_previous_link() is not None:
                    response["previous"] = paginator.get_previous_link()

                return Response(response)
            else:
                raise PermissionDenied(
                    "Forbidden: You don't have permission to access comments for this post or you provided an invalid user."
                )
        else:
            raise MethodNotAllowed(method=request.method)