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
-53
View File
@@ -1,53 +0,0 @@
import Stripe from "stripe";
const MONTHLY_PRICE_ID = process.env.MONTHLY_PRICE_ID;
const YEARLY_PRICE_ID = process.env.YEARLY_PRICE_ID;
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
export default async function checkSubscriptionByEmail(email: string) {
let active: boolean | undefined,
stripeSubscriptionId: string | undefined,
currentPeriodStart: number | undefined,
currentPeriodEnd: number | undefined;
if (!STRIPE_SECRET_KEY)
return {
active,
stripeSubscriptionId,
currentPeriodStart,
currentPeriodEnd,
};
const stripe = new Stripe(STRIPE_SECRET_KEY, {
apiVersion: "2022-11-15",
});
console.log("Request made to Stripe by:", email);
const listByEmail = await stripe.customers.list({
email: email.toLowerCase(),
expand: ["data.subscriptions"],
});
listByEmail.data.some((customer) => {
customer.subscriptions?.data.some((subscription) => {
subscription.current_period_end;
active =
subscription.items.data.some(
(e) =>
(e.price.id === MONTHLY_PRICE_ID && e.price.active === true) ||
(e.price.id === YEARLY_PRICE_ID && e.price.active === true)
) || false;
stripeSubscriptionId = subscription.id;
currentPeriodStart = subscription.current_period_start * 1000;
currentPeriodEnd = subscription.current_period_end * 1000;
});
});
return {
active: active || false,
stripeSubscriptionId,
currentPeriodStart,
currentPeriodEnd,
};
}
@@ -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 };
@@ -6,16 +6,16 @@ type Props = {
req: NextApiRequest;
};
export default async function isServerAdmin({ req }: Props): Promise<boolean> {
export default async function isAuthenticatedRequest({ req }: Props) {
const token = await getToken({ req });
const userId = token?.id;
if (!userId) {
return false;
return null;
}
if (token.exp < Date.now() / 1000) {
return false;
return null;
}
// check if token is revoked
@@ -27,18 +27,21 @@ export default async function isServerAdmin({ req }: Props): Promise<boolean> {
});
if (revoked) {
return false;
return null;
}
const findUser = await prisma.user.findFirst({
where: {
id: userId,
},
include: {
subscriptions: true,
},
});
if (findUser?.id === Number(process.env.NEXT_PUBLIC_ADMIN || 1)) {
return true;
} else {
return false;
if (findUser && !findUser?.subscriptions) {
return null;
}
return findUser;
}
+21 -1
View File
@@ -1,4 +1,6 @@
import Stripe from "stripe";
import verifySubscription from "./stripe/verifySubscription";
import { prisma } from "./db";
export default async function paymentCheckout(
stripeSecretKey: string,
@@ -9,6 +11,23 @@ export default async function paymentCheckout(
apiVersion: "2022-11-15",
});
const user = await prisma.user.findUnique({
where: {
email: email.toLowerCase(),
},
include: {
subscriptions: true,
parentSubscription: true,
},
});
const subscription = await verifySubscription(user);
if (subscription) {
// To prevent users from creating multiple subscriptions
return { response: "/dashboard", status: 200 };
}
const listByEmail = await stripe.customers.list({
email: email.toLowerCase(),
expand: ["data.subscriptions"],
@@ -18,6 +37,7 @@ export default async function paymentCheckout(
const NEXT_PUBLIC_TRIAL_PERIOD_DAYS =
process.env.NEXT_PUBLIC_TRIAL_PERIOD_DAYS;
const session = await stripe.checkout.sessions.create({
customer: isExistingCustomer ? isExistingCustomer : undefined,
line_items: [
@@ -28,7 +48,7 @@ export default async function paymentCheckout(
],
mode: "subscription",
customer_email: isExistingCustomer ? undefined : email.toLowerCase(),
success_url: `${process.env.BASE_URL}?session_id={CHECKOUT_SESSION_ID}`,
success_url: `${process.env.BASE_URL}/dashboard`,
cancel_url: `${process.env.BASE_URL}/login`,
automatic_tax: {
enabled: true,
+56
View File
@@ -0,0 +1,56 @@
import { readFileSync } from "fs";
import path from "path";
import Handlebars from "handlebars";
import transporter from "./transporter";
type Params = {
parentSubscriptionEmail: string;
identifier: string;
url: string;
from: string;
token: string;
};
export default async function sendInvitationRequest({
parentSubscriptionEmail,
identifier,
url,
from,
token,
}: Params) {
const emailsDir = path.resolve(process.cwd(), "templates");
const templateFile = readFileSync(
path.join(emailsDir, "acceptInvitation.html"),
"utf8"
);
const emailTemplate = Handlebars.compile(templateFile);
const { host } = new URL(url);
const result = await transporter.sendMail({
to: identifier,
from: {
name: "Linkwarden",
address: from as string,
},
subject: `You have been invited to join Linkwarden`,
text: text({ url, host }),
html: emailTemplate({
parentSubscriptionEmail,
identifier,
url: `${
process.env.NEXTAUTH_URL
}/callback/email?token=${token}&email=${encodeURIComponent(identifier)}`,
}),
});
const failed = result.rejected.concat(result.pending).filter(Boolean);
if (failed.length) {
throw new Error(`Email (${failed.join(", ")}) could not be sent`);
}
}
/** Email Text body (fallback for email clients that don't render HTML, e.g. feature phones) */
function text({ url, host }: { url: string; host: string }) {
return `Sign in to ${host}\n${url}\n\n`;
}
+2
View File
@@ -45,6 +45,7 @@ const setLinkCollection = async (link: PostLinkSchemaType, userId: number) => {
data: {
name: link.collection.name.trim(),
ownerId: userId,
createdById: userId,
},
});
@@ -78,6 +79,7 @@ const setLinkCollection = async (link: PostLinkSchemaType, userId: number) => {
name: "Unorganized",
ownerId: userId,
parentId: null,
createdById: userId,
},
});
}
@@ -0,0 +1,31 @@
import Stripe from "stripe";
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
export default async function checkSubscriptionByEmail(email: string) {
if (!STRIPE_SECRET_KEY) return null;
const stripe = new Stripe(STRIPE_SECRET_KEY, {
apiVersion: "2022-11-15",
});
console.log("Request made to Stripe by:", email);
const listByEmail = await stripe.customers.list({
email: email.toLowerCase(),
expand: ["data.subscriptions"],
});
if (listByEmail?.data[0]?.subscriptions?.data[0]) {
return {
active: (listByEmail.data[0].subscriptions?.data[0] as any).plan.active,
stripeSubscriptionId: listByEmail.data[0].subscriptions?.data[0].id,
currentPeriodStart:
listByEmail.data[0].subscriptions?.data[0].current_period_start * 1000,
currentPeriodEnd:
listByEmail.data[0].subscriptions?.data[0].current_period_end * 1000,
quantity: (listByEmail?.data[0]?.subscriptions?.data[0] as any).quantity,
};
} else {
return null;
}
}
+91
View File
@@ -0,0 +1,91 @@
import Stripe from "stripe";
import { prisma } from "../db";
type Data = {
id: string;
active: boolean;
quantity: number;
periodStart: number;
periodEnd: number;
};
export default async function handleSubscription({
id,
active,
quantity,
periodStart,
periodEnd,
}: Data) {
const subscription = await prisma.subscription.findUnique({
where: {
stripeSubscriptionId: id,
},
});
if (subscription) {
await prisma.subscription.update({
where: {
stripeSubscriptionId: id,
},
data: {
active,
quantity,
currentPeriodStart: new Date(periodStart * 1000),
currentPeriodEnd: new Date(periodEnd * 1000),
},
});
return;
} else {
if (!process.env.STRIPE_SECRET_KEY)
throw new Error("Missing Stripe secret key");
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: "2022-11-15",
});
const subscription = await stripe.subscriptions.retrieve(id);
const customerId = subscription.customer;
const customer = await stripe.customers.retrieve(customerId.toString());
const email = (customer as Stripe.Customer).email;
if (!email) throw new Error("Email not found");
const user = await prisma.user.findUnique({
where: {
email,
},
});
if (!user) throw new Error("User not found");
const userId = user.id;
await prisma.subscription
.upsert({
where: {
userId,
},
create: {
active,
stripeSubscriptionId: id,
quantity,
currentPeriodStart: new Date(periodStart * 1000),
currentPeriodEnd: new Date(periodEnd * 1000),
user: {
connect: {
id: userId,
},
},
},
update: {
active,
stripeSubscriptionId: id,
quantity,
currentPeriodStart: new Date(periodStart * 1000),
currentPeriodEnd: new Date(periodEnd * 1000),
},
})
.catch((err) => console.log(err));
}
}
+27
View File
@@ -0,0 +1,27 @@
import Stripe from "stripe";
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
const updateSeats = async (subscriptionId: string, seats: number) => {
if (!STRIPE_SECRET_KEY) {
return;
}
const stripe = new Stripe(STRIPE_SECRET_KEY, {
apiVersion: "2022-11-15",
});
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
const trialing = subscription.status === "trialing";
if (subscription) {
await stripe.subscriptions.update(subscriptionId, {
billing_cycle_anchor: trialing ? undefined : "now",
proration_behavior: trialing ? undefined : "create_prorations",
quantity: seats,
} as Stripe.SubscriptionUpdateParams);
}
};
export default updateSeats;
+70
View File
@@ -0,0 +1,70 @@
import { prisma } from "../db";
import { Subscription, User } from "@prisma/client";
import checkSubscriptionByEmail from "./checkSubscriptionByEmail";
interface UserIncludingSubscription extends User {
subscriptions: Subscription | null;
parentSubscription: Subscription | null;
}
export default async function verifySubscription(
user?: UserIncludingSubscription | null
) {
if (!user || (!user.subscriptions && !user.parentSubscription)) {
return null;
}
if (user.parentSubscription?.active) {
return user;
}
if (
!user.subscriptions?.active ||
new Date() > user.subscriptions.currentPeriodEnd
) {
const subscription = await checkSubscriptionByEmail(user.email as string);
if (
!subscription ||
!subscription.stripeSubscriptionId ||
!subscription.currentPeriodEnd ||
!subscription.currentPeriodStart ||
!subscription.quantity
) {
return null;
}
const {
active,
stripeSubscriptionId,
currentPeriodStart,
currentPeriodEnd,
quantity,
} = subscription;
await prisma.subscription
.upsert({
where: {
userId: user.id,
},
create: {
active,
stripeSubscriptionId,
currentPeriodStart: new Date(currentPeriodStart),
currentPeriodEnd: new Date(currentPeriodEnd),
quantity,
userId: user.id,
},
update: {
active,
stripeSubscriptionId,
currentPeriodStart: new Date(currentPeriodStart),
currentPeriodEnd: new Date(currentPeriodEnd),
quantity,
},
})
.catch((err) => console.log(err));
}
return user;
}
+2 -1
View File
@@ -1,6 +1,6 @@
import { prisma } from "./db";
import { User } from "@prisma/client";
import verifySubscription from "./verifySubscription";
import verifySubscription from "./stripe/verifySubscription";
import bcrypt from "bcrypt";
type Props = {
@@ -33,6 +33,7 @@ export default async function verifyByCredentials({
},
include: {
subscriptions: true,
parentSubscription: true,
},
});
+76
View File
@@ -0,0 +1,76 @@
import { prisma } from "./db";
const MAX_LINKS_PER_USER = Number(process.env.MAX_LINKS_PER_USER) || 30000;
const stripeEnabled = process.env.NEXT_PUBLIC_STRIPE === "true";
export const hasPassedLimit = async (
userId: number,
numberOfImports: number
) => {
if (!stripeEnabled) {
const totalLinks = await prisma.link.count({
where: {
createdBy: {
id: userId,
},
},
});
return MAX_LINKS_PER_USER - (numberOfImports + totalLinks) < 0;
}
const user = await prisma.user.findUnique({
where: { id: userId },
include: {
parentSubscription: true,
subscriptions: true,
},
});
if (!user) {
return true;
}
if (
user.parentSubscription ||
(user.subscriptions && user.subscriptions?.quantity > 1)
) {
const subscription = user.parentSubscription || user.subscriptions;
if (!subscription) {
return true;
}
// Calculate the total allowed links for the organization
const totalCapacity = subscription.quantity * MAX_LINKS_PER_USER;
const totalLinks = await prisma.link.count({
where: {
createdBy: {
OR: [
{
parentSubscriptionId: subscription.id || undefined,
},
{
subscriptions: {
id: subscription.id || undefined,
},
},
],
},
},
});
return totalCapacity - (numberOfImports + totalLinks) < 0;
} else {
const totalLinks = await prisma.link.count({
where: {
createdBy: {
id: userId,
},
},
});
return MAX_LINKS_PER_USER - (numberOfImports + totalLinks) < 0;
}
};
-73
View File
@@ -1,73 +0,0 @@
import { prisma } from "./db";
import { Subscription, User } from "@prisma/client";
import checkSubscriptionByEmail from "./checkSubscriptionByEmail";
interface UserIncludingSubscription extends User {
subscriptions: Subscription | null;
}
export default async function verifySubscription(
user?: UserIncludingSubscription
) {
if (!user) {
return null;
}
const subscription = user.subscriptions;
const currentDate = new Date();
if (!subscription?.active || currentDate > subscription.currentPeriodEnd) {
const {
active,
stripeSubscriptionId,
currentPeriodStart,
currentPeriodEnd,
} = await checkSubscriptionByEmail(user.email as string);
if (
active &&
stripeSubscriptionId &&
currentPeriodStart &&
currentPeriodEnd
) {
await prisma.subscription
.upsert({
where: {
userId: user.id,
},
create: {
active,
stripeSubscriptionId,
currentPeriodStart: new Date(currentPeriodStart),
currentPeriodEnd: new Date(currentPeriodEnd),
userId: user.id,
},
update: {
active,
stripeSubscriptionId,
currentPeriodStart: new Date(currentPeriodStart),
currentPeriodEnd: new Date(currentPeriodEnd),
},
})
.catch((err) => console.log(err));
} else if (!active) {
const subscription = await prisma.subscription.findFirst({
where: {
userId: user.id,
},
});
if (subscription)
await prisma.subscription.delete({
where: {
userId: user.id,
},
});
return null;
}
}
return user;
}
+2 -1
View File
@@ -1,7 +1,7 @@
import { NextApiRequest, NextApiResponse } from "next";
import { prisma } from "./db";
import { User } from "@prisma/client";
import verifySubscription from "./verifySubscription";
import verifySubscription from "./stripe/verifySubscription";
import verifyToken from "./verifyToken";
type Props = {
@@ -30,6 +30,7 @@ export default async function verifyUser({
},
include: {
subscriptions: true,
parentSubscription: true,
},
});
+18 -7
View File
@@ -2,29 +2,36 @@ import { CollectionIncludingMembersAndLinkCount, Member } from "@/types/global";
import getPublicUserData from "./getPublicUserData";
import { toast } from "react-hot-toast";
import { TFunction } from "i18next";
import { User } from "@prisma/client";
const addMemberToCollection = async (
ownerUsername: string,
memberUsername: string,
owner: User,
memberIdentifier: string,
collection: CollectionIncludingMembersAndLinkCount,
setMember: (newMember: Member) => null | undefined,
t: TFunction<"translation", undefined>
) => {
const checkIfMemberAlreadyExists = collection.members.find((e) => {
const username = (e.user.username || "").toLowerCase();
return username === memberUsername.toLowerCase();
const email = (e.user.email || "").toLowerCase();
return (
username === memberIdentifier.toLowerCase() ||
email === memberIdentifier.toLowerCase()
);
});
if (
// no duplicate members
!checkIfMemberAlreadyExists &&
// member can't be empty
memberUsername.trim() !== "" &&
memberIdentifier.trim() !== "" &&
// member can't be the owner
memberUsername.trim().toLowerCase() !== ownerUsername.toLowerCase()
memberIdentifier.trim().toLowerCase() !== owner.username?.toLowerCase() &&
memberIdentifier.trim().toLowerCase() !== owner.email?.toLowerCase()
) {
// Lookup, get data/err, list ...
const user = await getPublicUserData(memberUsername.trim().toLowerCase());
const user = await getPublicUserData(memberIdentifier.trim().toLowerCase());
if (user.username) {
setMember({
@@ -37,12 +44,16 @@ const addMemberToCollection = async (
id: user.id,
name: user.name,
username: user.username,
email: user.email,
image: user.image,
},
});
}
} else if (checkIfMemberAlreadyExists) toast.error(t("user_already_member"));
else if (memberUsername.trim().toLowerCase() === ownerUsername.toLowerCase())
else if (
memberIdentifier.trim().toLowerCase() === owner.username?.toLowerCase() ||
memberIdentifier.trim().toLowerCase() === owner.email?.toLowerCase()
)
toast.error(t("you_are_already_collection_owner"));
};
+5 -4
View File
@@ -33,8 +33,8 @@ export const PostUserSchema = () => {
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
return z.object({
name: z.string().trim().min(1).max(50),
password: z.string().min(8).max(2048),
name: z.string().trim().min(1).max(50).optional(),
password: z.string().min(8).max(2048).optional(),
email: emailEnabled
? z.string().trim().email().toLowerCase()
: z.string().optional(),
@@ -47,6 +47,7 @@ export const PostUserSchema = () => {
.min(3)
.max(50)
.regex(/^[a-z0-9_-]{3,50}$/),
invite: z.boolean().optional(),
});
};
@@ -66,7 +67,7 @@ export const UpdateUserSchema = () => {
.min(3)
.max(30)
.regex(/^[a-z0-9_-]{3,30}$/),
image: z.string().optional(),
image: z.string().nullish(),
password: z.string().min(8).max(2048).optional(),
newPassword: z.string().min(8).max(2048).optional(),
oldPassword: z.string().min(8).max(2048).optional(),
@@ -189,7 +190,7 @@ export const UpdateCollectionSchema = z.object({
isPublic: z.boolean().optional(),
icon: z.string().trim().max(50).nullish(),
iconWeight: z.string().trim().max(50).nullish(),
parentId: z.number().nullish(),
parentId: z.union([z.number(), z.literal("root")]).nullish(),
members: z.array(
z.object({
userId: z.number(),