From 0f29052feaf177dd50edebe34336556512e87c96 Mon Sep 17 00:00:00 2001 From: Sanjib Kumar Sen Date: Sat, 11 Jan 2025 21:33:58 +0600 Subject: [PATCH] added email auth --- src/lib/auth/auth.ts | 20 +++++++++++++++++++- src/lib/mail.ts | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 src/lib/mail.ts diff --git a/src/lib/auth/auth.ts b/src/lib/auth/auth.ts index 226c052..4968c50 100644 --- a/src/lib/auth/auth.ts +++ b/src/lib/auth/auth.ts @@ -3,10 +3,10 @@ import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { db } from "../../db/index"; import { openAPI } from "better-auth/plugins" import { user, account, verification, session } from "../../db/schema"; +import { sendMail } from "../mail"; export const auth = betterAuth({ database: drizzleAdapter(db, { - // We're using Drizzle as our database provider: "pg", schema: { user: user, @@ -17,6 +17,24 @@ export const auth = betterAuth({ }), emailAndPassword: { enabled: true, // If you want to use email and password auth + requireEmailVerification: false, + sendResetPassword: async ({ user, url }, request) => { + await sendMail({ + to: user.email, + subject: "Reset your password", + text: `Click the link to reset your password: ${url}`, + }); + }, + }, + emailVerification: { + sendVerificationEmail: async ({ user, url, token }, request) => { + await sendMail({ + to: user.email, + subject: "Verify your email address", + text: `Click the link to verify your email: ${url}`, + }); + }, + }, plugins: [ openAPI({ diff --git a/src/lib/mail.ts b/src/lib/mail.ts new file mode 100644 index 0000000..83757f3 --- /dev/null +++ b/src/lib/mail.ts @@ -0,0 +1,19 @@ +import nodemailer from 'nodemailer' + +export async function sendMail({ to, subject, text }: { to: string, subject: string, text: string }) { + const transporter = nodemailer.createTransport({ + host: process.env.SMTP_HOST!, + port: +process.env.SMTP_PORT!, + auth: { + user: process.env.SMTP_USER!, + pass: process.env.SMTP_PASSWORD!, + } + }) + + await transporter.sendMail({ + from: process.env.SMTP_FROM!, + to, + subject, + text, + }) +}