Set up persistence of user id in session on client and server and pass userid to db call

This commit is contained in:
Khalim Conn-Kowlessar 2023-07-11 22:48:03 +01:00
parent 6224c303c8
commit 1e305912f6
3 changed files with 32 additions and 13 deletions

View file

@ -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;

View file

@ -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) {}

View file

@ -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 (
<>