Skip to content

Commit

Permalink
Security Fix: Deny users from editing others posts. (#48)
Browse files Browse the repository at this point in the history
* Vulnerability Fix: Deny edits from other users.

Users currently can go to other peoples posts and edit them without any checks if its their post or not, all they have to do is figure out the id for the post and go to /editor/[postId], do their edits and save it.

This can be very bad (not so much in this circumstance).

* Add the missing code (forgot to add a few lines)

* Fixed linting & code errors.

* Fixed typescript issues.

* Overall fixes, read the comment.

---------

Co-authored-by: Touha Zohair <[email protected]>
  • Loading branch information
Fr3akyMurk and iamtouha authored Mar 10, 2024
1 parent 84529e2 commit f52d0f3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
18 changes: 16 additions & 2 deletions src/app/(main)/editor/[postId]/_components/post-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,17 @@ import { api } from "@/trpc/react";
import { Pencil2Icon } from "@/components/icons";
import { LoadingButton } from "@/components/loading-button";
import Link from "next/link";
import { toast } from "sonner";

const markdownlink = "https://remarkjs.github.io/react-markdown/" // Can also be changed for something like /markdown

type usertype = {
id: string;
}

interface Props {
post: RouterOutputs["post"]["get"];
user: usertype;
}

const schema = z.object({
Expand All @@ -37,7 +43,7 @@ const schema = z.object({
.max(2048 * 2),
});

export const PostEditor = ({ post }: Props) => {
export const PostEditor = ({ post, user }: Props) => {
if (!post) return null;
const formRef = useRef<HTMLFormElement>(null);
const updatePost = api.post.update.useMutation();
Expand All @@ -50,8 +56,16 @@ export const PostEditor = ({ post }: Props) => {
resolver: zodResolver(schema),
});
const onSubmit = form.handleSubmit(async (values) => {
updatePost.mutate({ id: post.id, ...values });
if (user.id == post.userId) {
updatePost.mutate({ id: post.id, ...values });
toast('Saved the post successfully.');
return;
}

toast('You do not have permission to edit this post.');
return;
});


return (
<>
Expand Down
2 changes: 1 addition & 1 deletion src/app/(main)/editor/[postId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export default async function EditPostPage({ params }: Props) {
<ArrowLeftIcon className="h-5 w-5" /> back to dashboard
</Link>

<PostEditor post={post} />
<PostEditor post={post} user={user} />
</main>
);
}

0 comments on commit f52d0f3

Please sign in to comment.