initial commit
This commit is contained in:
49
src/app/api/auth/[...nextauth]/route.ts
Normal file
49
src/app/api/auth/[...nextauth]/route.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import NextAuth, { NextAuthOptions } from "next-auth";
|
||||
import GoogleProvider from "next-auth/providers/google";
|
||||
import { PrismaAdapter } from "@next-auth/prisma-adapter";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export const authOptions: NextAuthOptions = {
|
||||
adapter: PrismaAdapter(prisma),
|
||||
providers: [
|
||||
GoogleProvider({
|
||||
clientId: process.env.GOOGLE_CLIENT_ID!,
|
||||
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
async jwt({ token, account }) {
|
||||
if (account) {
|
||||
token.accessToken = account.access_token;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
async session({ session, user, token }) {
|
||||
if (session.user) {
|
||||
session.user.id = user?.id || (token?.sub as string);
|
||||
// Fetch fresh role from DB if needed, or use token
|
||||
const dbUser = await prisma.user.findUnique({ where: { id: session.user.id } });
|
||||
session.user.role = dbUser?.role || 'EMPLOYEE';
|
||||
}
|
||||
return session;
|
||||
},
|
||||
},
|
||||
events: {
|
||||
async createUser({ user }) {
|
||||
const userCount = await prisma.user.count();
|
||||
if (userCount === 1) {
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { role: 'ADMIN' },
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
pages: {
|
||||
signIn: "/auth/signin",
|
||||
},
|
||||
};
|
||||
|
||||
const handler = NextAuth(authOptions);
|
||||
|
||||
export { handler as GET, handler as POST };
|
||||
Reference in New Issue
Block a user