Guest User

Untitled

a guest
Jan 26th, 2024
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 10.29 KB | Source Code | 0 0
  1. import { authOptions } from "@/pages/api/auth/[...nextauth]";
  2. import { getServerSession } from "next-auth/next";
  3.  
  4. import prisma from "@/lib/prismadb";
  5. import { levels } from "@/app/dashboard/_components/levels";
  6.  
  7. // Function to retrieve the user's session
  8. export async function getSession() {
  9.   return await getServerSession(authOptions);
  10. }
  11.  
  12. // Function to get the current user
  13. export default async function getCurrentUser() {
  14.   try {
  15.     // Get the user's session
  16.     const session = await getSession();
  17.  
  18.     // Check if the session exists and contains an email
  19.     if (!session?.user?.email) {
  20.       return null;
  21.     }
  22.  
  23.     // Find the current user based on their email
  24.     const currentUser = await prisma.user.findUnique({
  25.       where: {
  26.         email: session.user.email as string,
  27.       },
  28.     });
  29.  
  30.     // If the current user does not exist, return null
  31.     if (!currentUser) {
  32.       return null;
  33.     }
  34.  
  35.     // Get user skills and languages
  36.     const userSkills = await getUserSkills(currentUser);
  37.     const userLanguages = await getUserLanguages(currentUser);
  38.     const userTwoFa = await getUserTwoFactorAuth(currentUser);
  39.     const userActivateToken = await getUserActivateToken(currentUser);
  40.     const userSubscription = await getUserSubscription(currentUser);
  41.     const userProducts = await getUserProducts(currentUser);
  42.     const userBoughtProducts = await getUserBoughtProducts(currentUser);
  43.     const userBillingInformation = await getUserBillingInformation(currentUser);
  44.     const userLevel = await getUserLevel(currentUser);
  45.     const userHistory = await getUserHistory(currentUser);
  46.     const userNotifications = await getUserNotifications(currentUser);
  47.     const userMessageNotifications =
  48.       await getUserMessageNotifications(currentUser);
  49.  
  50.     // Format and return the user data with ISO date strings
  51.     return {
  52.       ...currentUser,
  53.       userSkills: userSkills || [],
  54.       userLanguages: userLanguages || [],
  55.       userTwoFa: userTwoFa || [],
  56.       userActivateToken: userActivateToken || [],
  57.       userSubscription: userSubscription || [],
  58.       userProducts: userProducts || [],
  59.       userBoughtProducts: userBoughtProducts || [],
  60.       userNotifications: userNotifications || [],
  61.       userMessageNotifications: userMessageNotifications || [],
  62.       userHistory: userHistory || [],
  63.       userBillingInformation: userBillingInformation || [],
  64.       userLevel: userLevel || [],
  65.       createdAt: currentUser.createdAt.toISOString(),
  66.       updatedAt: currentUser.updatedAt.toISOString(),
  67.       updatedPasswordAt: currentUser.updatedPasswordAt?.toISOString() ?? "null",
  68.       emailVerified: currentUser.emailVerified?.toISOString() || null,
  69.     };
  70.   } catch (error: any) {
  71.     // Handle errors and return null
  72.     return null;
  73.   }
  74. }
  75.  
  76. // Function to get user skills
  77. async function getUserSkills(user: any) {
  78.   try {
  79.     return await prisma.skills.findMany({
  80.       where: {
  81.         userId: {
  82.           equals: user?.id,
  83.         },
  84.       },
  85.     });
  86.   } catch (error) {
  87.     return;
  88.   }
  89. }
  90.  
  91. // Function to get user languages
  92. async function getUserLanguages(user: any) {
  93.   try {
  94.     return await prisma.languages.findMany({
  95.       where: {
  96.         userId: {
  97.           equals: user?.id,
  98.         },
  99.       },
  100.     });
  101.   } catch (error) {
  102.     return;
  103.   }
  104. }
  105.  
  106. // Function to get user 2fa
  107. async function getUserTwoFactorAuth(user: any) {
  108.   try {
  109.     return await prisma.twoFactorAuth.findMany({
  110.       where: {
  111.         userId: {
  112.           equals: user?.id,
  113.         },
  114.       },
  115.     });
  116.   } catch (error) {
  117.     return;
  118.   }
  119. }
  120.  
  121. // Function to get user activation token
  122. async function getUserActivateToken(user: any) {
  123.   try {
  124.     return await prisma.activateToken.findMany({
  125.       where: {
  126.         userId: {
  127.           equals: user?.id,
  128.         },
  129.       },
  130.     });
  131.   } catch (error) {
  132.     return;
  133.   }
  134. }
  135.  
  136. // Function to get user subscription
  137. async function getUserSubscription(user: any) {
  138.   try {
  139.     return await prisma.subscription.findMany({
  140.       where: {
  141.         userId: {
  142.           equals: user?.id,
  143.         },
  144.       },
  145.     });
  146.   } catch (error) {
  147.     return;
  148.   }
  149. }
  150.  
  151. // Function to get user products
  152. async function getUserProducts(user: any) {
  153.   try {
  154.     return await prisma.product.findMany({
  155.       where: {
  156.         userId: {
  157.           equals: user?.id,
  158.         },
  159.       },
  160.     });
  161.   } catch (error) {
  162.     return;
  163.   }
  164. }
  165.  
  166. async function getUserBoughtProducts(user: any) {
  167.   try {
  168.     const orders = await prisma.order.findMany({
  169.       where: {
  170.         userId: {
  171.           equals: user?.id,
  172.         },
  173.       },
  174.       include: {
  175.         orderItems: true,
  176.       },
  177.     });
  178.  
  179.     // find all products from order productId and map everything together
  180.     // return orders with products
  181.     return await Promise.all(
  182.       orders.map(async (order) => {
  183.         let orderItems = order.orderItems;
  184.         if (!orderItems) throw new Error("Order items not found");
  185.         if (!order.isPaid) return null;
  186.  
  187.         // Fetch all products from the order
  188.  
  189.         const allProducts = await Promise.all(
  190.           orderItems.map(async (item) => {
  191.             const product = await prisma.product.findUnique({
  192.               where: {
  193.                 id: item.productId,
  194.               },
  195.             });
  196.  
  197.             // find product owner
  198.             if (product) {
  199.               const productOwner = await prisma.user.findUnique({
  200.                 where: {
  201.                   id: product.productOwnerId,
  202.                 },
  203.               });
  204.  
  205.               if (!productOwner) throw new Error("Product owner not found");
  206.  
  207.               return {
  208.                 id: product.id,
  209.                 image: product.images[0],
  210.                 provider: {
  211.                   id: productOwner.id || "",
  212.                   name: productOwner.name || "",
  213.                   image: productOwner.image || null,
  214.                 },
  215.                 name: product.name,
  216.                 game: product.game,
  217.                 description: product.description,
  218.                 createdAt: product.createdAt,
  219.                 downloads: product.downloads,
  220.                 lastUpdated: product.createdAt,
  221.                 href: `/store/product/${productOwner.username}/${product.productId}`,
  222.               };
  223.             }
  224.           })
  225.         );
  226.  
  227.         return {
  228.           ...order,
  229.           products: allProducts,
  230.         };
  231.       })
  232.     );
  233.   } catch (error) {
  234.     console.error("Error fetching user bought products:", error);
  235.     return [];
  236.   }
  237. }
  238.  
  239. async function getUserBillingInformation(user: any) {
  240.   try {
  241.     return await prisma.billingInformation.findMany({
  242.       where: {
  243.         userId: {
  244.           equals: user?.id,
  245.         },
  246.       },
  247.     });
  248.   } catch (error) {
  249.     return;
  250.   }
  251. }
  252.  
  253. async function getUserHistory(user: any) {
  254.   try {
  255.     let historyUser = await prisma.historyUser.findMany({
  256.       where: {
  257.         userId: {
  258.           equals: user?.id,
  259.         },
  260.       },
  261.     });
  262.  
  263.     // get each history product owner name
  264.     return await Promise.all(
  265.       historyUser.map(async (history) => {
  266.         if (!history.productId) return history;
  267.  
  268.         const product = await prisma.product.findUnique({
  269.           where: {
  270.             id: history.productId!,
  271.           },
  272.         });
  273.  
  274.         if (product) {
  275.           const productOwner = await prisma.user.findUnique({
  276.             where: {
  277.               id: product.productOwnerId,
  278.             },
  279.           });
  280.  
  281.           if (!productOwner) throw new Error("Product owner not found");
  282.  
  283.           return {
  284.             ...history,
  285.             productOwnerName: productOwner.name,
  286.             productOwnerUsername: productOwner.username,
  287.           };
  288.         }
  289.       })
  290.     );
  291.   } catch (error) {
  292.     return;
  293.   }
  294. }
  295.  
  296. async function getUserLevel(user: any) {
  297.   try {
  298.     const userLevels = await prisma.userLevel.findMany({
  299.       where: {
  300.         userId: {
  301.           equals: user?.id,
  302.         },
  303.       },
  304.     });
  305.  
  306.     const updatePromises = userLevels.map(async (level) => {
  307.       if (level.timeStarted) {
  308.         const date = new Date(level.timeStarted);
  309.         const now = new Date();
  310.         const diff = Math.abs(now.getTime() - date.getTime());
  311.         const diffDays = Math.ceil(diff / (1000 * 3600 * 24));
  312.  
  313.         if (diffDays > levels[level.level - 1].days) {
  314.           await prisma.userLevel.update({
  315.             where: {
  316.               id: level.id,
  317.             },
  318.             data: {
  319.               level: 1,
  320.             },
  321.           });
  322.         }
  323.       }
  324.     });
  325.  
  326.     await Promise.all(updatePromises);
  327.  
  328.     return userLevels;
  329.   } catch (error) {
  330.     console.error("Error in getUserLevel:", error);
  331.     throw error; // Rethrow the error if needed
  332.   }
  333. }
  334.  
  335. async function getUserNotifications(user: any) {
  336.   try {
  337.     // take only last 3 notifications
  338.     return await prisma.notification.findMany({
  339.       where: {
  340.         userId: {
  341.           equals: user?.id,
  342.         },
  343.         isHidden: false,
  344.       },
  345.       orderBy: {
  346.         createdAt: "desc",
  347.       },
  348.       take: 3,
  349.     });
  350.   } catch (error) {
  351.     return;
  352.   }
  353. }
  354.  
  355. async function getUserMessageNotifications(user: any) {
  356.   try {
  357.     // take only last 3 notifications
  358.     let notifications = await prisma.messageNotification.findMany({
  359.       where: {
  360.         userId: {
  361.           equals: user?.id,
  362.         },
  363.       },
  364.       orderBy: {
  365.         createdAt: "desc",
  366.       },
  367.       take: 3,
  368.     });
  369.  
  370.     // Fetch information about the authors
  371.     let users = await Promise.all(
  372.       notifications.map(async (notification: any) => {
  373.         // find the other user in the conversation
  374.         return prisma.user.findUnique({
  375.           where: {
  376.             id: notification.authorId,
  377.           },
  378.         });
  379.       })
  380.     );
  381.  
  382.     return notifications.map((notification: any, index: number) => {
  383.       return {
  384.         conversationId: notification.conversationId,
  385.         message: notification.message,
  386.         unreadMessages: notification.unreadMessages,
  387.         author: {
  388.           name: users[index]?.name,
  389.           image: users[index]?.image ?? null,
  390.         },
  391.         createdAt: notification.createdAt,
  392.       };
  393.     });
  394.   } catch (error) {
  395.     console.error("Error fetching message notifications:", error);
  396.     throw error; // Rethrow the error if needed
  397.   }
  398. }
  399.  
Tags: JavaScript
Advertisement
Add Comment
Please, Sign In to add comment