Fix permission checking
This commit is contained in:
parent
ea31eb47ae
commit
26997475fd
|
@ -95,7 +95,7 @@ export default function LinkCard({
|
|||
{showCheckbox &&
|
||||
<input
|
||||
type="checkbox"
|
||||
className="checkbox checkbox-primary my-auto ml-3 mt-3 absolute z-20 bg-white"
|
||||
className="checkbox checkbox-primary my-auto ml-3 mt-3 absolute z-20 bg-white dark:bg-base-200"
|
||||
checked={selectedLinks.includes(link.id)}
|
||||
onChange={() => handleCheckboxClick(link.id)}
|
||||
/>
|
||||
|
|
|
@ -25,7 +25,7 @@ export default function BulkDeleteLinksModal({ onClose }: Props) {
|
|||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
<p className="text-xl font-thin text-red-500">Delete {selectedLinks.length}</p>
|
||||
<p className="text-xl font-thin text-red-500">Delete {selectedLinks.length} Link{selectedLinks.length > 1 ? "s" : ""}!</p>
|
||||
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
|
||||
|
|
|
@ -0,0 +1,150 @@
|
|||
import React, { useEffect, useState } from "react";
|
||||
import CollectionSelection from "@/components/InputSelect/CollectionSelection";
|
||||
import TagSelection from "@/components/InputSelect/TagSelection";
|
||||
import TextInput from "@/components/TextInput";
|
||||
import unescapeString from "@/lib/client/unescapeString";
|
||||
import useLinkStore from "@/store/links";
|
||||
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
|
||||
import toast from "react-hot-toast";
|
||||
import Link from "next/link";
|
||||
import Modal from "../Modal";
|
||||
|
||||
type Props = {
|
||||
onClose: Function;
|
||||
};
|
||||
|
||||
export default function EditLinkModal({ onClose }: Props) {
|
||||
const { updateLink, updateLinksById } = useLinkStore();
|
||||
const [submitLoader, setSubmitLoader] = useState(false);
|
||||
const [updatedValues, setUpdatedValues] = useState<Partial<LinkIncludingShortenedCollectionAndTags>>();
|
||||
|
||||
const setCollection = (e: any) => {
|
||||
if (e?.__isNew__) e.value = null;
|
||||
|
||||
setUpdatedValues({
|
||||
...updatedValues,
|
||||
collection: { id: e?.value, name: e?.label, ownerId: e?.ownerId },
|
||||
});
|
||||
};
|
||||
|
||||
const setTags = (e: any) => {
|
||||
const tagNames = e.map((e: any) => {
|
||||
return { name: e.label };
|
||||
});
|
||||
|
||||
setUpdatedValues({ ...updatedValues, tags: tagNames });
|
||||
};
|
||||
|
||||
const submit = async () => {
|
||||
if (!submitLoader) {
|
||||
setSubmitLoader(true);
|
||||
|
||||
let response;
|
||||
|
||||
const load = toast.loading("Updating...");
|
||||
|
||||
response = await updateLinksById(user);
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
if (response.ok) {
|
||||
toast.success(`Updated!`);
|
||||
onClose();
|
||||
} else toast.error(response.data as string);
|
||||
|
||||
setSubmitLoader(false);
|
||||
|
||||
return response;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal toggleModal={onClose}>
|
||||
<p className="text-xl font-thin">Edit Link</p>
|
||||
|
||||
<div className="divider mb-3 mt-1"></div>
|
||||
|
||||
{link.url ? (
|
||||
<Link
|
||||
href={link.url}
|
||||
className="truncate text-neutral flex gap-2 mb-5 w-fit max-w-full"
|
||||
title={link.url}
|
||||
target="_blank"
|
||||
>
|
||||
<i className="bi-link-45deg text-xl" />
|
||||
<p>{shortendURL}</p>
|
||||
</Link>
|
||||
) : undefined}
|
||||
|
||||
<div className="w-full">
|
||||
<p className="mb-2">Name</p>
|
||||
<TextInput
|
||||
value={link.name}
|
||||
onChange={(e) => setLink({ ...link, name: e.target.value })}
|
||||
placeholder="e.g. Example Link"
|
||||
className="bg-base-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-5">
|
||||
{/* <hr className="mb-3 border border-neutral-content" /> */}
|
||||
<div className="grid sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<p className="mb-2">Collection</p>
|
||||
{link.collection.name ? (
|
||||
<CollectionSelection
|
||||
onChange={setCollection}
|
||||
// defaultValue={{
|
||||
// label: link.collection.name,
|
||||
// value: link.collection.id,
|
||||
// }}
|
||||
defaultValue={
|
||||
link.collection.id
|
||||
? {
|
||||
value: link.collection.id,
|
||||
label: link.collection.name,
|
||||
}
|
||||
: {
|
||||
value: null as unknown as number,
|
||||
label: "Unorganized",
|
||||
}
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-2">Tags</p>
|
||||
<TagSelection
|
||||
onChange={setTags}
|
||||
defaultValue={link.tags.map((e) => {
|
||||
return { label: e.name, value: e.id };
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-2">
|
||||
<p className="mb-2">Description</p>
|
||||
<textarea
|
||||
value={unescapeString(link.description) as string}
|
||||
onChange={(e) =>
|
||||
setLink({ ...link, description: e.target.value })
|
||||
}
|
||||
placeholder="Will be auto generated if nothing is provided."
|
||||
className="resize-none w-full rounded-md p-2 border-neutral-content bg-base-200 focus:border-sky-300 dark:focus:border-sky-600 border-solid border outline-none duration-100"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end items-center mt-5">
|
||||
<button
|
||||
className="btn btn-accent dark:border-violet-400 text-white"
|
||||
onClick={submit}
|
||||
>
|
||||
Save Changes
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
|
@ -4,18 +4,18 @@ import getPermission from "@/lib/api/getPermission";
|
|||
import removeFile from "@/lib/api/storage/removeFile";
|
||||
|
||||
export default async function deleteLinksById(userId: number, linkIds: number[]) {
|
||||
console.log("linkIds: ", linkIds);
|
||||
if (!linkIds || linkIds.length === 0) {
|
||||
return { response: "Please choose valid links.", status: 401 };
|
||||
}
|
||||
|
||||
const deletedLinks = [];
|
||||
const collectionIsAccessibleArray = [];
|
||||
|
||||
// Check if the user has access to the collection of each link
|
||||
// if any of the links are not accessible, return an error
|
||||
// if all links are accessible, continue with the deletion
|
||||
// and add the collection to the collectionIsAccessibleArray
|
||||
for (const linkId of linkIds) {
|
||||
const collectionIsAccessible = await getPermission({
|
||||
userId,
|
||||
linkId,
|
||||
});
|
||||
const collectionIsAccessible = await getPermission({ userId, linkId });
|
||||
|
||||
const memberHasAccess = collectionIsAccessible?.members.some(
|
||||
(e: UsersAndCollections) => e.userId === userId && e.canDelete
|
||||
|
@ -25,12 +25,21 @@ export default async function deleteLinksById(userId: number, linkIds: number[])
|
|||
return { response: "Collection is not accessible.", status: 401 };
|
||||
}
|
||||
|
||||
const deletedLink = await prisma.link.delete({
|
||||
collectionIsAccessibleArray.push(collectionIsAccessible);
|
||||
}
|
||||
|
||||
const deletedLinks = await prisma.link.deleteMany({
|
||||
where: {
|
||||
id: linkId,
|
||||
id: { in: linkIds },
|
||||
},
|
||||
});
|
||||
|
||||
// Loop through each link and delete the associated files
|
||||
// if the user has access to the collection
|
||||
for (let i = 0; i < linkIds.length; i++) {
|
||||
const linkId = linkIds[i];
|
||||
const collectionIsAccessible = collectionIsAccessibleArray[i];
|
||||
|
||||
removeFile({
|
||||
filePath: `archives/${collectionIsAccessible?.id}/${linkId}.pdf`,
|
||||
});
|
||||
|
@ -40,8 +49,6 @@ export default async function deleteLinksById(userId: number, linkIds: number[])
|
|||
removeFile({
|
||||
filePath: `archives/${collectionIsAccessible?.id}/${linkId}_readability.json`,
|
||||
});
|
||||
|
||||
deletedLinks.push(deletedLink);
|
||||
}
|
||||
|
||||
return { response: deletedLinks, status: 200 };
|
||||
|
|
|
@ -0,0 +1,64 @@
|
|||
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
|
||||
import { prisma } from "@/lib/api/db";
|
||||
import getPermission from "@/lib/api/getPermission";
|
||||
import { UsersAndCollections } from "@prisma/client";
|
||||
|
||||
export default async function updateLinksById(userId: number, linkIds: number[], data: LinkIncludingShortenedCollectionAndTags) {
|
||||
if (!linkIds || linkIds.length === 0) {
|
||||
return { response: "Please choose valid links.", status: 401 };
|
||||
}
|
||||
|
||||
// Check if the user has access to the collection of each link
|
||||
// if any of the links are not accessible, return an error
|
||||
for (const linkId of linkIds) {
|
||||
const linkIsAccessible = await getPermission({ userId, linkId });
|
||||
|
||||
const memberHasAccess = linkIsAccessible?.members.some(
|
||||
(e: UsersAndCollections) => e.userId === userId && e.canUpdate
|
||||
);
|
||||
|
||||
if (!(linkIsAccessible?.ownerId === userId || memberHasAccess)) {
|
||||
return { response: "Link is not accessible.", status: 401 };
|
||||
}
|
||||
}
|
||||
|
||||
const updateData = {
|
||||
collection: {
|
||||
connect: {
|
||||
id: data.collection.id,
|
||||
},
|
||||
},
|
||||
tags: {
|
||||
set: [],
|
||||
connectOrCreate: data.tags.map((tag) => ({
|
||||
where: {
|
||||
name_ownerId: {
|
||||
name: tag.name,
|
||||
ownerId: data.collection.ownerId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
name: tag.name,
|
||||
owner: {
|
||||
connect: {
|
||||
id: data.collection.ownerId,
|
||||
},
|
||||
},
|
||||
},
|
||||
})),
|
||||
},
|
||||
include: {
|
||||
tags: true,
|
||||
collection: true,
|
||||
}
|
||||
};
|
||||
|
||||
const updatedLinks = await prisma.link.updateMany({
|
||||
where: {
|
||||
id: { in: linkIds },
|
||||
},
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
return { response: updatedLinks, status: 200 };
|
||||
}
|
|
@ -1,12 +1,19 @@
|
|||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import verifyUser from "@/lib/api/verifyUser";
|
||||
import deleteLinksById from "@/lib/api/controllers/links/bulk/deleteLinksById";
|
||||
import updateLinksById from "@/lib/api/controllers/links/bulk/updateLinksById";
|
||||
|
||||
export default async function links(req: NextApiRequest, res: NextApiResponse) {
|
||||
const user = await verifyUser({ req, res });
|
||||
if (!user) return;
|
||||
|
||||
if (req.method === "DELETE") {
|
||||
if (req.method === "PUT") {
|
||||
const updated = await updateLinksById(user.id, req.body.linkIds, req.body.data);
|
||||
return res.status(updated.status).json({
|
||||
response: updated.response,
|
||||
});
|
||||
}
|
||||
else if (req.method === "DELETE") {
|
||||
const deleted = await deleteLinksById(user.id, req.body.linkIds);
|
||||
return res.status(deleted.status).json({
|
||||
response: deleted.response,
|
||||
|
|
|
@ -23,6 +23,7 @@ type LinkStore = {
|
|||
updateLink: (
|
||||
link: LinkIncludingShortenedCollectionAndTags
|
||||
) => Promise<ResponseObject>;
|
||||
updateLinksById: (linkIds: number[], data: Partial<LinkIncludingShortenedCollectionAndTags>) => Promise<ResponseObject>;
|
||||
removeLink: (linkId: number) => Promise<ResponseObject>;
|
||||
deleteLinksById: (linkIds: number[]) => Promise<ResponseObject>;
|
||||
resetLinks: () => void;
|
||||
|
@ -127,6 +128,29 @@ const useLinkStore = create<LinkStore>()((set) => ({
|
|||
|
||||
return { ok: response.ok, data: data.response };
|
||||
},
|
||||
updateLinksById: async (linkIds, data) => {
|
||||
const response = await fetch("/api/v1/links/bulk", {
|
||||
body: JSON.stringify({ linkIds, data }),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: "PUT",
|
||||
});
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
set((state) => ({
|
||||
links: state.links.map((link) =>
|
||||
linkIds.includes(link.id) ? { ...link, ...data } : link
|
||||
),
|
||||
}));
|
||||
useTagStore.getState().setTags();
|
||||
useCollectionStore.getState().setCollections();
|
||||
}
|
||||
|
||||
return { ok: response.ok, data: responseData.response };
|
||||
},
|
||||
removeLink: async (linkId) => {
|
||||
const response = await fetch(`/api/v1/links/${linkId}`, {
|
||||
headers: {
|
||||
|
|
Ŝarĝante…
Reference in New Issue