diff --git a/src/app/api/auth/[...nextauth]/route.ts b/src/app/api/auth/[...nextauth]/route.ts index 6d27dc04..ad18277e 100644 --- a/src/app/api/auth/[...nextauth]/route.ts +++ b/src/app/api/auth/[...nextauth]/route.ts @@ -1,8 +1,13 @@ import NextAuth, { NextAuthOptions } from "next-auth"; import GoogleProvider from "next-auth/providers/google"; +import { db } from "@/app/db/db"; +import { user as userTable, User } from "@/app/db/schema/users"; +import { eq } from "drizzle-orm"; const { GOOGLE_CLIENT_ID = "", GOOGLE_CLIENT_SECRET = "" } = process.env; +type OauthProvider = "google"; + // TODO: handle token expiration // https://next-auth.js.org/v3/tutorials/refresh-token-rotation // propertly set options too @@ -26,14 +31,33 @@ export const AuthOptions: NextAuthOptions = { signIn: "/", }, callbacks: { - async signIn({ user, account, profile, email, credentials }) { - // TODO: While we don't have a database with verified users, - // for the demo, allow any user to sign in - // if (user.email?.endsWith("@hestia.homes")) { - // return true; - // } - // TODO: Handle this more elegantly - // return "/beta"; + async signIn({ user, account }) { + if (user == null || user.email == null) { + return "/beta"; + } + + const dbUser: User[] = await db + .select() + .from(userTable) + .where(eq(userTable.email, String(user.email))); + + if (dbUser.length !== 1 || account == null) { + return "/beta"; + } + + if (!dbUser[0].oauthId) { + // We make a second query to populate the oauthId and oauthProvider + console.log("Updating user with oauthId and oauthProvider"); + const provider = account.provider as OauthProvider; + + await db + .update(userTable) + .set({ oauthId: user.id, oauthProvider: provider }) + .where(eq(userTable.email, String(user.email))); + + console.log("Updated oauthId and oauthProvider"); + } + return true; }, async redirect({ baseUrl }) { diff --git a/src/app/db/db.ts b/src/app/db/db.ts index ac4c851b..ab3eaeb6 100644 --- a/src/app/db/db.ts +++ b/src/app/db/db.ts @@ -1,5 +1,4 @@ // db.ts -import { pgTable, serial, text, varchar } from "drizzle-orm/pg-core"; import { drizzle } from "drizzle-orm/node-postgres"; import { Pool } from "pg"; diff --git a/src/app/db/schema/users.ts b/src/app/db/schema/users.ts index 12268628..9c0cc5ea 100644 --- a/src/app/db/schema/users.ts +++ b/src/app/db/schema/users.ts @@ -1,4 +1,5 @@ import { serial, text, timestamp, pgTable } from "drizzle-orm/pg-core"; +import { InferModel } from "drizzle-orm"; export const user = pgTable("user", { id: serial("id").primaryKey(), @@ -21,3 +22,6 @@ export const user = pgTable("user", { .defaultNow() .notNull(), }); + +export type User = InferModel; +export type NewUser = InferModel;