code refactoring + many security/bug fixes
This commit is contained in:
@@ -1,31 +0,0 @@
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getToken } from "next-auth/jwt";
|
||||
import { prisma } from "./db";
|
||||
import { User } from "@prisma/client";
|
||||
|
||||
type Props = {
|
||||
req: NextApiRequest;
|
||||
res: NextApiResponse;
|
||||
};
|
||||
|
||||
export default async function authenticateUser({
|
||||
req,
|
||||
res,
|
||||
}: Props): Promise<User | null> {
|
||||
const token = await getToken({ req });
|
||||
const userId = token?.id;
|
||||
|
||||
if (!userId) {
|
||||
res.status(401).json({ message: "You must be logged in." });
|
||||
return null;
|
||||
} else if (process.env.STRIPE_SECRET_KEY && token.isSubscriber === false) {
|
||||
res.status(401).json({
|
||||
message:
|
||||
"You are not a subscriber, feel free to reach out to us at support@linkwarden.app if you think this is an issue.",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { id: userId } });
|
||||
return user;
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import Stripe from "stripe";
|
||||
|
||||
export default async function checkSubscription(
|
||||
stripeSecretKey: string,
|
||||
email: string
|
||||
) {
|
||||
const stripe = new Stripe(stripeSecretKey, {
|
||||
apiVersion: "2022-11-15",
|
||||
});
|
||||
|
||||
const listByEmail = await stripe.customers.list({
|
||||
email: email.toLowerCase(),
|
||||
expand: ["data.subscriptions"],
|
||||
});
|
||||
|
||||
let subscriptionCanceledAt: number | null | undefined;
|
||||
|
||||
const isSubscriber = listByEmail.data.some((customer, i) => {
|
||||
const hasValidSubscription = customer.subscriptions?.data.some(
|
||||
(subscription) => {
|
||||
const NEXT_PUBLIC_TRIAL_PERIOD_DAYS =
|
||||
process.env.NEXT_PUBLIC_TRIAL_PERIOD_DAYS;
|
||||
const secondsInTwoWeeks = NEXT_PUBLIC_TRIAL_PERIOD_DAYS
|
||||
? Number(NEXT_PUBLIC_TRIAL_PERIOD_DAYS) * 86400
|
||||
: 1209600;
|
||||
|
||||
subscriptionCanceledAt = subscription.canceled_at;
|
||||
|
||||
const isNotCanceledOrHasTime = !(
|
||||
subscription.canceled_at &&
|
||||
new Date() >
|
||||
new Date((subscription.canceled_at + secondsInTwoWeeks) * 1000)
|
||||
);
|
||||
|
||||
return subscription?.items?.data[0].plan && isNotCanceledOrHasTime;
|
||||
}
|
||||
);
|
||||
|
||||
return (
|
||||
customer.email?.toLowerCase() === email.toLowerCase() &&
|
||||
hasValidSubscription
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
isSubscriber,
|
||||
subscriptionCanceledAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
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)
|
||||
);
|
||||
stripeSubscriptionId = subscription.id;
|
||||
currentPeriodStart = subscription.current_period_start * 1000;
|
||||
currentPeriodEnd = subscription.current_period_end * 1000;
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
active,
|
||||
stripeSubscriptionId,
|
||||
currentPeriodStart,
|
||||
currentPeriodEnd,
|
||||
};
|
||||
}
|
||||
+18
-7
@@ -3,7 +3,7 @@ import { prisma } from "@/lib/api/db";
|
||||
export default async function getPublicUserById(
|
||||
targetId: number | string,
|
||||
isId: boolean,
|
||||
requestingUsername?: string
|
||||
requestingId?: number
|
||||
) {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: isId
|
||||
@@ -29,12 +29,23 @@ export default async function getPublicUserById(
|
||||
(usernames) => usernames.username
|
||||
);
|
||||
|
||||
if (
|
||||
user?.isPrivate &&
|
||||
(!requestingUsername ||
|
||||
!whitelistedUsernames.includes(requestingUsername?.toLowerCase()))
|
||||
) {
|
||||
return { response: "User not found or profile is private.", status: 404 };
|
||||
if (user?.isPrivate) {
|
||||
if (requestingId) {
|
||||
const requestingUsername = (
|
||||
await prisma.user.findUnique({ where: { id: requestingId } })
|
||||
)?.username;
|
||||
|
||||
if (
|
||||
!requestingUsername ||
|
||||
!whitelistedUsernames.includes(requestingUsername?.toLowerCase())
|
||||
) {
|
||||
return {
|
||||
response: "User not found or profile is private.",
|
||||
status: 404,
|
||||
};
|
||||
}
|
||||
} else
|
||||
return { response: "User not found or profile is private.", status: 404 };
|
||||
}
|
||||
|
||||
const { password, ...lessSensitiveInfo } = user;
|
||||
@@ -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` });
|
||||
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -14,12 +14,12 @@ export default async function paymentCheckout(
|
||||
expand: ["data.subscriptions"],
|
||||
});
|
||||
|
||||
const isExistingCostomer = listByEmail?.data[0]?.id || undefined;
|
||||
const isExistingCustomer = listByEmail?.data[0]?.id || undefined;
|
||||
|
||||
const NEXT_PUBLIC_TRIAL_PERIOD_DAYS =
|
||||
process.env.NEXT_PUBLIC_TRIAL_PERIOD_DAYS;
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
customer: isExistingCostomer ? isExistingCostomer : undefined,
|
||||
customer: isExistingCustomer ? isExistingCustomer : undefined,
|
||||
line_items: [
|
||||
{
|
||||
price: priceId,
|
||||
@@ -27,7 +27,7 @@ export default async function paymentCheckout(
|
||||
},
|
||||
],
|
||||
mode: "subscription",
|
||||
customer_email: isExistingCostomer ? undefined : email.toLowerCase(),
|
||||
customer_email: isExistingCustomer ? undefined : email.toLowerCase(),
|
||||
success_url: `${process.env.BASE_URL}?session_id={CHECKOUT_SESSION_ID}`,
|
||||
cancel_url: `${process.env.BASE_URL}/login`,
|
||||
automatic_tax: {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
export default async function verifySubscription(
|
||||
user?: UserIncludingSubscription
|
||||
) {
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const subscription = user.subscriptions;
|
||||
|
||||
const currentDate = new Date();
|
||||
|
||||
if (
|
||||
subscription &&
|
||||
currentDate > subscription.currentPeriodEnd &&
|
||||
!subscription.active
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!subscription || 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));
|
||||
}
|
||||
|
||||
if (!active) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { getToken } from "next-auth/jwt";
|
||||
import { prisma } from "./db";
|
||||
import { User } from "@prisma/client";
|
||||
import verifySubscription from "./verifySubscription";
|
||||
|
||||
type Props = {
|
||||
req: NextApiRequest;
|
||||
res: NextApiResponse;
|
||||
};
|
||||
|
||||
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
|
||||
|
||||
export default async function verifyUser({
|
||||
req,
|
||||
res,
|
||||
}: Props): Promise<User | null> {
|
||||
const token = await getToken({ req });
|
||||
const userId = token?.id;
|
||||
|
||||
if (!userId) {
|
||||
res.status(401).json({ response: "You must be logged in." });
|
||||
return null;
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
include: {
|
||||
subscriptions: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
res.status(404).json({ response: "User not found." });
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!user.username) {
|
||||
res.status(401).json({
|
||||
response: "Username not found.",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
if (STRIPE_SECRET_KEY) {
|
||||
const subscribedUser = verifySubscription(user);
|
||||
|
||||
if (!subscribedUser) {
|
||||
res.status(401).json({
|
||||
response:
|
||||
"You are not a subscriber, feel free to reach out to us at support@linkwarden.app if you think this is an issue.",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
Reference in New Issue
Block a user