From 1e305912f636db8a6f65e62ec94076eff6e2c1c4 Mon Sep 17 00:00:00 2001 From: Khalim Conn-Kowlessar Date: Tue, 11 Jul 2023 22:48:03 +0100 Subject: [PATCH] Set up persistence of user id in session on client and server and pass userid to db call --- src/app/api/auth/[...nextauth]/route.ts | 20 ++++++++++++++++++++ src/app/api/portfolio/route.ts | 13 +------------ src/app/home/page.tsx | 12 +++++++++++- 3 files changed, 32 insertions(+), 13 deletions(-) diff --git a/src/app/api/auth/[...nextauth]/route.ts b/src/app/api/auth/[...nextauth]/route.ts index fb3b4cc..e23c689 100644 --- a/src/app/api/auth/[...nextauth]/route.ts +++ b/src/app/api/auth/[...nextauth]/route.ts @@ -64,12 +64,32 @@ export const AuthOptions: NextAuthOptions = { console.log("Updated oauthId and oauthProvider"); } + // Set the user's ID from your database + user.dbId = dbUser[0].id; + return true; } catch (error) { console.error("Error during sign-in: ", error); return false; } }, + async jwt({ token, user }) { + // This is executed whenever a JWT is created or refreshed. + // `user` is the object returned from `signIn` callback and + // is only available during sign in, which is why we need to + // store the id in the token and then read it back into the session. + if (user?.dbId) { + token.dbId = user.dbId; + } + return token; + }, + async session({ session, token }) { + if (session?.user) { + session.user.dbId = token.dbId; + } + + return session; + }, async redirect({ baseUrl }) { const redirectUrl = baseUrl + "/home"; return redirectUrl; diff --git a/src/app/api/portfolio/route.ts b/src/app/api/portfolio/route.ts index 4d7ac79..a13a9f4 100644 --- a/src/app/api/portfolio/route.ts +++ b/src/app/api/portfolio/route.ts @@ -3,15 +3,4 @@ import { portfolio, portfolioUsers } from "@/app/db/schema/portfolio"; import { NextRequest, NextResponse } from "next/server"; import { db } from "@/app/db/db"; -export async function GET(request: NextRequest) { - // Get all portfolios for a user - use a relation - console.log(request); - - // const portfolios = await db - // .select() - // .from(portfolioUsers) - // .where(eq(portfolioUsers.userId, 1)); - // - const portfolios: String[] = []; - return NextResponse.json(portfolios); -} +export async function POST(request: NextRequest) {} diff --git a/src/app/home/page.tsx b/src/app/home/page.tsx index 6be585f..faab169 100644 --- a/src/app/home/page.tsx +++ b/src/app/home/page.tsx @@ -1,8 +1,18 @@ import CardTiles from "../components/home/CardTiles"; import getPortfolios from "./utils"; +import { AuthOptions } from "@/app/api/auth/[...nextauth]/route"; +import { getServerSession } from "next-auth"; +import { redirect } from "next/navigation"; const Home = async () => { - const portfolios = await getPortfolios(2); + const user = await getServerSession(AuthOptions); + + if (!user?.user) { + console.error("User not found"); + redirect("/"); + } + + const portfolios = await getPortfolios(user.user.dbId); return ( <>