81 lines
2.1 KiB
TypeScript

import { PrismaAdapter } from "@auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import Discord from "next-auth/providers/discord";
import bcrypt from "bcryptjs";
import { SecretClient } from "@/lib/secret/init";
const prisma = new PrismaClient();
export const { handlers, signIn, signOut, auth } = NextAuth(async () => {
const sClient = SecretClient();
const clientId = await sClient.fetchSecret("discord_client_id");
const clientSecret = await sClient.fetchSecret("discord_client_secret");
return {
providers: [
Discord({
clientId,
clientSecret,
// redirectProxyUrl:
// "https://bottomsurgery.local:3000/api/auth/callback/discord",
}),
Credentials({
credentials: {
email: {},
password: {},
},
authorize: async (credentials) => {
let user = null;
const pwHash = await saltAndHashPassword(
credentials.password as string,
);
user = await prisma.user.findFirst({
where: {
email: credentials.email as string,
},
select: {
name: true,
image: true,
email: true,
emailVerified: true,
username: true,
passwordHash: true,
},
});
if (!user) {
user = await prisma.user.create({
data: {
email: credentials.email as string,
passwordHash: pwHash,
},
select: {
name: true,
image: true,
email: true,
emailVerified: true,
username: true,
},
});
return user;
}
user.passwordHash = null;
return user;
},
}),
],
adapter: PrismaAdapter(prisma),
};
});
async function saltAndHashPassword(password: string) {
const hash = await bcrypt.hash(password, 10);
return hash;
}