code refactoring + many security/bug fixes

This commit is contained in:
daniel31x13
2023-11-06 08:25:57 -05:00
parent b5a28f68ad
commit c8edc3844b
48 changed files with 472 additions and 317 deletions
@@ -68,6 +68,11 @@ export default async function deleteUserById(
where: { ownerId: userId },
});
// Delete subscription
await prisma.subscription.delete({
where: { userId },
});
// Delete user's avatar
removeFile({ filePath: `uploads/avatar/${userId}.jpg` });
@@ -1,50 +0,0 @@
import { prisma } from "@/lib/api/db";
export default async function getPublicUserById(
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 = {
id: lessSensitiveInfo.id,
name: lessSensitiveInfo.name,
username: lessSensitiveInfo.username,
image: lessSensitiveInfo.image,
};
return { response: data, status: 200 };
}
@@ -11,6 +11,7 @@ export default async function getUserById(userId: number) {
username: true,
},
},
subscriptions: true,
},
});
@@ -21,11 +22,14 @@ export default async function getUserById(userId: number) {
(usernames) => usernames.username
);
const { password, ...lessSensitiveInfo } = user;
const { password, subscriptions, ...lessSensitiveInfo } = user;
const data = {
...lessSensitiveInfo,
whitelistedUsers: whitelistedUsernames,
subscription: {
active: subscriptions?.active,
},
};
return { response: data, status: 200 };
@@ -139,10 +139,12 @@ export default async function updateUserById(
},
include: {
whitelistedUsers: true,
subscriptions: true,
},
});
const { whitelistedUsers, password, ...userInfo } = updatedUser;
const { whitelistedUsers, password, subscriptions, ...userInfo } =
updatedUser;
// If user.whitelistedUsers is not provided, we will assume the whitelistedUsers should be removed
const newWhitelistedUsernames: string[] = data.whitelistedUsers || [];
@@ -196,6 +198,7 @@ export default async function updateUserById(
...userInfo,
whitelistedUsers: newWhitelistedUsernames,
image: userInfo.image ? `${userInfo.image}?${Date.now()}` : "",
subscription: { active: subscriptions?.active },
};
return { response, status: 200 };