import { betterAuth } from 'better-auth'; import { prismaAdapter } from '@better-auth/prisma-adapter'; import prisma from './prisma.js'; import EmailSender from './email-sender.js'; import { emailOTP } from 'better-auth/plugins'; export const auth = betterAuth({ appName: process.env.APP_NAME ?? 'app', basePath: '/api/auth', plugins: [ // authTransformResponse() emailOTP({ async sendVerificationOTP({ email, otp, type }) { if (type === 'sign-in') { EmailSender.sendInBackground({ to: email, subject: `Your OTP code is: ${otp}`, text: `Your OTP code is: ${otp}`, }); } else if (type === 'email-verification') { // Send the OTP for email verification console.log({ email, otp, type }); } else if (type === 'forget-password') { EmailSender.sendInBackground({ to: email, subject: `Your password reset code is: ${otp}`, text: `Your password reset code is: ${otp}`, }); } else { console.log({ email, otp, type }); } }, }), ], database: prismaAdapter(prisma, { provider: 'postgresql', }), advanced: { disableOriginCheck: true, disableCSRFCheck: true, database: { joins: true, }, }, secret: process.env.BETTER_AUTH_SECRET, baseURL: process.env.BETTER_AUTH_URL ?? 'http://localhost:3000', emailAndPassword: { enabled: true, autoSignIn: false, requireEmailVerification: true, onExistingUserSignUp: async ({ user }, request) => { EmailSender.sendInBackground({ to: user.email, subject: 'Sign-up attempt with your email', text: 'Someone tried to create an account using your email address. If this was you, try signing in instead. If not, you can safely ignore this email.', }); }, sendResetPassword: async ({ user, url, token }, request) => { EmailSender.sendInBackground({ to: user.email, subject: 'Reset your password', text: `Click the link to reset your password: ${url}`, }); }, onPasswordReset: async ({ user }, request) => { EmailSender.sendInBackground({ to: user.email, subject: 'Reset your password result', text: `Password for user ${user.email} has been reset.`, }); }, }, emailVerification: { sendOnSignIn: true, autoSignInAfterVerification: true, sendVerificationEmail: async ({ user, url }) => { EmailSender.sendInBackground({ to: user.email, subject: 'Verify your email address', text: `Click the link to verify your email: ${url}`, }); }, }, session: { freshAge: 0, cookieCache: { enabled: true, maxAge: 30, }, }, });