Merge pull request #250 from linkwarden/dev

refactored/cleaned up API + added support for renaming tags
This commit is contained in:
Daniel 2023-10-23 00:30:30 -04:00 committed by GitHub
commit 86cfdd508a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
48 changed files with 603 additions and 305 deletions

View File

@ -20,14 +20,5 @@ NEXT_PUBLIC_EMAIL_PROVIDER=
EMAIL_FROM= EMAIL_FROM=
EMAIL_SERVER= EMAIL_SERVER=
# Stripe settings (You don't need these, it's for the cloud instance payments)
NEXT_PUBLIC_STRIPE_IS_ACTIVE=
STRIPE_SECRET_KEY=
MONTHLY_PRICE_ID=
YEARLY_PRICE_ID=
NEXT_PUBLIC_TRIAL_PERIOD_DAYS=
NEXT_PUBLIC_STRIPE_BILLING_PORTAL_URL=
BASE_URL=http://localhost:3000
# Docker postgres settings # Docker postgres settings
POSTGRES_PASSWORD= POSTGRES_PASSWORD=

View File

@ -38,7 +38,7 @@ We highly recommend that you don't use the old version because it is no longer m
## Features ## Features
- 📸 Auto capture a screenshot and a PDF of each link. - 📸 Auto capture a screenshot and a PDF of each link.
- 🏛️ Send your webpage to Wayback Machine archive.org for a snapshot. - 🏛️ Send your webpage to Wayback Machine ([archive.org](https://archive.org)) for a snapshot. (Optional)
- 📂 Organize links by collection, name, description and multiple tags. - 📂 Organize links by collection, name, description and multiple tags.
- 👥 Collaborate on gathering links in a collection. - 👥 Collaborate on gathering links in a collection.
- 🔐 Customize the permissions of each member. - 🔐 Customize the permissions of each member.

View File

@ -68,7 +68,7 @@ export default function CollectionCard({ collection, className }: Props) {
return ( return (
<ProfilePhoto <ProfilePhoto
key={i} key={i}
src={`/api/avatar/${e.userId}?${Date.now()}`} src={`/api/v1/avatar/${e.userId}?${Date.now()}`}
className="-mr-3 border-[3px]" className="-mr-3 border-[3px]"
/> />
); );

View File

@ -87,7 +87,7 @@ export default function LinkCard({ link, count, className }: Props) {
const deleteLink = async () => { const deleteLink = async () => {
const load = toast.loading("Deleting..."); const load = toast.loading("Deleting...");
const response = await removeLink(link); const response = await removeLink(link.id as number);
toast.dismiss(load); toast.dismiss(load);

View File

@ -58,7 +58,7 @@ export default function TeamManagement({
useEffect(() => { useEffect(() => {
const fetchOwner = async () => { const fetchOwner = async () => {
const owner = await getPublicUserData({ id: collection.ownerId }); const owner = await getPublicUserData(collection.ownerId as number);
setCollectionOwner(owner); setCollectionOwner(owner);
}; };
@ -238,7 +238,7 @@ export default function TeamManagement({
)} )}
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<ProfilePhoto <ProfilePhoto
src={`/api/avatar/${e.userId}?${Date.now()}`} src={`/api/v1/avatar/${e.userId}?${Date.now()}`}
className="border-[3px]" className="border-[3px]"
/> />
<div> <div>
@ -425,7 +425,7 @@ export default function TeamManagement({
> >
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<ProfilePhoto <ProfilePhoto
src={`/api/avatar/${collection.ownerId}?${Date.now()}`} src={`/api/v1/avatar/${collection.ownerId}?${Date.now()}`}
className="border-[3px]" className="border-[3px]"
/> />
<div> <div>

View File

@ -106,7 +106,7 @@ export default function LinkDetails({ link, isOwnerOrMod }: Props) {
}, [colorPalette, theme]); }, [colorPalette, theme]);
const handleDownload = (format: "png" | "pdf") => { const handleDownload = (format: "png" | "pdf") => {
const path = `/api/archives/${link.collection.id}/${link.id}.${format}`; const path = `/api/v1/archives/${link.collection.id}/${link.id}.${format}`;
fetch(path) fetch(path)
.then((response) => { .then((response) => {
if (response.ok) { if (response.ok) {
@ -250,7 +250,7 @@ export default function LinkDetails({ link, isOwnerOrMod }: Props) {
</div> </div>
<Link <Link
href={`/api/archives/${link.collectionId}/${link.id}.png`} href={`/api/v1/archives/${link.collectionId}/${link.id}.png`}
target="_blank" target="_blank"
className="cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-2 rounded-md" className="cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-2 rounded-md"
> >
@ -283,7 +283,7 @@ export default function LinkDetails({ link, isOwnerOrMod }: Props) {
</div> </div>
<Link <Link
href={`/api/archives/${link.collectionId}/${link.id}.pdf`} href={`/api/v1/archives/${link.collectionId}/${link.id}.pdf`}
target="_blank" target="_blank"
className="cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-2 rounded-md" className="cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-2 rounded-md"
> >

View File

@ -33,7 +33,7 @@ export default function useLinks(
const encodedData = encodeURIComponent(JSON.stringify(requestBody)); const encodedData = encodeURIComponent(JSON.stringify(requestBody));
const response = await fetch( const response = await fetch(
`/api/links?body=${encodeURIComponent(encodedData)}` `/api/v1/links?body=${encodeURIComponent(encodedData)}`
); );
const data = await response.json(); const data = await response.json();

View File

@ -4,15 +4,16 @@ import { Collection, UsersAndCollections } from "@prisma/client";
import removeFolder from "@/lib/api/storage/removeFolder"; import removeFolder from "@/lib/api/storage/removeFolder";
export default async function deleteCollection( export default async function deleteCollection(
collection: { id: number }, userId: number,
userId: number collectionId: number
) { ) {
const collectionId = collection.id;
if (!collectionId) if (!collectionId)
return { response: "Please choose a valid collection.", status: 401 }; return { response: "Please choose a valid collection.", status: 401 };
const collectionIsAccessible = (await getPermission(userId, collectionId)) as const collectionIsAccessible = (await getPermission({
userId,
collectionId,
})) as
| (Collection & { | (Collection & {
members: UsersAndCollections[]; members: UsersAndCollections[];
}) })

View File

@ -4,16 +4,17 @@ import getPermission from "@/lib/api/getPermission";
import { Collection, UsersAndCollections } from "@prisma/client"; import { Collection, UsersAndCollections } from "@prisma/client";
export default async function updateCollection( export default async function updateCollection(
collection: CollectionIncludingMembersAndLinkCount, userId: number,
userId: number collectionId: number,
data: CollectionIncludingMembersAndLinkCount
) { ) {
if (!collection.id) if (!collectionId)
return { response: "Please choose a valid collection.", status: 401 }; return { response: "Please choose a valid collection.", status: 401 };
const collectionIsAccessible = (await getPermission( const collectionIsAccessible = (await getPermission({
userId, userId,
collection.id collectionId,
)) as })) as
| (Collection & { | (Collection & {
members: UsersAndCollections[]; members: UsersAndCollections[];
}) })
@ -26,23 +27,23 @@ export default async function updateCollection(
await prisma.usersAndCollections.deleteMany({ await prisma.usersAndCollections.deleteMany({
where: { where: {
collection: { collection: {
id: collection.id, id: collectionId,
}, },
}, },
}); });
return await prisma.collection.update({ return await prisma.collection.update({
where: { where: {
id: collection.id, id: collectionId,
}, },
data: { data: {
name: collection.name.trim(), name: data.name.trim(),
description: collection.description, description: data.description,
color: collection.color, color: data.color,
isPublic: collection.isPublic, isPublic: data.isPublic,
members: { members: {
create: collection.members.map((e) => ({ create: data.members.map((e) => ({
user: { connect: { id: e.user.id || e.userId } }, user: { connect: { id: e.user.id || e.userId } },
canCreate: e.canCreate, canCreate: e.canCreate,
canUpdate: e.canUpdate, canUpdate: e.canUpdate,

View File

@ -1,20 +1,12 @@
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { Collection, Link, UsersAndCollections } from "@prisma/client"; import { Collection, Link, UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission"; import getPermission from "@/lib/api/getPermission";
import removeFile from "@/lib/api/storage/removeFile"; import removeFile from "@/lib/api/storage/removeFile";
export default async function deleteLink( export default async function deleteLink(userId: number, linkId: number) {
link: LinkIncludingShortenedCollectionAndTags, if (!linkId) return { response: "Please choose a valid link.", status: 401 };
userId: number
) {
if (!link || !link.collectionId)
return { response: "Please choose a valid link.", status: 401 };
const collectionIsAccessible = (await getPermission( const collectionIsAccessible = (await getPermission({ userId, linkId })) as
userId,
link.collectionId
)) as
| (Collection & { | (Collection & {
members: UsersAndCollections[]; members: UsersAndCollections[];
}) })
@ -29,12 +21,16 @@ export default async function deleteLink(
const deleteLink: Link = await prisma.link.delete({ const deleteLink: Link = await prisma.link.delete({
where: { where: {
id: link.id, id: linkId,
}, },
}); });
removeFile({ filePath: `archives/${link.collectionId}/${link.id}.pdf` }); removeFile({
removeFile({ filePath: `archives/${link.collectionId}/${link.id}.png` }); filePath: `archives/${collectionIsAccessible?.id}/${linkId}.pdf`,
});
removeFile({
filePath: `archives/${collectionIsAccessible?.id}/${linkId}.png`,
});
return { response: deleteLink, status: 200 }; return { response: deleteLink, status: 200 };
} }

View File

@ -5,40 +5,32 @@ import getPermission from "@/lib/api/getPermission";
import moveFile from "@/lib/api/storage/moveFile"; import moveFile from "@/lib/api/storage/moveFile";
export default async function updateLink( export default async function updateLink(
link: LinkIncludingShortenedCollectionAndTags, userId: number,
userId: number linkId: number,
data: LinkIncludingShortenedCollectionAndTags
) { ) {
console.log(link); if (!data || !data.collection.id)
if (!link || !link.collection.id)
return { return {
response: "Please choose a valid link and collection.", response: "Please choose a valid link and collection.",
status: 401, status: 401,
}; };
const targetLink = (await getPermission( const collectionIsAccessible = (await getPermission({ userId, linkId })) as
userId, | (Collection & {
link.collection.id,
link.id
)) as
| (Link & {
collection: Collection & {
members: UsersAndCollections[]; members: UsersAndCollections[];
};
}) })
| null; | null;
const memberHasAccess = targetLink?.collection.members.some( const memberHasAccess = collectionIsAccessible?.members.some(
(e: UsersAndCollections) => e.userId === userId && e.canUpdate (e: UsersAndCollections) => e.userId === userId && e.canUpdate
); );
const isCollectionOwner = const isCollectionOwner =
targetLink?.collection.ownerId === link.collection.ownerId && collectionIsAccessible?.ownerId === data.collection.ownerId &&
link.collection.ownerId === userId; data.collection.ownerId === userId;
const unauthorizedSwitchCollection = const unauthorizedSwitchCollection =
!isCollectionOwner && targetLink?.collection.id !== link.collection.id; !isCollectionOwner && collectionIsAccessible?.id !== data.collection.id;
console.log(isCollectionOwner);
// Makes sure collection members (non-owners) cannot move a link to/from a collection. // Makes sure collection members (non-owners) cannot move a link to/from a collection.
if (unauthorizedSwitchCollection) if (unauthorizedSwitchCollection)
@ -46,7 +38,7 @@ export default async function updateLink(
response: "You can't move a link to/from a collection you don't own.", response: "You can't move a link to/from a collection you don't own.",
status: 401, status: 401,
}; };
else if (targetLink?.collection.ownerId !== userId && !memberHasAccess) else if (collectionIsAccessible?.ownerId !== userId && !memberHasAccess)
return { return {
response: "Collection is not accessible.", response: "Collection is not accessible.",
status: 401, status: 401,
@ -54,37 +46,37 @@ export default async function updateLink(
else { else {
const updatedLink = await prisma.link.update({ const updatedLink = await prisma.link.update({
where: { where: {
id: link.id, id: linkId,
}, },
data: { data: {
name: link.name, name: data.name,
description: link.description, description: data.description,
collection: { collection: {
connect: { connect: {
id: link.collection.id, id: data.collection.id,
}, },
}, },
tags: { tags: {
set: [], set: [],
connectOrCreate: link.tags.map((tag) => ({ connectOrCreate: data.tags.map((tag) => ({
where: { where: {
name_ownerId: { name_ownerId: {
name: tag.name, name: tag.name,
ownerId: link.collection.ownerId, ownerId: data.collection.ownerId,
}, },
}, },
create: { create: {
name: tag.name, name: tag.name,
owner: { owner: {
connect: { connect: {
id: link.collection.ownerId, id: data.collection.ownerId,
}, },
}, },
}, },
})), })),
}, },
pinnedBy: pinnedBy:
link?.pinnedBy && link.pinnedBy[0] data?.pinnedBy && data.pinnedBy[0]
? { connect: { id: userId } } ? { connect: { id: userId } }
: { disconnect: { id: userId } }, : { disconnect: { id: userId } },
}, },
@ -100,15 +92,15 @@ export default async function updateLink(
}, },
}); });
if (targetLink?.collection.id !== link.collection.id) { if (collectionIsAccessible?.id !== data.collection.id) {
await moveFile( await moveFile(
`archives/${targetLink?.collection.id}/${link.id}.pdf`, `archives/${collectionIsAccessible?.id}/${linkId}.pdf`,
`archives/${link.collection.id}/${link.id}.pdf` `archives/${data.collection.id}/${linkId}.pdf`
); );
await moveFile( await moveFile(
`archives/${targetLink?.collection.id}/${link.id}.png`, `archives/${collectionIsAccessible?.id}/${linkId}.png`,
`archives/${link.collection.id}/${link.id}.png` `archives/${data.collection.id}/${linkId}.png`
); );
} }

View File

@ -27,10 +27,10 @@ export default async function postLink(
link.collection.name = link.collection.name.trim(); link.collection.name = link.collection.name.trim();
if (link.collection.id) { if (link.collection.id) {
const collectionIsAccessible = (await getPermission( const collectionIsAccessible = (await getPermission({
userId, userId,
link.collection.id collectionId: link.collection.id,
)) as })) as
| (Collection & { | (Collection & {
members: UsersAndCollections[]; members: UsersAndCollections[];
}) })

View File

@ -0,0 +1,47 @@
import { prisma } from "@/lib/api/db";
import { Tag } from "@prisma/client";
export default async function updateTag(
userId: number,
tagId: number,
data: Tag
) {
if (!tagId || !data.name)
return { response: "Please choose a valid name for the tag.", status: 401 };
const tagNameIsTaken = await prisma.tag.findFirst({
where: {
ownerId: userId,
name: data.name,
},
});
if (tagNameIsTaken)
return {
response: "Tag names should be unique.",
status: 400,
};
const targetTag = await prisma.tag.findUnique({
where: {
id: tagId,
},
});
if (targetTag?.ownerId !== userId)
return {
response: "Permission denied.",
status: 401,
};
const updatedTag = await prisma.tag.update({
where: {
id: tagId,
},
data: {
name: data.name,
},
});
return { response: updatedTag, status: 200 };
}

View File

@ -1,54 +0,0 @@
import { prisma } from "@/lib/api/db";
export default async function getUser({
params,
isSelf,
username,
}: {
params: {
lookupUsername?: string;
lookupId?: number;
};
isSelf: boolean;
username: string;
}) {
const user = await prisma.user.findUnique({
where: {
id: params.lookupId,
username: params.lookupUsername?.toLowerCase(),
},
include: {
whitelistedUsers: {
select: {
username: true
}
}
}
});
if (!user) return { response: "User not found.", status: 404 };
const whitelistedUsernames = user.whitelistedUsers?.map(usernames => usernames.username);
if (
!isSelf &&
user?.isPrivate &&
!whitelistedUsernames.includes(username.toLowerCase())
) {
return { response: "This profile is private.", status: 401 };
}
const { password, ...lessSensitiveInfo } = user;
const data = isSelf
? // If user is requesting its own data
{...lessSensitiveInfo, whitelistedUsers: whitelistedUsernames}
: {
// If user is requesting someone elses data
id: lessSensitiveInfo.id,
name: lessSensitiveInfo.name,
username: lessSensitiveInfo.username,
};
return { response: data || null, status: 200 };
}

View File

@ -16,7 +16,7 @@ interface User {
password: string; password: string;
} }
export default async function Index( export default async function postUser(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse<Data> res: NextApiResponse<Data>
) { ) {
@ -35,8 +35,16 @@ export default async function Index(
.status(400) .status(400)
.json({ response: "Please fill out all the fields." }); .json({ response: "Please fill out all the fields." });
const checkUsername = RegExp("^[a-z0-9_-]{3,31}$"); // Check email (if enabled)
const checkEmail =
/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
if (emailEnabled && !checkEmail.test(body.email?.toLowerCase() || ""))
return res.status(400).json({
response: "Please enter a valid email.",
});
// Check username (if email was disabled)
const checkUsername = RegExp("^[a-z0-9_-]{3,31}$");
if (!emailEnabled && !checkUsername.test(body.username?.toLowerCase() || "")) if (!emailEnabled && !checkUsername.test(body.username?.toLowerCase() || ""))
return res.status(400).json({ return res.status(400).json({
response: response:
@ -47,7 +55,6 @@ export default async function Index(
where: emailEnabled where: emailEnabled
? { ? {
email: body.email?.toLowerCase(), email: body.email?.toLowerCase(),
emailVerified: { not: null },
} }
: { : {
username: (body.username as string).toLowerCase(), username: (body.username as string).toLowerCase(),
@ -72,8 +79,8 @@ export default async function Index(
return res.status(201).json({ response: "User successfully created." }); return res.status(201).json({ response: "User successfully created." });
} else if (checkIfUserExists) { } else if (checkIfUserExists) {
return res return res.status(400).json({
.status(400) response: `${emailEnabled ? "Email" : "Username"} already exists.`,
.json({ response: "Username and/or Email already exists." }); });
} }
} }

View File

@ -0,0 +1,48 @@
import { prisma } from "@/lib/api/db";
export default async function getUser(
targetId: number | string,
isId: boolean,
requestingUsername?: string
) {
const user = await prisma.user.findUnique({
where: isId
? {
id: Number(targetId) as number,
}
: {
username: targetId as string,
},
include: {
whitelistedUsers: {
select: {
username: true,
},
},
},
});
if (!user)
return { response: "User not found or profile is private.", status: 404 };
const whitelistedUsernames = user.whitelistedUsers?.map(
(usernames) => usernames.username
);
if (
user?.isPrivate &&
(!requestingUsername ||
!whitelistedUsernames.includes(requestingUsername?.toLowerCase()))
) {
return { response: "User not found or profile is private.", status: 404 };
}
const { password, ...lessSensitiveInfo } = user;
const data = {
name: lessSensitiveInfo.name,
username: lessSensitiveInfo.username,
};
return { response: data, status: 200 };
}

View File

@ -0,0 +1,32 @@
import { prisma } from "@/lib/api/db";
export default async function getUser(userId: number) {
const user = await prisma.user.findUnique({
where: {
id: userId,
},
include: {
whitelistedUsers: {
select: {
username: true,
},
},
},
});
if (!user)
return { response: "User not found or profile is private.", status: 404 };
const whitelistedUsernames = user.whitelistedUsers?.map(
(usernames) => usernames.username
);
const { password, ...lessSensitiveInfo } = user;
const data = {
...lessSensitiveInfo,
whitelistedUsers: whitelistedUsernames,
};
return { response: data, status: 200 };
}

View File

@ -10,20 +10,20 @@ const emailEnabled =
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false; process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
export default async function updateUser( export default async function updateUser(
user: AccountSettings,
sessionUser: { sessionUser: {
id: number; id: number;
username: string; username: string;
email: string; email: string;
isSubscriber: boolean; isSubscriber: boolean;
} },
data: AccountSettings
) { ) {
if (emailEnabled && !user.email) if (emailEnabled && !data.email)
return { return {
response: "Email invalid.", response: "Email invalid.",
status: 400, status: 400,
}; };
else if (!user.username) else if (!data.username)
return { return {
response: "Username invalid.", response: "Username invalid.",
status: 400, status: 400,
@ -31,7 +31,7 @@ export default async function updateUser(
const checkUsername = RegExp("^[a-z0-9_-]{3,31}$"); const checkUsername = RegExp("^[a-z0-9_-]{3,31}$");
if (!checkUsername.test(user.username.toLowerCase())) if (!checkUsername.test(data.username.toLowerCase()))
return { return {
response: response:
"Username has to be between 3-30 characters, no spaces and special characters are allowed.", "Username has to be between 3-30 characters, no spaces and special characters are allowed.",
@ -44,15 +44,15 @@ export default async function updateUser(
OR: emailEnabled OR: emailEnabled
? [ ? [
{ {
username: user.username.toLowerCase(), username: data.username.toLowerCase(),
}, },
{ {
email: user.email?.toLowerCase(), email: data.email?.toLowerCase(),
}, },
] ]
: [ : [
{ {
username: user.username.toLowerCase(), username: data.username.toLowerCase(),
}, },
], ],
}, },
@ -66,10 +66,10 @@ export default async function updateUser(
// Avatar Settings // Avatar Settings
const profilePic = user.profilePic; const profilePic = data.profilePic;
if (profilePic.startsWith("data:image/jpeg;base64")) { if (profilePic.startsWith("data:image/jpeg;base64")) {
if (user.profilePic.length < 1572864) { if (data.profilePic.length < 1572864) {
try { try {
const base64Data = profilePic.replace(/^data:image\/jpeg;base64,/, ""); const base64Data = profilePic.replace(/^data:image\/jpeg;base64,/, "");
@ -97,22 +97,22 @@ export default async function updateUser(
// Other settings // Other settings
const saltRounds = 10; const saltRounds = 10;
const newHashedPassword = bcrypt.hashSync(user.newPassword || "", saltRounds); const newHashedPassword = bcrypt.hashSync(data.newPassword || "", saltRounds);
const updatedUser = await prisma.user.update({ const updatedUser = await prisma.user.update({
where: { where: {
id: sessionUser.id, id: sessionUser.id,
}, },
data: { data: {
name: user.name, name: data.name,
username: user.username.toLowerCase(), username: data.username.toLowerCase(),
email: user.email?.toLowerCase(), email: data.email?.toLowerCase(),
isPrivate: user.isPrivate, isPrivate: data.isPrivate,
archiveAsScreenshot: user.archiveAsScreenshot, archiveAsScreenshot: data.archiveAsScreenshot,
archiveAsPDF: user.archiveAsPDF, archiveAsPDF: data.archiveAsPDF,
archiveAsWaybackMachine: user.archiveAsWaybackMachine, archiveAsWaybackMachine: data.archiveAsWaybackMachine,
password: password:
user.newPassword && user.newPassword !== "" data.newPassword && data.newPassword !== ""
? newHashedPassword ? newHashedPassword
: undefined, : undefined,
}, },
@ -124,11 +124,11 @@ export default async function updateUser(
const { whitelistedUsers, password, ...userInfo } = updatedUser; const { whitelistedUsers, password, ...userInfo } = updatedUser;
// If user.whitelistedUsers is not provided, we will assume the whitelistedUsers should be removed // If user.whitelistedUsers is not provided, we will assume the whitelistedUsers should be removed
const newWhitelistedUsernames: string[] = user.whitelistedUsers || []; const newWhitelistedUsernames: string[] = data.whitelistedUsers || [];
// Get the current whitelisted usernames // Get the current whitelisted usernames
const currentWhitelistedUsernames: string[] = whitelistedUsers.map( const currentWhitelistedUsernames: string[] = whitelistedUsers.map(
(user) => user.username (data) => data.username
); );
// Find the usernames to be deleted (present in current but not in new) // Find the usernames to be deleted (present in current but not in new)
@ -164,17 +164,17 @@ export default async function updateUser(
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY; const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
if (STRIPE_SECRET_KEY && emailEnabled && sessionUser.email !== user.email) if (STRIPE_SECRET_KEY && emailEnabled && sessionUser.email !== data.email)
await updateCustomerEmail( await updateCustomerEmail(
STRIPE_SECRET_KEY, STRIPE_SECRET_KEY,
sessionUser.email, sessionUser.email,
user.email as string data.email as string
); );
const response: Omit<AccountSettings, "password"> = { const response: Omit<AccountSettings, "password"> = {
...userInfo, ...userInfo,
whitelistedUsers: newWhitelistedUsernames, whitelistedUsers: newWhitelistedUsernames,
profilePic: `/api/avatar/${userInfo.id}?${Date.now()}`, profilePic: `/api/v1/avatar/${userInfo.id}?${Date.now()}`,
}; };
return { response, status: 200 }; return { response, status: 200 };

View File

@ -1,24 +1,30 @@
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
export default async function getPermission( type Props = {
userId: number, userId: number;
collectionId: number, collectionId?: number;
linkId?: number linkId?: number;
) { };
export default async function getPermission({
userId,
collectionId,
linkId,
}: Props) {
if (linkId) { if (linkId) {
const link = await prisma.link.findUnique({ const check = await prisma.collection.findFirst({
where: { where: {
links: {
some: {
id: linkId, id: linkId,
}, },
include: { },
collection: { },
include: { members: true }, include: { members: true },
},
},
}); });
return link; return check;
} else { } else if (collectionId) {
const check = await prisma.collection.findFirst({ const check = await prisma.collection.findFirst({
where: { where: {
AND: { AND: {

View File

@ -22,9 +22,7 @@ const addMemberToCollection = async (
memberUsername.trim().toLowerCase() !== ownerUsername.toLowerCase() memberUsername.trim().toLowerCase() !== ownerUsername.toLowerCase()
) { ) {
// Lookup, get data/err, list ... // Lookup, get data/err, list ...
const user = await getPublicUserData({ const user = await getPublicUserData(memberUsername.trim().toLowerCase());
username: memberUsername.trim().toLowerCase(),
});
if (user.username) { if (user.username) {
setMember({ setMember({

View File

@ -17,7 +17,7 @@ const getPublicCollectionData = async (
const encodedData = encodeURIComponent(JSON.stringify(requestBody)); const encodedData = encodeURIComponent(JSON.stringify(requestBody));
const res = await fetch( const res = await fetch(
"/api/public/collections?body=" + encodeURIComponent(encodedData) "/api/v1/public/collections?body=" + encodeURIComponent(encodedData)
); );
const data = await res.json(); const data = await res.json();

View File

@ -1,17 +1,7 @@
import { toast } from "react-hot-toast"; import { toast } from "react-hot-toast";
export default async function getPublicUserData({ export default async function getPublicUserData(id: number | string) {
username, const response = await fetch(`/api/v1/users/${id}`);
id,
}: {
username?: string;
id?: number;
}) {
const response = await fetch(
`/api/users?id=${id}&${
username ? `username=${username?.toLowerCase()}` : undefined
}`
);
const data = await response.json(); const data = await response.json();

View File

@ -22,7 +22,7 @@ export default function App({
}, []); }, []);
return ( return (
<SessionProvider session={pageProps.session}> <SessionProvider session={pageProps.session} basePath="/api/v1/auth">
<Head> <Head>
<title>Linkwarden</title> <title>Linkwarden</title>
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />

View File

@ -1,39 +0,0 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import getUsers from "@/lib/api/controllers/users/getUsers";
import updateUser from "@/lib/api/controllers/users/updateUser";
export default async function users(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions);
if (!session?.user.id) {
return res.status(401).json({ response: "You must be logged in." });
} else if (session?.user?.isSubscriber === false)
res.status(401).json({
response:
"You are not a subscriber, feel free to reach out to us at support@linkwarden.app in case of any issues.",
});
const lookupUsername = (req.query.username as string) || undefined;
const lookupId = Number(req.query.id) || undefined;
const isSelf =
session.user.username === lookupUsername || session.user.id === lookupId
? true
: false;
if (req.method === "GET") {
const users = await getUsers({
params: {
lookupUsername,
lookupId,
},
isSelf,
username: session.user.username,
});
return res.status(users.status).json({ response: users.response });
} else if (req.method === "PUT") {
const updated = await updateUser(req.body, session.user);
return res.status(updated.status).json({ response: updated.response });
}
}

View File

@ -1,6 +1,6 @@
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next"; import { getServerSession } from "next-auth/next";
import { authOptions } from "pages/api/auth/[...nextauth]"; import { authOptions } from "@/pages/api/v1/auth/[...nextauth]";
import getPermission from "@/lib/api/getPermission"; import getPermission from "@/lib/api/getPermission";
import readFile from "@/lib/api/storage/readFile"; import readFile from "@/lib/api/storage/readFile";
@ -21,10 +21,10 @@ export default async function Index(req: NextApiRequest, res: NextApiResponse) {
"You are not a subscriber, feel free to reach out to us at support@linkwarden.app in case of any issues.", "You are not a subscriber, feel free to reach out to us at support@linkwarden.app in case of any issues.",
}); });
const collectionIsAccessible = await getPermission( const collectionIsAccessible = await getPermission({
session.user.id, userId: session.user.id,
Number(collectionId) collectionId: Number(collectionId),
); });
if (!collectionIsAccessible) if (!collectionIsAccessible)
return res return res

View File

@ -88,8 +88,7 @@ export const authOptions: AuthOptions = {
return session; return session;
}, },
// Using the `...rest` parameter to be able to narrow down the type based on `trigger` async jwt({ token, trigger, user }) {
async jwt({ token, trigger, session, user }) {
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY; const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
const NEXT_PUBLIC_TRIAL_PERIOD_DAYS = const NEXT_PUBLIC_TRIAL_PERIOD_DAYS =

View File

@ -1,6 +1,6 @@
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next"; import { getServerSession } from "next-auth/next";
import { authOptions } from "pages/api/auth/[...nextauth]"; import { authOptions } from "@/pages/api/v1/auth/[...nextauth]";
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import readFile from "@/lib/api/storage/readFile"; import readFile from "@/lib/api/storage/readFile";

View File

@ -0,0 +1,35 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/v1/auth/[...nextauth]";
import updateCollectionById from "@/lib/api/controllers/collections/collectionId/updateCollectionById";
import deleteCollectionById from "@/lib/api/controllers/collections/collectionId/deleteCollectionById";
export default async function collections(
req: NextApiRequest,
res: NextApiResponse
) {
const session = await getServerSession(req, res, authOptions);
if (!session?.user?.id) {
return res.status(401).json({ response: "You must be logged in." });
} else if (session?.user?.isSubscriber === false)
res.status(401).json({
response:
"You are not a subscriber, feel free to reach out to us at support@linkwarden.app in case of any issues.",
});
if (req.method === "PUT") {
const updated = await updateCollectionById(
session.user.id,
Number(req.query.id) as number,
req.body
);
return res.status(updated.status).json({ response: updated.response });
} else if (req.method === "DELETE") {
const deleted = await deleteCollectionById(
session.user.id,
Number(req.query.id) as number
);
return res.status(deleted.status).json({ response: deleted.response });
}
}

View File

@ -1,10 +1,8 @@
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next"; import { getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/auth/[...nextauth]"; import { authOptions } from "@/pages/api/v1/auth/[...nextauth]";
import getCollections from "@/lib/api/controllers/collections/getCollections"; import getCollections from "@/lib/api/controllers/collections/getCollections";
import postCollection from "@/lib/api/controllers/collections/postCollection"; import postCollection from "@/lib/api/controllers/collections/postCollection";
import updateCollection from "@/lib/api/controllers/collections/updateCollection";
import deleteCollection from "@/lib/api/controllers/collections/deleteCollection";
export default async function collections( export default async function collections(
req: NextApiRequest, req: NextApiRequest,
@ -30,11 +28,5 @@ export default async function collections(
return res return res
.status(newCollection.status) .status(newCollection.status)
.json({ response: newCollection.response }); .json({ response: newCollection.response });
} else if (req.method === "PUT") {
const updated = await updateCollection(req.body, session.user.id);
return res.status(updated.status).json({ response: updated.response });
} else if (req.method === "DELETE") {
const deleted = await deleteCollection(req.body, session.user.id);
return res.status(deleted.status).json({ response: deleted.response });
} }
} }

16
pages/api/v1/getToken.ts Normal file
View File

@ -0,0 +1,16 @@
// For future...
// import { getToken } from "next-auth/jwt";
// export default async (req, res) => {
// // If you don't have NEXTAUTH_SECRET set, you will have to pass your secret as `secret` to `getToken`
// console.log({ req });
// const token = await getToken({ req, raw: true });
// if (token) {
// // Signed in
// console.log("JSON Web Token", JSON.stringify(token, null, 2));
// } else {
// // Not Signed in
// res.status(401);
// }
// res.end();
// };

View File

@ -0,0 +1,33 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/v1/auth/[...nextauth]";
import deleteLinkById from "@/lib/api/controllers/links/linkId/deleteLinkById";
import updateLinkById from "@/lib/api/controllers/links/linkId/updateLinkById";
export default async function links(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions);
if (!session?.user?.id) {
return res.status(401).json({ response: "You must be logged in." });
} else if (session?.user?.isSubscriber === false)
res.status(401).json({
response:
"You are not a subscriber, feel free to reach out to us at support@linkwarden.app in case of any issues.",
});
if (req.method === "PUT") {
const updated = await updateLinkById(
session.user.id,
Number(req.query.id),
req.body
);
return res.status(updated.status).json({
response: updated.response,
});
} else if (req.method === "DELETE") {
const deleted = await deleteLinkById(session.user.id, Number(req.query.id));
return res.status(deleted.status).json({
response: deleted.response,
});
}
}

View File

@ -1,10 +1,8 @@
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next"; import { getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/auth/[...nextauth]"; import { authOptions } from "@/pages/api/v1/auth/[...nextauth]";
import getLinks from "@/lib/api/controllers/links/getLinks"; import getLinks from "@/lib/api/controllers/links/getLinks";
import postLink from "@/lib/api/controllers/links/postLink"; import postLink from "@/lib/api/controllers/links/postLink";
import deleteLink from "@/lib/api/controllers/links/deleteLink";
import updateLink from "@/lib/api/controllers/links/updateLink";
export default async function links(req: NextApiRequest, res: NextApiResponse) { export default async function links(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions); const session = await getServerSession(req, res, authOptions);
@ -25,15 +23,5 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
return res.status(newlink.status).json({ return res.status(newlink.status).json({
response: newlink.response, response: newlink.response,
}); });
} else if (req.method === "PUT") {
const updated = await updateLink(req.body, session.user.id);
return res.status(updated.status).json({
response: updated.response,
});
} else if (req.method === "DELETE") {
const deleted = await deleteLink(req.body, session.user.id);
return res.status(deleted.status).json({
response: deleted.response,
});
} }
} }

View File

@ -1,6 +1,6 @@
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next"; import { getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/auth/[...nextauth]"; import { authOptions } from "@/pages/api/v1/auth/[...nextauth]";
import exportData from "@/lib/api/controllers/migration/exportData"; import exportData from "@/lib/api/controllers/migration/exportData";
import importFromHTMLFile from "@/lib/api/controllers/migration/importFromHTMLFile"; import importFromHTMLFile from "@/lib/api/controllers/migration/importFromHTMLFile";
import importFromLinkwarden from "@/lib/api/controllers/migration/importFromLinkwarden"; import importFromLinkwarden from "@/lib/api/controllers/migration/importFromLinkwarden";

View File

@ -1,6 +1,6 @@
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next"; import { getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/auth/[...nextauth]"; import { authOptions } from "@/pages/api/v1/auth/[...nextauth]";
import paymentCheckout from "@/lib/api/paymentCheckout"; import paymentCheckout from "@/lib/api/paymentCheckout";
import { Plan } from "@/types/global"; import { Plan } from "@/types/global";

23
pages/api/v1/tags/[id].ts Normal file
View File

@ -0,0 +1,23 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/v1/auth/[...nextauth]";
import updateTag from "@/lib/api/controllers/tags/tagId/updeteTagById";
export default async function tags(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions);
if (!session?.user?.username) {
return res.status(401).json({ response: "You must be logged in." });
} else if (session?.user?.isSubscriber === false)
res.status(401).json({
response:
"You are not a subscriber, feel free to reach out to us at support@linkwarden.app in case of any issues.",
});
const tagId = Number(req.query.id);
if (req.method === "PUT") {
const tags = await updateTag(session.user.id, tagId, req.body);
return res.status(tags.status).json({ response: tags.response });
}
}

View File

@ -1,6 +1,6 @@
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next"; import { getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/auth/[...nextauth]"; import { authOptions } from "@/pages/api/v1/auth/[...nextauth]";
import getTags from "@/lib/api/controllers/tags/getTags"; import getTags from "@/lib/api/controllers/tags/getTags";
export default async function tags(req: NextApiRequest, res: NextApiResponse) { export default async function tags(req: NextApiRequest, res: NextApiResponse) {

View File

@ -0,0 +1,40 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/v1/auth/[...nextauth]";
import getUserById from "@/lib/api/controllers/users/userId/getUserById";
import getPublicUserById from "@/lib/api/controllers/users/userId/getPublicUserById";
import updateUserById from "@/lib/api/controllers/users/userId/updateUserById";
export default async function users(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions);
const userId = session?.user.id;
const username = session?.user.username;
const lookupId = req.query.id as string;
const isSelf =
userId === Number(lookupId) || username === lookupId ? true : false;
// Check if "lookupId" is the user "id" or their "username"
const isId = lookupId.split("").every((e) => Number.isInteger(parseInt(e)));
if (req.method === "GET" && !isSelf) {
const users = await getPublicUserById(lookupId, isId, username);
return res.status(users.status).json({ response: users.response });
}
if (!userId) {
return res.status(401).json({ response: "You must be logged in." });
} else if (session?.user?.isSubscriber === false)
res.status(401).json({
response:
"You are not a subscriber, feel free to reach out to us at support@linkwarden.app in case of any issues.",
});
if (req.method === "GET") {
const users = await getUserById(session.user.id);
return res.status(users.status).json({ response: users.response });
} else if (req.method === "PUT") {
const updated = await updateUserById(session.user, req.body);
return res.status(updated.status).json({ response: updated.response });
}
}

View File

@ -0,0 +1,9 @@
import type { NextApiRequest, NextApiResponse } from "next";
import postUser from "@/lib/api/controllers/users/postUser";
export default async function users(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "POST") {
const response = await postUser(req, res);
return response;
}
}

View File

@ -104,7 +104,7 @@ export default function Index() {
return ( return (
<ProfilePhoto <ProfilePhoto
key={i} key={i}
src={`/api/avatar/${e.userId}?${Date.now()}`} src={`/api/v1/avatar/${e.userId}?${Date.now()}`}
className="-mr-3 border-[3px]" className="-mr-3 border-[3px]"
/> />
); );

View File

@ -59,7 +59,7 @@ export default function Register() {
const load = toast.loading("Creating Account..."); const load = toast.loading("Creating Account...");
const response = await fetch("/api/auth/register", { const response = await fetch("/api/v1/users", {
body: JSON.stringify(request), body: JSON.stringify(request),
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",

View File

@ -128,7 +128,7 @@ export default function Account() {
data: request, data: request,
}; };
const response = await fetch("/api/migration", { const response = await fetch("/api/v1/migration", {
method: "POST", method: "POST",
body: JSON.stringify(body), body: JSON.stringify(body),
}); });
@ -333,7 +333,7 @@ export default function Account() {
<p className="text-sm text-black dark:text-white mb-2"> <p className="text-sm text-black dark:text-white mb-2">
Download your data instantly. Download your data instantly.
</p> </p>
<Link className="w-fit" href="/api/migration"> <Link className="w-fit" href="/api/v1/migration">
<div className="border w-fit border-slate-200 dark:border-neutral-700 rounded-md bg-white dark:bg-neutral-800 px-2 text-center select-none cursor-pointer duration-100 hover:border-sky-300 hover:dark:border-sky-600"> <div className="border w-fit border-slate-200 dark:border-neutral-700 rounded-md bg-white dark:bg-neutral-800 px-2 text-center select-none cursor-pointer duration-100 hover:border-sky-300 hover:dark:border-sky-600">
Export Data Export Data
</div> </div>

View File

@ -20,7 +20,7 @@ export default function Subscribe() {
const redirectionToast = toast.loading("Redirecting to Stripe..."); const redirectionToast = toast.loading("Redirecting to Stripe...");
const res = await fetch("/api/payment?plan=" + plan); const res = await fetch("/api/v1/payment?plan=" + plan);
const data = await res.json(); const data = await res.json();
router.push(data.response); router.push(data.response);

View File

@ -1,25 +1,38 @@
import LinkCard from "@/components/LinkCard"; import LinkCard from "@/components/LinkCard";
import useLinkStore from "@/store/links"; import useLinkStore from "@/store/links";
import { faHashtag, faSort } from "@fortawesome/free-solid-svg-icons"; import {
faCheck,
faEllipsis,
faHashtag,
faSort,
faXmark,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useEffect, useState } from "react"; import { FormEvent, useEffect, useState } from "react";
import MainLayout from "@/layouts/MainLayout"; import MainLayout from "@/layouts/MainLayout";
import { Tag } from "@prisma/client"; import { Tag } from "@prisma/client";
import useTagStore from "@/store/tags"; import useTagStore from "@/store/tags";
import SortDropdown from "@/components/SortDropdown"; import SortDropdown from "@/components/SortDropdown";
import { Sort } from "@/types/global"; import { Sort } from "@/types/global";
import useLinks from "@/hooks/useLinks"; import useLinks from "@/hooks/useLinks";
import Dropdown from "@/components/Dropdown";
import { toast } from "react-hot-toast";
export default function Index() { export default function Index() {
const router = useRouter(); const router = useRouter();
const { links } = useLinkStore(); const { links } = useLinkStore();
const { tags } = useTagStore(); const { tags, updateTag } = useTagStore();
const [sortDropdown, setSortDropdown] = useState(false); const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst); const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
const [expandDropdown, setExpandDropdown] = useState(false);
const [renameTag, setRenameTag] = useState(false);
const [newTagName, setNewTagName] = useState<string>();
const [activeTag, setActiveTag] = useState<Tag>(); const [activeTag, setActiveTag] = useState<Tag>();
useLinks({ tagId: Number(router.query.id), sort: sortBy }); useLinks({ tagId: Number(router.query.id), sort: sortBy });
@ -28,19 +41,130 @@ export default function Index() {
setActiveTag(tags.find((e) => e.id === Number(router.query.id))); setActiveTag(tags.find((e) => e.id === Number(router.query.id)));
}, [router, tags]); }, [router, tags]);
useEffect(() => {
setNewTagName(activeTag?.name);
}, [activeTag]);
const [submitLoader, setSubmitLoader] = useState(false);
const cancelUpdateTag = async () => {
setNewTagName(activeTag?.name);
setRenameTag(false);
};
const submit = async (e?: FormEvent) => {
e?.preventDefault();
if (activeTag?.name === newTagName) return setRenameTag(false);
else if (newTagName === "") {
return cancelUpdateTag();
}
setSubmitLoader(true);
const load = toast.loading("Applying...");
let response;
if (activeTag && newTagName)
response = await updateTag({
...activeTag,
name: newTagName,
});
toast.dismiss(load);
if (response?.ok) {
toast.success("Tag Renamed!");
} else toast.error(response?.data as string);
setSubmitLoader(false);
setRenameTag(false);
};
return ( return (
<MainLayout> <MainLayout>
<div className="p-5 flex flex-col gap-5 w-full"> <div className="p-5 flex flex-col gap-5 w-full">
<div className="flex gap-3 items-center justify-between"> <div className="flex gap-3 items-center justify-between">
<div className="flex gap-3 items-center"> <div className="flex gap-3 items-center">
<div className="flex gap-2"> <div className="flex gap-2 items-end">
<FontAwesomeIcon <FontAwesomeIcon
icon={faHashtag} icon={faHashtag}
className="sm:w-8 sm:h-8 w-6 h-6 mt-2 text-sky-500 dark:text-sky-500" className="sm:w-8 sm:h-8 w-6 h-6 mt-2 text-sky-500 dark:text-sky-500"
/> />
{renameTag ? (
<>
<form onSubmit={submit} className="flex items-end gap-2">
<input
type="text"
autoFocus
className="sm:text-4xl text-3xl capitalize text-black dark:text-white bg-transparent h-10 w-3/4 outline-none border-b border-b-sky-100 dark:border-b-neutral-700"
value={newTagName}
onChange={(e) => setNewTagName(e.target.value)}
/>
<div
onClick={() => submit()}
id="expand-dropdown"
className="inline-flex rounded-md cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-1"
>
<FontAwesomeIcon
icon={faCheck}
id="expand-dropdown"
className="w-5 h-5 text-gray-500 dark:text-gray-300"
/>
</div>
<div
onClick={() => cancelUpdateTag()}
id="expand-dropdown"
className="inline-flex rounded-md cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-1"
>
<FontAwesomeIcon
icon={faXmark}
id="expand-dropdown"
className="w-5 h-5 text-gray-500 dark:text-gray-300"
/>
</div>
</form>
</>
) : (
<>
<p className="sm:text-4xl text-3xl capitalize text-black dark:text-white"> <p className="sm:text-4xl text-3xl capitalize text-black dark:text-white">
{activeTag?.name} {activeTag?.name}
</p> </p>
<div className="relative">
<div
onClick={() => setExpandDropdown(!expandDropdown)}
id="expand-dropdown"
className="inline-flex rounded-md cursor-pointer hover:bg-slate-200 hover:dark:bg-neutral-700 duration-100 p-1"
>
<FontAwesomeIcon
icon={faEllipsis}
id="expand-dropdown"
className="w-5 h-5 text-gray-500 dark:text-gray-300"
/>
</div>
{expandDropdown ? (
<Dropdown
items={[
{
name: "Rename Tag",
onClick: () => {
setRenameTag(true);
setExpandDropdown(false);
},
},
]}
onClickOutside={(e: Event) => {
const target = e.target as HTMLInputElement;
if (target.id !== "expand-dropdown")
setExpandDropdown(false);
}}
className="absolute top-8 left-0 w-36"
/>
) : null}
</div>
</>
)}
</div> </div>
</div> </div>

View File

@ -15,16 +15,16 @@ type AccountStore = {
const useAccountStore = create<AccountStore>()((set) => ({ const useAccountStore = create<AccountStore>()((set) => ({
account: {} as AccountSettings, account: {} as AccountSettings,
setAccount: async (id) => { setAccount: async (id) => {
const response = await fetch(`/api/users?id=${id}`); const response = await fetch(`/api/v1/users/${id}`);
const data = await response.json(); const data = await response.json();
const profilePic = `/api/avatar/${data.response.id}?${Date.now()}`; const profilePic = `/api/v1/avatar/${data.response.id}?${Date.now()}`;
if (response.ok) set({ account: { ...data.response, profilePic } }); if (response.ok) set({ account: { ...data.response, profilePic } });
}, },
updateAccount: async (user) => { updateAccount: async (user) => {
const response = await fetch("/api/users", { const response = await fetch(`/api/v1/users/${user.id}`, {
method: "PUT", method: "PUT",
body: JSON.stringify(user), body: JSON.stringify(user),
headers: { headers: {

View File

@ -22,14 +22,14 @@ type CollectionStore = {
const useCollectionStore = create<CollectionStore>()((set) => ({ const useCollectionStore = create<CollectionStore>()((set) => ({
collections: [], collections: [],
setCollections: async () => { setCollections: async () => {
const response = await fetch("/api/collections"); const response = await fetch("/api/v1/collections");
const data = await response.json(); const data = await response.json();
if (response.ok) set({ collections: data.response }); if (response.ok) set({ collections: data.response });
}, },
addCollection: async (body) => { addCollection: async (body) => {
const response = await fetch("/api/collections", { const response = await fetch("/api/v1/collections", {
body: JSON.stringify(body), body: JSON.stringify(body),
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -47,7 +47,7 @@ const useCollectionStore = create<CollectionStore>()((set) => ({
return { ok: response.ok, data: data.response }; return { ok: response.ok, data: data.response };
}, },
updateCollection: async (collection) => { updateCollection: async (collection) => {
const response = await fetch("/api/collections", { const response = await fetch(`/api/v1/collections/${collection.id}`, {
body: JSON.stringify(collection), body: JSON.stringify(collection),
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -66,9 +66,8 @@ const useCollectionStore = create<CollectionStore>()((set) => ({
return { ok: response.ok, data: data.response }; return { ok: response.ok, data: data.response };
}, },
removeCollection: async (id) => { removeCollection: async (collectionId) => {
const response = await fetch("/api/collections", { const response = await fetch(`/api/v1/collections/${collectionId}`, {
body: JSON.stringify({ id }),
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
@ -79,7 +78,7 @@ const useCollectionStore = create<CollectionStore>()((set) => ({
if (response.ok) { if (response.ok) {
set((state) => ({ set((state) => ({
collections: state.collections.filter((e) => e.id !== id), collections: state.collections.filter((e) => e.id !== collectionId),
})); }));
useTagStore.getState().setTags(); useTagStore.getState().setTags();
} }

View File

@ -20,9 +20,7 @@ type LinkStore = {
updateLink: ( updateLink: (
link: LinkIncludingShortenedCollectionAndTags link: LinkIncludingShortenedCollectionAndTags
) => Promise<ResponseObject>; ) => Promise<ResponseObject>;
removeLink: ( removeLink: (linkId: number) => Promise<ResponseObject>;
link: LinkIncludingShortenedCollectionAndTags
) => Promise<ResponseObject>;
resetLinks: () => void; resetLinks: () => void;
}; };
@ -38,7 +36,7 @@ const useLinkStore = create<LinkStore>()((set) => ({
})); }));
}, },
addLink: async (body) => { addLink: async (body) => {
const response = await fetch("/api/links", { const response = await fetch("/api/v1/links", {
body: JSON.stringify(body), body: JSON.stringify(body),
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -59,7 +57,7 @@ const useLinkStore = create<LinkStore>()((set) => ({
return { ok: response.ok, data: data.response }; return { ok: response.ok, data: data.response };
}, },
updateLink: async (link) => { updateLink: async (link) => {
const response = await fetch("/api/links", { const response = await fetch(`/api/v1/links/${link.id}`, {
body: JSON.stringify(link), body: JSON.stringify(link),
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -81,9 +79,8 @@ const useLinkStore = create<LinkStore>()((set) => ({
return { ok: response.ok, data: data.response }; return { ok: response.ok, data: data.response };
}, },
removeLink: async (link) => { removeLink: async (linkId) => {
const response = await fetch("/api/links", { const response = await fetch(`/api/v1/links/${linkId}`, {
body: JSON.stringify(link),
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
@ -94,7 +91,7 @@ const useLinkStore = create<LinkStore>()((set) => ({
if (response.ok) { if (response.ok) {
set((state) => ({ set((state) => ({
links: state.links.filter((e) => e.id !== link.id), links: state.links.filter((e) => e.id !== linkId),
})); }));
useTagStore.getState().setTags(); useTagStore.getState().setTags();
} }

View File

@ -1,20 +1,47 @@
import { create } from "zustand"; import { create } from "zustand";
import { Tag } from "@prisma/client"; import { Tag } from "@prisma/client";
type ResponseObject = {
ok: boolean;
data: object | string;
};
type TagStore = { type TagStore = {
tags: Tag[]; tags: Tag[];
setTags: () => void; setTags: () => void;
updateTag: (tag: Tag) => Promise<ResponseObject>;
}; };
const useTagStore = create<TagStore>()((set) => ({ const useTagStore = create<TagStore>()((set) => ({
tags: [], tags: [],
setTags: async () => { setTags: async () => {
const response = await fetch("/api/tags"); const response = await fetch("/api/v1/tags");
const data = await response.json(); const data = await response.json();
if (response.ok) set({ tags: data.response }); if (response.ok) set({ tags: data.response });
}, },
updateTag: async (tag) => {
const response = await fetch(`/api/v1/tags/${tag.id}`, {
body: JSON.stringify(tag),
headers: {
"Content-Type": "application/json",
},
method: "PUT",
});
const data = await response.json();
if (response.ok) {
set((state) => ({
tags: state.tags.map((e) =>
e.id === data.response.id ? data.response : e
),
}));
}
return { ok: response.ok, data: data.response };
},
})); }));
export default useTagStore; export default useTagStore;