refactored/cleaned up API + added support for renaming tags

This commit is contained in:
daniel31x13
2023-10-23 00:28:39 -04:00
parent 24cced9dba
commit ed24685aaf
48 changed files with 603 additions and 305 deletions
@@ -4,15 +4,16 @@ import { Collection, UsersAndCollections } from "@prisma/client";
import removeFolder from "@/lib/api/storage/removeFolder";
export default async function deleteCollection(
collection: { id: number },
userId: number
userId: number,
collectionId: number
) {
const collectionId = collection.id;
if (!collectionId)
return { response: "Please choose a valid collection.", status: 401 };
const collectionIsAccessible = (await getPermission(userId, collectionId)) as
const collectionIsAccessible = (await getPermission({
userId,
collectionId,
})) as
| (Collection & {
members: UsersAndCollections[];
})
@@ -4,16 +4,17 @@ import getPermission from "@/lib/api/getPermission";
import { Collection, UsersAndCollections } from "@prisma/client";
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 };
const collectionIsAccessible = (await getPermission(
const collectionIsAccessible = (await getPermission({
userId,
collection.id
)) as
collectionId,
})) as
| (Collection & {
members: UsersAndCollections[];
})
@@ -26,23 +27,23 @@ export default async function updateCollection(
await prisma.usersAndCollections.deleteMany({
where: {
collection: {
id: collection.id,
id: collectionId,
},
},
});
return await prisma.collection.update({
where: {
id: collection.id,
id: collectionId,
},
data: {
name: collection.name.trim(),
description: collection.description,
color: collection.color,
isPublic: collection.isPublic,
name: data.name.trim(),
description: data.description,
color: data.color,
isPublic: data.isPublic,
members: {
create: collection.members.map((e) => ({
create: data.members.map((e) => ({
user: { connect: { id: e.user.id || e.userId } },
canCreate: e.canCreate,
canUpdate: e.canUpdate,
@@ -1,20 +1,12 @@
import { prisma } from "@/lib/api/db";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { Collection, Link, UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission";
import removeFile from "@/lib/api/storage/removeFile";
export default async function deleteLink(
link: LinkIncludingShortenedCollectionAndTags,
userId: number
) {
if (!link || !link.collectionId)
return { response: "Please choose a valid link.", status: 401 };
export default async function deleteLink(userId: number, linkId: number) {
if (!linkId) return { response: "Please choose a valid link.", status: 401 };
const collectionIsAccessible = (await getPermission(
userId,
link.collectionId
)) as
const collectionIsAccessible = (await getPermission({ userId, linkId })) as
| (Collection & {
members: UsersAndCollections[];
})
@@ -29,12 +21,16 @@ export default async function deleteLink(
const deleteLink: Link = await prisma.link.delete({
where: {
id: link.id,
id: linkId,
},
});
removeFile({ filePath: `archives/${link.collectionId}/${link.id}.pdf` });
removeFile({ filePath: `archives/${link.collectionId}/${link.id}.png` });
removeFile({
filePath: `archives/${collectionIsAccessible?.id}/${linkId}.pdf`,
});
removeFile({
filePath: `archives/${collectionIsAccessible?.id}/${linkId}.png`,
});
return { response: deleteLink, status: 200 };
}
@@ -5,40 +5,32 @@ import getPermission from "@/lib/api/getPermission";
import moveFile from "@/lib/api/storage/moveFile";
export default async function updateLink(
link: LinkIncludingShortenedCollectionAndTags,
userId: number
userId: number,
linkId: number,
data: LinkIncludingShortenedCollectionAndTags
) {
console.log(link);
if (!link || !link.collection.id)
if (!data || !data.collection.id)
return {
response: "Please choose a valid link and collection.",
status: 401,
};
const targetLink = (await getPermission(
userId,
link.collection.id,
link.id
)) as
| (Link & {
collection: Collection & {
members: UsersAndCollections[];
};
const collectionIsAccessible = (await getPermission({ userId, linkId })) as
| (Collection & {
members: UsersAndCollections[];
})
| null;
const memberHasAccess = targetLink?.collection.members.some(
const memberHasAccess = collectionIsAccessible?.members.some(
(e: UsersAndCollections) => e.userId === userId && e.canUpdate
);
const isCollectionOwner =
targetLink?.collection.ownerId === link.collection.ownerId &&
link.collection.ownerId === userId;
collectionIsAccessible?.ownerId === data.collection.ownerId &&
data.collection.ownerId === userId;
const unauthorizedSwitchCollection =
!isCollectionOwner && targetLink?.collection.id !== link.collection.id;
console.log(isCollectionOwner);
!isCollectionOwner && collectionIsAccessible?.id !== data.collection.id;
// Makes sure collection members (non-owners) cannot move a link to/from a collection.
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.",
status: 401,
};
else if (targetLink?.collection.ownerId !== userId && !memberHasAccess)
else if (collectionIsAccessible?.ownerId !== userId && !memberHasAccess)
return {
response: "Collection is not accessible.",
status: 401,
@@ -54,37 +46,37 @@ export default async function updateLink(
else {
const updatedLink = await prisma.link.update({
where: {
id: link.id,
id: linkId,
},
data: {
name: link.name,
description: link.description,
name: data.name,
description: data.description,
collection: {
connect: {
id: link.collection.id,
id: data.collection.id,
},
},
tags: {
set: [],
connectOrCreate: link.tags.map((tag) => ({
connectOrCreate: data.tags.map((tag) => ({
where: {
name_ownerId: {
name: tag.name,
ownerId: link.collection.ownerId,
ownerId: data.collection.ownerId,
},
},
create: {
name: tag.name,
owner: {
connect: {
id: link.collection.ownerId,
id: data.collection.ownerId,
},
},
},
})),
},
pinnedBy:
link?.pinnedBy && link.pinnedBy[0]
data?.pinnedBy && data.pinnedBy[0]
? { connect: { 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(
`archives/${targetLink?.collection.id}/${link.id}.pdf`,
`archives/${link.collection.id}/${link.id}.pdf`
`archives/${collectionIsAccessible?.id}/${linkId}.pdf`,
`archives/${data.collection.id}/${linkId}.pdf`
);
await moveFile(
`archives/${targetLink?.collection.id}/${link.id}.png`,
`archives/${link.collection.id}/${link.id}.png`
`archives/${collectionIsAccessible?.id}/${linkId}.png`,
`archives/${data.collection.id}/${linkId}.png`
);
}
+3 -3
View File
@@ -27,10 +27,10 @@ export default async function postLink(
link.collection.name = link.collection.name.trim();
if (link.collection.id) {
const collectionIsAccessible = (await getPermission(
const collectionIsAccessible = (await getPermission({
userId,
link.collection.id
)) as
collectionId: link.collection.id,
})) as
| (Collection & {
members: UsersAndCollections[];
})
@@ -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 };
}
-54
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 };
}
+86
View File
@@ -0,0 +1,86 @@
import { prisma } from "@/lib/api/db";
import type { NextApiRequest, NextApiResponse } from "next";
import bcrypt from "bcrypt";
const emailEnabled =
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
interface Data {
response: string | object;
}
interface User {
name: string;
username?: string;
email?: string;
password: string;
}
export default async function postUser(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
if (process.env.NEXT_PUBLIC_DISABLE_REGISTRATION === "true") {
return res.status(400).json({ response: "Registration is disabled." });
}
const body: User = req.body;
const checkHasEmptyFields = emailEnabled
? !body.password || !body.name || !body.email
: !body.username || !body.password || !body.name;
if (checkHasEmptyFields)
return res
.status(400)
.json({ response: "Please fill out all the fields." });
// 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() || ""))
return res.status(400).json({
response:
"Username has to be between 3-30 characters, no spaces and special characters are allowed.",
});
const checkIfUserExists = await prisma.user.findFirst({
where: emailEnabled
? {
email: body.email?.toLowerCase(),
}
: {
username: (body.username as string).toLowerCase(),
},
});
if (!checkIfUserExists) {
const saltRounds = 10;
const hashedPassword = bcrypt.hashSync(body.password, saltRounds);
await prisma.user.create({
data: {
name: body.name,
username: emailEnabled
? undefined
: (body.username as string).toLowerCase(),
email: emailEnabled ? body.email?.toLowerCase() : undefined,
password: hashedPassword,
},
});
return res.status(201).json({ response: "User successfully created." });
} else if (checkIfUserExists) {
return res.status(400).json({
response: `${emailEnabled ? "Email" : "Username"} already exists.`,
});
}
}
@@ -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 };
}
@@ -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 };
}
@@ -10,20 +10,20 @@ const emailEnabled =
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
export default async function updateUser(
user: AccountSettings,
sessionUser: {
id: number;
username: string;
email: string;
isSubscriber: boolean;
}
},
data: AccountSettings
) {
if (emailEnabled && !user.email)
if (emailEnabled && !data.email)
return {
response: "Email invalid.",
status: 400,
};
else if (!user.username)
else if (!data.username)
return {
response: "Username invalid.",
status: 400,
@@ -31,7 +31,7 @@ export default async function updateUser(
const checkUsername = RegExp("^[a-z0-9_-]{3,31}$");
if (!checkUsername.test(user.username.toLowerCase()))
if (!checkUsername.test(data.username.toLowerCase()))
return {
response:
"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
? [
{
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
const profilePic = user.profilePic;
const profilePic = data.profilePic;
if (profilePic.startsWith("data:image/jpeg;base64")) {
if (user.profilePic.length < 1572864) {
if (data.profilePic.length < 1572864) {
try {
const base64Data = profilePic.replace(/^data:image\/jpeg;base64,/, "");
@@ -97,22 +97,22 @@ export default async function updateUser(
// Other settings
const saltRounds = 10;
const newHashedPassword = bcrypt.hashSync(user.newPassword || "", saltRounds);
const newHashedPassword = bcrypt.hashSync(data.newPassword || "", saltRounds);
const updatedUser = await prisma.user.update({
where: {
id: sessionUser.id,
},
data: {
name: user.name,
username: user.username.toLowerCase(),
email: user.email?.toLowerCase(),
isPrivate: user.isPrivate,
archiveAsScreenshot: user.archiveAsScreenshot,
archiveAsPDF: user.archiveAsPDF,
archiveAsWaybackMachine: user.archiveAsWaybackMachine,
name: data.name,
username: data.username.toLowerCase(),
email: data.email?.toLowerCase(),
isPrivate: data.isPrivate,
archiveAsScreenshot: data.archiveAsScreenshot,
archiveAsPDF: data.archiveAsPDF,
archiveAsWaybackMachine: data.archiveAsWaybackMachine,
password:
user.newPassword && user.newPassword !== ""
data.newPassword && data.newPassword !== ""
? newHashedPassword
: undefined,
},
@@ -124,11 +124,11 @@ export default async function updateUser(
const { whitelistedUsers, password, ...userInfo } = updatedUser;
// 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
const currentWhitelistedUsernames: string[] = whitelistedUsers.map(
(user) => user.username
(data) => data.username
);
// 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;
if (STRIPE_SECRET_KEY && emailEnabled && sessionUser.email !== user.email)
if (STRIPE_SECRET_KEY && emailEnabled && sessionUser.email !== data.email)
await updateCustomerEmail(
STRIPE_SECRET_KEY,
sessionUser.email,
user.email as string
data.email as string
);
const response: Omit<AccountSettings, "password"> = {
...userInfo,
whitelistedUsers: newWhitelistedUsernames,
profilePic: `/api/avatar/${userInfo.id}?${Date.now()}`,
profilePic: `/api/v1/avatar/${userInfo.id}?${Date.now()}`,
};
return { response, status: 200 };