create-auth-js-boiler
Version:
Create a new auth-js-boiler project
116 lines (109 loc) • 3.05 kB
text/typescript
import NextAuth from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/lib/prisma";
import authConfig from "./auth.config";
import { getTwoFactorConfirmationByUserId } from "./lib/two-factor-confirmation";
export const { handlers, signIn, signOut, auth } = NextAuth({
trustHost: true,
pages: {
signIn: "/auth/login",
error: "/auth/error",
},
events: {
async linkAccount({ user }) {
// check if user is already verified
const existingUser = await prisma.user.findUnique({
where: {
id: user.id,
},
});
if (!existingUser?.emailVerified && existingUser) {
await prisma.user.update({
where: {
id: user.id,
},
data: {
emailVerified: new Date(),
},
});
}
},
},
callbacks: {
async signIn({ user, account }) {
// allow oauth sign in
if (account?.provider !== "credentials") {
return true;
}
const existingUser = await prisma.user.findUnique({
where: {
id: user.id,
},
});
// prevent sign in if user not verified
if (!existingUser?.emailVerified) {
return false;
}
if (existingUser.isTwoFactorEnabled) {
const twoFactorConfirmation = await getTwoFactorConfirmationByUserId(
existingUser.id,
);
if (!twoFactorConfirmation) {
return false;
}
// delete two factor confirmation for next sign in
await prisma.twoFactorConfirmation.delete({
where: {
id: twoFactorConfirmation.id,
},
});
}
return true;
},
async session({ token, session }) {
if (token.sub && session.user) {
session.user.id = token.sub;
}
if (token.role && session.user) {
session.user.role = token.role;
}
if (token.isTwoFactorEnabled && session.user) {
session.user.isTwoFactorEnabled = token.isTwoFactorEnabled;
}
if (session.user) {
session.user.isTwoFactorEnabled = token.isTwoFactorEnabled;
session.user.name = token.name;
session.user.email = token.email;
session.user.isOAuth = token.isOAuth;
}
return session;
},
async jwt({ token }) {
if (!token.sub) {
return token;
}
const existingUser = await prisma.user.findUnique({
where: {
id: token.sub,
},
});
if (!existingUser) {
return token;
}
const existingAccount = await prisma.account.findFirst({
where: { id: existingUser.id },
});
token.isOAuth = !!existingAccount;
token.name = existingUser.name;
token.email = existingUser.email;
token.role = existingUser.role;
token.isTwoFactorEnabled = existingUser.isTwoFactorEnabled;
return token;
},
},
adapter: PrismaAdapter(prisma),
session: {
strategy: "jwt",
},
...authConfig,
});