Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { authOptions } from "@/pages/api/auth/[...nextauth]";
- import { getServerSession } from "next-auth/next";
- import prisma from "@/lib/prismadb";
- import { levels } from "@/app/dashboard/_components/levels";
- // Function to retrieve the user's session
- export async function getSession() {
- return await getServerSession(authOptions);
- }
- // Function to get the current user
- export default async function getCurrentUser() {
- try {
- // Get the user's session
- const session = await getSession();
- // Check if the session exists and contains an email
- if (!session?.user?.email) {
- return null;
- }
- // Find the current user based on their email
- const currentUser = await prisma.user.findUnique({
- where: {
- email: session.user.email as string,
- },
- });
- // If the current user does not exist, return null
- if (!currentUser) {
- return null;
- }
- // Get user skills and languages
- const userSkills = await getUserSkills(currentUser);
- const userLanguages = await getUserLanguages(currentUser);
- const userTwoFa = await getUserTwoFactorAuth(currentUser);
- const userActivateToken = await getUserActivateToken(currentUser);
- const userSubscription = await getUserSubscription(currentUser);
- const userProducts = await getUserProducts(currentUser);
- const userBoughtProducts = await getUserBoughtProducts(currentUser);
- const userBillingInformation = await getUserBillingInformation(currentUser);
- const userLevel = await getUserLevel(currentUser);
- const userHistory = await getUserHistory(currentUser);
- const userNotifications = await getUserNotifications(currentUser);
- const userMessageNotifications =
- await getUserMessageNotifications(currentUser);
- // Format and return the user data with ISO date strings
- return {
- ...currentUser,
- userSkills: userSkills || [],
- userLanguages: userLanguages || [],
- userTwoFa: userTwoFa || [],
- userActivateToken: userActivateToken || [],
- userSubscription: userSubscription || [],
- userProducts: userProducts || [],
- userBoughtProducts: userBoughtProducts || [],
- userNotifications: userNotifications || [],
- userMessageNotifications: userMessageNotifications || [],
- userHistory: userHistory || [],
- userBillingInformation: userBillingInformation || [],
- userLevel: userLevel || [],
- createdAt: currentUser.createdAt.toISOString(),
- updatedAt: currentUser.updatedAt.toISOString(),
- updatedPasswordAt: currentUser.updatedPasswordAt?.toISOString() ?? "null",
- emailVerified: currentUser.emailVerified?.toISOString() || null,
- };
- } catch (error: any) {
- // Handle errors and return null
- return null;
- }
- }
- // Function to get user skills
- async function getUserSkills(user: any) {
- try {
- return await prisma.skills.findMany({
- where: {
- userId: {
- equals: user?.id,
- },
- },
- });
- } catch (error) {
- return;
- }
- }
- // Function to get user languages
- async function getUserLanguages(user: any) {
- try {
- return await prisma.languages.findMany({
- where: {
- userId: {
- equals: user?.id,
- },
- },
- });
- } catch (error) {
- return;
- }
- }
- // Function to get user 2fa
- async function getUserTwoFactorAuth(user: any) {
- try {
- return await prisma.twoFactorAuth.findMany({
- where: {
- userId: {
- equals: user?.id,
- },
- },
- });
- } catch (error) {
- return;
- }
- }
- // Function to get user activation token
- async function getUserActivateToken(user: any) {
- try {
- return await prisma.activateToken.findMany({
- where: {
- userId: {
- equals: user?.id,
- },
- },
- });
- } catch (error) {
- return;
- }
- }
- // Function to get user subscription
- async function getUserSubscription(user: any) {
- try {
- return await prisma.subscription.findMany({
- where: {
- userId: {
- equals: user?.id,
- },
- },
- });
- } catch (error) {
- return;
- }
- }
- // Function to get user products
- async function getUserProducts(user: any) {
- try {
- return await prisma.product.findMany({
- where: {
- userId: {
- equals: user?.id,
- },
- },
- });
- } catch (error) {
- return;
- }
- }
- async function getUserBoughtProducts(user: any) {
- try {
- const orders = await prisma.order.findMany({
- where: {
- userId: {
- equals: user?.id,
- },
- },
- include: {
- orderItems: true,
- },
- });
- // find all products from order productId and map everything together
- // return orders with products
- return await Promise.all(
- orders.map(async (order) => {
- let orderItems = order.orderItems;
- if (!orderItems) throw new Error("Order items not found");
- if (!order.isPaid) return null;
- // Fetch all products from the order
- const allProducts = await Promise.all(
- orderItems.map(async (item) => {
- const product = await prisma.product.findUnique({
- where: {
- id: item.productId,
- },
- });
- // find product owner
- if (product) {
- const productOwner = await prisma.user.findUnique({
- where: {
- id: product.productOwnerId,
- },
- });
- if (!productOwner) throw new Error("Product owner not found");
- return {
- id: product.id,
- image: product.images[0],
- provider: {
- id: productOwner.id || "",
- name: productOwner.name || "",
- image: productOwner.image || null,
- },
- name: product.name,
- game: product.game,
- description: product.description,
- createdAt: product.createdAt,
- downloads: product.downloads,
- lastUpdated: product.createdAt,
- href: `/store/product/${productOwner.username}/${product.productId}`,
- };
- }
- })
- );
- return {
- ...order,
- products: allProducts,
- };
- })
- );
- } catch (error) {
- console.error("Error fetching user bought products:", error);
- return [];
- }
- }
- async function getUserBillingInformation(user: any) {
- try {
- return await prisma.billingInformation.findMany({
- where: {
- userId: {
- equals: user?.id,
- },
- },
- });
- } catch (error) {
- return;
- }
- }
- async function getUserHistory(user: any) {
- try {
- let historyUser = await prisma.historyUser.findMany({
- where: {
- userId: {
- equals: user?.id,
- },
- },
- });
- // get each history product owner name
- return await Promise.all(
- historyUser.map(async (history) => {
- if (!history.productId) return history;
- const product = await prisma.product.findUnique({
- where: {
- id: history.productId!,
- },
- });
- if (product) {
- const productOwner = await prisma.user.findUnique({
- where: {
- id: product.productOwnerId,
- },
- });
- if (!productOwner) throw new Error("Product owner not found");
- return {
- ...history,
- productOwnerName: productOwner.name,
- productOwnerUsername: productOwner.username,
- };
- }
- })
- );
- } catch (error) {
- return;
- }
- }
- async function getUserLevel(user: any) {
- try {
- const userLevels = await prisma.userLevel.findMany({
- where: {
- userId: {
- equals: user?.id,
- },
- },
- });
- const updatePromises = userLevels.map(async (level) => {
- if (level.timeStarted) {
- const date = new Date(level.timeStarted);
- const now = new Date();
- const diff = Math.abs(now.getTime() - date.getTime());
- const diffDays = Math.ceil(diff / (1000 * 3600 * 24));
- if (diffDays > levels[level.level - 1].days) {
- await prisma.userLevel.update({
- where: {
- id: level.id,
- },
- data: {
- level: 1,
- },
- });
- }
- }
- });
- await Promise.all(updatePromises);
- return userLevels;
- } catch (error) {
- console.error("Error in getUserLevel:", error);
- throw error; // Rethrow the error if needed
- }
- }
- async function getUserNotifications(user: any) {
- try {
- // take only last 3 notifications
- return await prisma.notification.findMany({
- where: {
- userId: {
- equals: user?.id,
- },
- isHidden: false,
- },
- orderBy: {
- createdAt: "desc",
- },
- take: 3,
- });
- } catch (error) {
- return;
- }
- }
- async function getUserMessageNotifications(user: any) {
- try {
- // take only last 3 notifications
- let notifications = await prisma.messageNotification.findMany({
- where: {
- userId: {
- equals: user?.id,
- },
- },
- orderBy: {
- createdAt: "desc",
- },
- take: 3,
- });
- // Fetch information about the authors
- let users = await Promise.all(
- notifications.map(async (notification: any) => {
- // find the other user in the conversation
- return prisma.user.findUnique({
- where: {
- id: notification.authorId,
- },
- });
- })
- );
- return notifications.map((notification: any, index: number) => {
- return {
- conversationId: notification.conversationId,
- message: notification.message,
- unreadMessages: notification.unreadMessages,
- author: {
- name: users[index]?.name,
- image: users[index]?.image ?? null,
- },
- createdAt: notification.createdAt,
- };
- });
- } catch (error) {
- console.error("Error fetching message notifications:", error);
- throw error; // Rethrow the error if needed
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment