Merge branch 'dev' into tags-in-public-collection

This commit is contained in:
Daniel
2024-11-02 17:56:43 -04:00
committed by GitHub
73 changed files with 2271 additions and 417 deletions
@@ -35,7 +35,7 @@ export default async function updateCollection(
return { response: "Collection is not accessible.", status: 401 };
if (data.parentId) {
if (data.parentId !== ("root" as any)) {
if (data.parentId !== "root") {
const findParentCollection = await prisma.collection.findUnique({
where: {
id: data.parentId,
@@ -58,6 +58,12 @@ export default async function updateCollection(
}
}
const uniqueMembers = data.members.filter(
(e, i, a) =>
a.findIndex((el) => el.userId === e.userId) === i &&
e.userId !== collectionIsAccessible.ownerId
);
const updatedCollection = await prisma.$transaction(async () => {
await prisma.usersAndCollections.deleteMany({
where: {
@@ -80,19 +86,19 @@ export default async function updateCollection(
isPublic: data.isPublic,
tagsArePublic: data.tagsArePublic,
parent:
data.parentId && data.parentId !== ("root" as any)
data.parentId && data.parentId !== "root"
? {
connect: {
id: data.parentId,
},
}
: data.parentId === ("root" as any)
: data.parentId === "root"
? {
disconnect: true,
}
: undefined,
members: {
create: data.members.map((e) => ({
create: uniqueMembers.map((e) => ({
user: { connect: { id: e.userId } },
canCreate: e.canCreate,
canUpdate: e.canUpdate,
@@ -44,11 +44,6 @@ export default async function postCollection(
const newCollection = await prisma.collection.create({
data: {
owner: {
connect: {
id: userId,
},
},
name: collection.name.trim(),
description: collection.description,
color: collection.color,
@@ -61,6 +56,16 @@ export default async function postCollection(
},
}
: undefined,
owner: {
connect: {
id: userId,
},
},
createdBy: {
connect: {
id: userId,
},
},
},
include: {
_count: {
+10 -11
View File
@@ -6,8 +6,7 @@ import {
PostLinkSchema,
PostLinkSchemaType,
} from "@/lib/shared/schemaValidation";
const MAX_LINKS_PER_USER = Number(process.env.MAX_LINKS_PER_USER) || 30000;
import { hasPassedLimit } from "../../verifyCapacity";
export default async function postLink(
body: PostLinkSchemaType,
@@ -59,19 +58,14 @@ export default async function postLink(
};
}
const numberOfLinksTheUserHas = await prisma.link.count({
where: {
collection: {
ownerId: linkCollection.ownerId,
},
},
});
const hasTooManyLinks = await hasPassedLimit(userId, 1);
if (numberOfLinksTheUserHas > MAX_LINKS_PER_USER)
if (hasTooManyLinks) {
return {
response: `Each collection owner can only have a maximum of ${MAX_LINKS_PER_USER} Links.`,
response: `Your subscription have reached the maximum number of links allowed.`,
status: 400,
};
}
const { title, headers } = await fetchTitleAndHeaders(link.url || "");
@@ -98,6 +92,11 @@ export default async function postLink(
name,
description: link.description,
type: linkType,
createdBy: {
connect: {
id: userId,
},
},
collection: {
connect: {
id: linkCollection.id,
@@ -2,8 +2,7 @@ import { prisma } from "@/lib/api/db";
import createFolder from "@/lib/api/storage/createFolder";
import { JSDOM } from "jsdom";
import { parse, Node, Element, TextNode } from "himalaya";
const MAX_LINKS_PER_USER = Number(process.env.MAX_LINKS_PER_USER) || 30000;
import { hasPassedLimit } from "../../verifyCapacity";
export default async function importFromHTMLFile(
userId: number,
@@ -20,19 +19,14 @@ export default async function importFromHTMLFile(
const bookmarks = document.querySelectorAll("A");
const totalImports = bookmarks.length;
const numberOfLinksTheUserHas = await prisma.link.count({
where: {
collection: {
ownerId: userId,
},
},
});
const hasTooManyLinks = await hasPassedLimit(userId, totalImports);
if (totalImports + numberOfLinksTheUserHas > MAX_LINKS_PER_USER)
if (hasTooManyLinks) {
return {
response: `Each collection owner can only have a maximum of ${MAX_LINKS_PER_USER} Links.`,
response: `Your subscription have reached the maximum number of links allowed.`,
status: 400,
};
}
const jsonData = parse(document.documentElement.outerHTML);
@@ -183,6 +177,11 @@ const createCollection = async (
id: userId,
},
},
createdBy: {
connect: {
id: userId,
},
},
},
});
@@ -222,28 +221,27 @@ const createLink = async (
url,
description,
collectionId,
createdById: userId,
tags:
tags && tags[0]
? {
connectOrCreate: tags.map((tag: string) => {
return (
{
where: {
name_ownerId: {
name: tag.trim(),
ownerId: userId,
},
},
create: {
return {
where: {
name_ownerId: {
name: tag.trim(),
owner: {
connect: {
id: userId,
},
ownerId: userId,
},
},
create: {
name: tag.trim(),
owner: {
connect: {
id: userId,
},
},
} || undefined
);
},
};
}),
}
: undefined,
@@ -1,8 +1,7 @@
import { prisma } from "@/lib/api/db";
import { Backup } from "@/types/global";
import createFolder from "@/lib/api/storage/createFolder";
const MAX_LINKS_PER_USER = Number(process.env.MAX_LINKS_PER_USER) || 30000;
import { hasPassedLimit } from "../../verifyCapacity";
export default async function importFromLinkwarden(
userId: number,
@@ -16,19 +15,14 @@ export default async function importFromLinkwarden(
totalImports += collection.links.length;
});
const numberOfLinksTheUserHas = await prisma.link.count({
where: {
collection: {
ownerId: userId,
},
},
});
const hasTooManyLinks = await hasPassedLimit(userId, totalImports);
if (totalImports + numberOfLinksTheUserHas > MAX_LINKS_PER_USER)
if (hasTooManyLinks) {
return {
response: `Each collection owner can only have a maximum of ${MAX_LINKS_PER_USER} Links.`,
response: `Your subscription have reached the maximum number of links allowed.`,
status: 400,
};
}
await prisma
.$transaction(
@@ -47,6 +41,11 @@ export default async function importFromLinkwarden(
name: e.name?.trim().slice(0, 254),
description: e.description?.trim().slice(0, 254),
color: e.color?.trim().slice(0, 50),
createdBy: {
connect: {
id: userId,
},
},
},
});
@@ -72,6 +71,11 @@ export default async function importFromLinkwarden(
id: newCollection.id,
},
},
createdBy: {
connect: {
id: userId,
},
},
// Import Tags
tags: {
connectOrCreate: link.tags.map((tag) => ({
@@ -1,7 +1,6 @@
import { prisma } from "@/lib/api/db";
import createFolder from "@/lib/api/storage/createFolder";
const MAX_LINKS_PER_USER = Number(process.env.MAX_LINKS_PER_USER) || 30000;
import { hasPassedLimit } from "../../verifyCapacity";
type WallabagBackup = {
is_archived: number;
@@ -36,19 +35,14 @@ export default async function importFromWallabag(
let totalImports = backup.length;
const numberOfLinksTheUserHas = await prisma.link.count({
where: {
collection: {
ownerId: userId,
},
},
});
const hasTooManyLinks = await hasPassedLimit(userId, totalImports);
if (totalImports + numberOfLinksTheUserHas > MAX_LINKS_PER_USER)
if (hasTooManyLinks) {
return {
response: `Each collection owner can only have a maximum of ${MAX_LINKS_PER_USER} Links.`,
response: `Your subscription have reached the maximum number of links allowed.`,
status: 400,
};
}
await prisma
.$transaction(
@@ -61,6 +55,11 @@ export default async function importFromWallabag(
},
},
name: "Imports",
createdBy: {
connect: {
id: userId,
},
},
},
});
@@ -89,6 +88,11 @@ export default async function importFromWallabag(
id: newCollection.id,
},
},
createdBy: {
connect: {
id: userId,
},
},
tags:
link.tags && link.tags[0]
? {
@@ -5,13 +5,20 @@ export default async function getPublicUser(
isId: boolean,
requestingId?: number
) {
const user = await prisma.user.findUnique({
const user = await prisma.user.findFirst({
where: isId
? {
id: Number(targetId) as number,
}
: {
username: targetId as string,
OR: [
{
username: targetId as string,
},
{
email: targetId as string,
},
],
},
include: {
whitelistedUsers: {
@@ -22,7 +29,7 @@ export default async function getPublicUser(
},
});
if (!user)
if (!user || !user.id)
return { response: "User not found or profile is private.", status: 404 };
const whitelistedUsernames = user.whitelistedUsers?.map(
@@ -31,7 +38,7 @@ export default async function getPublicUser(
const isInAPublicCollection = await prisma.collection.findFirst({
where: {
["OR"]: [
OR: [
{ ownerId: user.id },
{
members: {
@@ -73,6 +80,7 @@ export default async function getPublicUser(
id: lessSensitiveInfo.id,
name: lessSensitiveInfo.name,
username: lessSensitiveInfo.username,
email: lessSensitiveInfo.email,
image: lessSensitiveInfo.image,
archiveAsScreenshot: lessSensitiveInfo.archiveAsScreenshot,
archiveAsMonolith: lessSensitiveInfo.archiveAsMonolith,
+65 -15
View File
@@ -1,21 +1,71 @@
import { prisma } from "@/lib/api/db";
import { User } from "@prisma/client";
export default async function getUsers() {
// Get all users
const users = await prisma.user.findMany({
select: {
id: true,
username: true,
email: true,
emailVerified: true,
subscriptions: {
select: {
active: true,
export default async function getUsers(user: User) {
if (user.id === Number(process.env.NEXT_PUBLIC_ADMIN || 1)) {
const users = await prisma.user.findMany({
select: {
id: true,
username: true,
email: true,
emailVerified: true,
subscriptions: {
select: {
active: true,
},
},
createdAt: true,
},
createdAt: true,
},
});
});
return { response: users, status: 200 };
return {
response: users.sort((a: any, b: any) => a.id - b.id),
status: 200,
};
} else {
let subscriptionId = (
await prisma.subscription.findFirst({
where: {
userId: user.id,
},
select: {
id: true,
},
})
)?.id;
if (!subscriptionId)
return {
response: "Subscription not found.",
status: 404,
};
const users = await prisma.user.findMany({
where: {
OR: [
{
parentSubscriptionId: subscriptionId,
},
{
subscriptions: {
id: subscriptionId,
},
},
],
},
select: {
id: true,
name: true,
username: true,
email: true,
emailVerified: true,
createdAt: true,
},
});
return {
response: users.sort((a: any, b: any) => a.id - b.id),
status: 200,
};
}
}
+61 -48
View File
@@ -1,8 +1,9 @@
import { prisma } from "@/lib/api/db";
import type { NextApiRequest, NextApiResponse } from "next";
import bcrypt from "bcrypt";
import isServerAdmin from "../../isServerAdmin";
import { PostUserSchema } from "@/lib/shared/schemaValidation";
import isAuthenticatedRequest from "../../isAuthenticatedRequest";
import { Subscription, User } from "@prisma/client";
const emailEnabled =
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
@@ -17,7 +18,11 @@ export default async function postUser(
req: NextApiRequest,
res: NextApiResponse
): Promise<Data> {
let isAdmin = await isServerAdmin({ req });
const parentUser = await isAuthenticatedRequest({ req });
const isAdmin =
parentUser && parentUser.id === Number(process.env.NEXT_PUBLIC_ADMIN || 1);
const DISABLE_INVITES = process.env.DISABLE_INVITES === "true";
if (process.env.NEXT_PUBLIC_DISABLE_REGISTRATION === "true" && !isAdmin) {
return { response: "Registration is disabled.", status: 400 };
@@ -34,15 +39,28 @@ export default async function postUser(
};
}
const { name, email, password } = dataValidation.data;
const { name, email, password, invite } = dataValidation.data;
let { username } = dataValidation.data;
if (invite && (DISABLE_INVITES || !emailEnabled)) {
return { response: "You are not authorized to invite users.", status: 401 };
} else if (invite && !parentUser) {
return { response: "You must be logged in to invite users.", status: 401 };
}
const autoGeneratedUsername = "user" + Math.round(Math.random() * 1000000000);
if (!username) {
username = autoGeneratedUsername;
}
if (!emailEnabled && !password) {
return {
response: "Password is required.",
status: 400,
};
}
const checkIfUserExists = await prisma.user.findFirst({
where: {
OR: [
@@ -62,62 +80,57 @@ export default async function postUser(
const saltRounds = 10;
const hashedPassword = bcrypt.hashSync(password, saltRounds);
const hashedPassword = bcrypt.hashSync(password || "", saltRounds);
// Subscription dates
const currentPeriodStart = new Date();
const currentPeriodEnd = new Date();
currentPeriodEnd.setFullYear(currentPeriodEnd.getFullYear() + 1000); // end date is in 1000 years...
if (isAdmin) {
const user = await prisma.user.create({
data: {
name: name,
username: emailEnabled
? (username as string) || autoGeneratedUsername
: (username as string),
email: emailEnabled ? email : undefined,
password: hashedPassword,
emailVerified: new Date(),
subscriptions: stripeEnabled
const user = await prisma.user.create({
data: {
name: name,
username: emailEnabled ? username || autoGeneratedUsername : username,
email: emailEnabled ? email : undefined,
emailVerified: isAdmin ? new Date() : undefined,
password: password ? hashedPassword : undefined,
parentSubscription:
parentUser && invite
? {
connect: {
id: (parentUser.subscriptions as Subscription).id,
},
}
: undefined,
subscriptions:
stripeEnabled && isAdmin
? {
create: {
stripeSubscriptionId:
"fake_sub_" + Math.round(Math.random() * 10000000000000),
active: true,
currentPeriodStart,
currentPeriodEnd,
currentPeriodStart: new Date(),
currentPeriodEnd: new Date(
new Date().setFullYear(new Date().getFullYear() + 1000)
), // 1000 years from now
},
}
: undefined,
},
select: {
id: true,
username: true,
email: true,
emailVerified: true,
subscriptions: {
select: {
active: true,
},
select: isAdmin
? {
id: true,
username: true,
email: true,
emailVerified: true,
password: true,
subscriptions: {
select: {
active: true,
},
},
},
createdAt: true,
},
});
createdAt: true,
}
: undefined,
});
return { response: user, status: 201 };
} else {
await prisma.user.create({
data: {
name: name,
username: emailEnabled ? autoGeneratedUsername : (username as string),
email: emailEnabled ? email : undefined,
password: hashedPassword,
},
});
return { response: "User successfully created.", status: 201 };
}
const { password: pass, ...userWithoutPassword } = user as User;
return { response: userWithoutPassword, status: 201 };
} else {
return { response: "Email or Username already exists.", status: 400 };
}
@@ -4,15 +4,28 @@ import removeFolder from "@/lib/api/storage/removeFolder";
import Stripe from "stripe";
import { DeleteUserBody } from "@/types/global";
import removeFile from "@/lib/api/storage/removeFile";
import updateSeats from "@/lib/api/stripe/updateSeats";
export default async function deleteUserById(
userId: number,
body: DeleteUserBody,
isServerAdmin?: boolean
isServerAdmin: boolean,
queryId: number
) {
// First, we retrieve the user from the database
const user = await prisma.user.findUnique({
where: { id: userId },
include: {
subscriptions: {
include: {
user: true,
},
},
parentSubscription: {
include: {
user: true,
},
},
},
});
if (!user) {
@@ -23,21 +36,74 @@ export default async function deleteUserById(
}
if (!isServerAdmin) {
if (user.password) {
const isPasswordValid = bcrypt.compareSync(body.password, user.password);
if (queryId === userId) {
if (user.password) {
const isPasswordValid = bcrypt.compareSync(
body.password,
user.password
);
if (!isPasswordValid && !isServerAdmin) {
if (!isPasswordValid && !isServerAdmin) {
return {
response: "Invalid credentials.",
status: 401,
};
}
} else {
return {
response: "Invalid credentials.",
status: 401, // Unauthorized
response:
"User has no password. Please reset your password from the forgot password page.",
status: 401,
};
}
} else {
return {
response:
"User has no password. Please reset your password from the forgot password page.",
status: 401, // Unauthorized
};
if (user.parentSubscriptionId) {
console.log(userId, user.parentSubscriptionId);
return {
response: "Permission denied.",
status: 401,
};
} else {
if (!user.subscriptions) {
return {
response: "User has no subscription.",
status: 401,
};
}
const findChild = await prisma.user.findFirst({
where: { id: queryId, parentSubscriptionId: user.subscriptions?.id },
});
if (!findChild)
return {
response: "Permission denied.",
status: 401,
};
const removeUser = await prisma.user.update({
where: { id: findChild.id },
data: {
parentSubscription: {
disconnect: true,
},
},
select: {
id: true,
},
});
await updateSeats(
user.subscriptions.stripeSubscriptionId,
user.subscriptions.quantity - 1
);
return {
response: removeUser,
status: 200,
};
}
}
}
@@ -47,27 +113,27 @@ export default async function deleteUserById(
async (prisma) => {
// Delete Access Tokens
await prisma.accessToken.deleteMany({
where: { userId },
where: { userId: queryId },
});
// Delete whitelisted users
await prisma.whitelistedUser.deleteMany({
where: { userId },
where: { userId: queryId },
});
// Delete links
await prisma.link.deleteMany({
where: { collection: { ownerId: userId } },
where: { collection: { ownerId: queryId } },
});
// Delete tags
await prisma.tag.deleteMany({
where: { ownerId: userId },
where: { ownerId: queryId },
});
// Find collections that the user owns
const collections = await prisma.collection.findMany({
where: { ownerId: userId },
where: { ownerId: queryId },
});
for (const collection of collections) {
@@ -86,29 +152,29 @@ export default async function deleteUserById(
// Delete collections after cleaning up related data
await prisma.collection.deleteMany({
where: { ownerId: userId },
where: { ownerId: queryId },
});
// Delete subscription
if (process.env.STRIPE_SECRET_KEY)
await prisma.subscription
.delete({
where: { userId },
where: { userId: queryId },
})
.catch((err) => console.log(err));
await prisma.usersAndCollections.deleteMany({
where: {
OR: [{ userId: userId }, { collection: { ownerId: userId } }],
OR: [{ userId: queryId }, { collection: { ownerId: queryId } }],
},
});
// Delete user's avatar
await removeFile({ filePath: `uploads/avatar/${userId}.jpg` });
await removeFile({ filePath: `uploads/avatar/${queryId}.jpg` });
// Finally, delete the user
await prisma.user.delete({
where: { id: userId },
where: { id: queryId },
});
},
{ timeout: 20000 }
@@ -121,24 +187,36 @@ export default async function deleteUserById(
});
try {
const listByEmail = await stripe.customers.list({
email: user.email?.toLowerCase(),
expand: ["data.subscriptions"],
});
if (user.subscriptions?.id) {
const listByEmail = await stripe.customers.list({
email: user.email?.toLowerCase(),
expand: ["data.subscriptions"],
});
if (listByEmail.data[0].subscriptions?.data[0].id) {
const deleted = await stripe.subscriptions.cancel(
listByEmail.data[0].subscriptions?.data[0].id,
{
cancellation_details: {
comment: body.cancellation_details?.comment,
feedback: body.cancellation_details?.feedback,
},
}
if (listByEmail.data[0].subscriptions?.data[0].id) {
const deleted = await stripe.subscriptions.cancel(
listByEmail.data[0].subscriptions?.data[0].id,
{
cancellation_details: {
comment: body.cancellation_details?.comment,
feedback: body.cancellation_details?.feedback,
},
}
);
return {
response: deleted,
status: 200,
};
}
} else if (user.parentSubscription?.id) {
await updateSeats(
user.parentSubscription.stripeSubscriptionId,
user.parentSubscription.quantity - 1
);
return {
response: deleted,
response: "User account and all related data deleted successfully.",
status: 200,
};
}
@@ -12,6 +12,11 @@ export default async function getUserById(userId: number) {
},
},
subscriptions: true,
parentSubscription: {
include: {
user: true,
},
},
},
});
@@ -22,13 +27,21 @@ export default async function getUserById(userId: number) {
(usernames) => usernames.username
);
const { password, subscriptions, ...lessSensitiveInfo } = user;
const { password, subscriptions, parentSubscription, ...lessSensitiveInfo } =
user;
const data = {
...lessSensitiveInfo,
whitelistedUsers: whitelistedUsernames,
subscription: {
active: subscriptions?.active,
quantity: subscriptions?.quantity,
},
parentSubscription: {
active: parentSubscription?.active,
user: {
email: parentSubscription?.user.email,
},
},
};
@@ -101,7 +101,6 @@ export default async function updateUserById(
const user = await prisma.user.findUnique({
where: { id: userId },
select: { email: true, password: true, name: true },
});
if (user && user.email && data.email && data.email !== user.email) {
@@ -133,7 +132,7 @@ export default async function updateUserById(
sendChangeEmailVerificationRequest(
user.email,
data.email,
data.name?.trim() || user.name
data.name?.trim() || user.name || "Linkwarden User"
);
}
@@ -170,8 +169,20 @@ export default async function updateUserById(
// Other settings / Apply changes
const isInvited =
user?.name === null && user.parentSubscriptionId && !user.password;
if (isInvited && data.password === "")
return {
response: "Password is required.",
status: 400,
};
const saltRounds = 10;
const newHashedPassword = bcrypt.hashSync(data.newPassword || "", saltRounds);
const newHashedPassword = bcrypt.hashSync(
data.newPassword || data.password || "",
saltRounds
);
const updatedUser = await prisma.user.update({
where: {
@@ -198,18 +209,28 @@ export default async function updateUserById(
linksRouteTo: data.linksRouteTo,
preventDuplicateLinks: data.preventDuplicateLinks,
password:
data.newPassword && data.newPassword !== ""
isInvited || (data.newPassword && data.newPassword !== "")
? newHashedPassword
: undefined,
},
include: {
whitelistedUsers: true,
subscriptions: true,
parentSubscription: {
include: {
user: true,
},
},
},
});
const { whitelistedUsers, password, subscriptions, ...userInfo } =
updatedUser;
const {
whitelistedUsers,
password,
subscriptions,
parentSubscription,
...userInfo
} = updatedUser;
// If user.whitelistedUsers is not provided, we will assume the whitelistedUsers should be removed
const newWhitelistedUsernames: string[] = data.whitelistedUsers || [];
@@ -250,11 +271,20 @@ export default async function updateUserById(
});
}
const response: Omit<AccountSettings, "password"> = {
const response = {
...userInfo,
whitelistedUsers: newWhitelistedUsernames,
image: userInfo.image ? `${userInfo.image}?${Date.now()}` : "",
subscription: { active: subscriptions?.active },
subscription: {
active: subscriptions?.active,
quantity: subscriptions?.quantity,
},
parentSubscription: {
active: parentSubscription?.active,
user: {
email: parentSubscription?.user.email,
},
},
};
return { response, status: 200 };