From e5edfc05585627e40dd07066d0e8b183ca9de48b Mon Sep 17 00:00:00 2001 From: ayusshrathore Date: Mon, 5 Jun 2023 21:53:50 +0530 Subject: [PATCH] chore: add libs for auth & db --- libs/fetcher.ts | 5 +++++ libs/prismadb.ts | 11 +++++++++++ libs/serverAuth.ts | 27 +++++++++++++++++++++++++++ pages/_document.tsx | 13 ------------- 4 files changed, 43 insertions(+), 13 deletions(-) create mode 100644 libs/fetcher.ts create mode 100644 libs/prismadb.ts create mode 100644 libs/serverAuth.ts delete mode 100644 pages/_document.tsx diff --git a/libs/fetcher.ts b/libs/fetcher.ts new file mode 100644 index 0000000..0507e9c --- /dev/null +++ b/libs/fetcher.ts @@ -0,0 +1,5 @@ +import axios from "axios"; + +const fetcher = (url: string) => axios.get(url).then((res) => res.data); + +export default fetcher; diff --git a/libs/prismadb.ts b/libs/prismadb.ts new file mode 100644 index 0000000..b13b1ad --- /dev/null +++ b/libs/prismadb.ts @@ -0,0 +1,11 @@ +import { PrismaClient } from "@prisma/client"; + +declare global { + var prisma: PrismaClient | undefined; +} + +const client = globalThis.prisma || new PrismaClient(); + +if (process.env.NODE_ENV !== "production") globalThis.prisma = client; + +export default client; diff --git a/libs/serverAuth.ts b/libs/serverAuth.ts new file mode 100644 index 0000000..9e75334 --- /dev/null +++ b/libs/serverAuth.ts @@ -0,0 +1,27 @@ +import { NextApiRequest, NextApiResponse } from "next"; + +import prisma from "@/libs/prismadb"; +import { authOptions } from "@/pages/api/auth/[...nextauth]"; +import { getServerSession } from "next-auth"; + +const serverAuth = async (req: NextApiRequest, res: NextApiResponse) => { + const session = await getServerSession(req, res, authOptions); + + if (!session?.user?.email) { + throw new Error("Unauthorized"); + } + + const currentUser = await prisma.user.findUnique({ + where: { + email: session.user.email, + }, + }); + + if (!currentUser) { + throw new Error("Unauthorized"); + } + + return { currentUser }; +}; + +export default serverAuth; diff --git a/pages/_document.tsx b/pages/_document.tsx deleted file mode 100644 index 54e8bf3..0000000 --- a/pages/_document.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { Html, Head, Main, NextScript } from 'next/document' - -export default function Document() { - return ( - - - -
- - - - ) -}