Revert "undo commit"

This reverts commit 9103f67db5.
This commit is contained in:
daniel31x13
2024-11-03 03:27:52 -05:00
parent e37702aa14
commit dbd096ab76
176 changed files with 2362 additions and 9401 deletions
@@ -4,28 +4,15 @@ 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,
queryId: number
isServerAdmin?: boolean
) {
// 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) {
@@ -36,74 +23,24 @@ export default async function deleteUserById(
}
if (!isServerAdmin) {
if (queryId === userId) {
if (user.password) {
const isPasswordValid = bcrypt.compareSync(
body.password,
user.password
);
if (user.password) {
const isPasswordValid = bcrypt.compareSync(
body.password,
user.password as string
);
if (!isPasswordValid && !isServerAdmin) {
return {
response: "Invalid credentials.",
status: 401,
};
}
} else {
if (!isPasswordValid && !isServerAdmin) {
return {
response:
"User has no password. Please reset your password from the forgot password page.",
status: 401,
response: "Invalid credentials.",
status: 401, // Unauthorized
};
}
} else {
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,
};
}
return {
response:
"User has no password. Please reset your password from the forgot password page.",
status: 401, // Unauthorized
};
}
}
@@ -113,27 +50,27 @@ export default async function deleteUserById(
async (prisma) => {
// Delete Access Tokens
await prisma.accessToken.deleteMany({
where: { userId: queryId },
where: { userId },
});
// Delete whitelisted users
await prisma.whitelistedUser.deleteMany({
where: { userId: queryId },
where: { userId },
});
// Delete links
await prisma.link.deleteMany({
where: { collection: { ownerId: queryId } },
where: { collection: { ownerId: userId } },
});
// Delete tags
await prisma.tag.deleteMany({
where: { ownerId: queryId },
where: { ownerId: userId },
});
// Find collections that the user owns
const collections = await prisma.collection.findMany({
where: { ownerId: queryId },
where: { ownerId: userId },
});
for (const collection of collections) {
@@ -152,29 +89,29 @@ export default async function deleteUserById(
// Delete collections after cleaning up related data
await prisma.collection.deleteMany({
where: { ownerId: queryId },
where: { ownerId: userId },
});
// Delete subscription
if (process.env.STRIPE_SECRET_KEY)
await prisma.subscription
.delete({
where: { userId: queryId },
where: { userId },
})
.catch((err) => console.log(err));
await prisma.usersAndCollections.deleteMany({
where: {
OR: [{ userId: queryId }, { collection: { ownerId: queryId } }],
OR: [{ userId: userId }, { collection: { ownerId: userId } }],
},
});
// Delete user's avatar
await removeFile({ filePath: `uploads/avatar/${queryId}.jpg` });
await removeFile({ filePath: `uploads/avatar/${userId}.jpg` });
// Finally, delete the user
await prisma.user.delete({
where: { id: queryId },
where: { id: userId },
});
},
{ timeout: 20000 }
@@ -187,36 +124,24 @@ export default async function deleteUserById(
});
try {
if (user.subscriptions?.id) {
const listByEmail = await stripe.customers.list({
email: user.email?.toLowerCase(),
expand: ["data.subscriptions"],
});
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,
},
}
);
return {
response: deleted,
status: 200,
};
}
} else if (user.parentSubscription?.id) {
await updateSeats(
user.parentSubscription.stripeSubscriptionId,
user.parentSubscription.quantity - 1
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: "User account and all related data deleted successfully.",
response: deleted,
status: 200,
};
}
@@ -12,11 +12,6 @@ export default async function getUserById(userId: number) {
},
},
subscriptions: true,
parentSubscription: {
include: {
user: true,
},
},
},
});
@@ -27,21 +22,13 @@ export default async function getUserById(userId: number) {
(usernames) => usernames.username
);
const { password, subscriptions, parentSubscription, ...lessSensitiveInfo } =
user;
const { password, subscriptions, ...lessSensitiveInfo } = user;
const data = {
...lessSensitiveInfo,
whitelistedUsers: whitelistedUsernames,
subscription: {
active: subscriptions?.active,
quantity: subscriptions?.quantity,
},
parentSubscription: {
active: parentSubscription?.active,
user: {
email: parentSubscription?.user.email,
},
},
};
@@ -6,27 +6,42 @@ import createFile from "@/lib/api/storage/createFile";
import createFolder from "@/lib/api/storage/createFolder";
import sendChangeEmailVerificationRequest from "@/lib/api/sendChangeEmailVerificationRequest";
import { i18n } from "next-i18next.config";
import { UpdateUserSchema } from "@/lib/shared/schemaValidation";
const emailEnabled =
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
export default async function updateUserById(
userId: number,
body: AccountSettings
data: AccountSettings
) {
const dataValidation = UpdateUserSchema().safeParse(body);
if (!dataValidation.success) {
if (emailEnabled && !data.email)
return {
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
response: "Email invalid.",
status: 400,
};
else if (!data.username)
return {
response: "Username invalid.",
status: 400,
};
}
const data = dataValidation.data;
// Check email (if enabled)
const checkEmail =
/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
if (emailEnabled && !checkEmail.test(data.email?.toLowerCase() || ""))
return {
response: "Please enter a valid email.",
status: 400,
};
const checkUsername = RegExp("^[a-z0-9_-]{3,31}$");
if (!checkUsername.test(data.username.toLowerCase()))
return {
response:
"Username has to be between 3-30 characters, no spaces and special characters are allowed.",
status: 400,
};
const userIsTaken = await prisma.user.findFirst({
where: {
@@ -101,6 +116,7 @@ export default async function updateUserById(
const user = await prisma.user.findUnique({
where: { id: userId },
select: { email: true, password: true },
});
if (user && user.email && data.email && data.email !== user.email) {
@@ -132,7 +148,7 @@ export default async function updateUserById(
sendChangeEmailVerificationRequest(
user.email,
data.email,
data.name?.trim() || user.name || "Linkwarden User"
data.name.trim()
);
}
@@ -169,28 +185,16 @@ 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 || data.password || "",
saltRounds
);
const newHashedPassword = bcrypt.hashSync(data.newPassword || "", saltRounds);
const updatedUser = await prisma.user.update({
where: {
id: userId,
},
data: {
name: data.name,
username: data.username,
name: data.name.trim(),
username: data.username?.toLowerCase().trim(),
isPrivate: data.isPrivate,
image:
data.image && data.image.startsWith("http")
@@ -198,10 +202,10 @@ export default async function updateUserById(
: data.image
? `uploads/avatar/${userId}.jpg`
: "",
collectionOrder: data.collectionOrder?.filter(
collectionOrder: data.collectionOrder.filter(
(value, index, self) => self.indexOf(value) === index
),
locale: i18n.locales.includes(data.locale || "") ? data.locale : "en",
locale: i18n.locales.includes(data.locale) ? data.locale : "en",
archiveAsScreenshot: data.archiveAsScreenshot,
archiveAsMonolith: data.archiveAsMonolith,
archiveAsPDF: data.archiveAsPDF,
@@ -209,28 +213,18 @@ export default async function updateUserById(
linksRouteTo: data.linksRouteTo,
preventDuplicateLinks: data.preventDuplicateLinks,
password:
isInvited || (data.newPassword && data.newPassword !== "")
data.newPassword && data.newPassword !== ""
? newHashedPassword
: undefined,
},
include: {
whitelistedUsers: true,
subscriptions: true,
parentSubscription: {
include: {
user: true,
},
},
},
});
const {
whitelistedUsers,
password,
subscriptions,
parentSubscription,
...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 || [];
@@ -271,20 +265,11 @@ export default async function updateUserById(
});
}
const response = {
const response: Omit<AccountSettings, "password"> = {
...userInfo,
whitelistedUsers: newWhitelistedUsernames,
image: userInfo.image ? `${userInfo.image}?${Date.now()}` : "",
subscription: {
active: subscriptions?.active,
quantity: subscriptions?.quantity,
},
parentSubscription: {
active: parentSubscription?.active,
user: {
email: parentSubscription?.user.email,
},
},
subscription: { active: subscriptions?.active },
};
return { response, status: 200 };