So I ran through the wonderful cookbook for Sending Emails using SendInBlue and everything went pretty flawless. This enabled the feature of sending an email from the admin interface. However, I’m struggling to integrate the new function built in email.ts to send an email from the Forgot Password page and adding the necessary code in auth.ts similar to the code added in user.ts
I also reviewed the post dbAuth - Fail to reset password (email) which was helpful but doesn’t use the reusable function email.ts like in the cookbook. Does someone have a working example to reference or any tips? Seems like functions like sending an email for password reset (when using dbAuth) would be one of the core features so I’m hoping there is a short guide that could extend the cookbook for working examples.
Hey Justin! So the code in api/src/lib/email.js still just exports regular JS functions you can use elsewhere. In this case, you could import your email sending function from api/src/lib/email.js into api/src/functions/auth.js. Then update the forgotPasswordOptions.handler() function to call your email sending function, passing in the user or email address, or whatever else your function expects to receive. You’ll want to include the resetToken in the URL as shown in the comments above the handler definition.
Okay, I guess fresh eyes help. Here is what worked for me in case it helps others (this is based on the cookbook Sending Email and the relevant files in place):
import { Prisma } from '@prisma/client'
import { DbAuthHandler } from '@redwoodjs/api'
import { db } from 'src/lib/db'
import { sendEmail } from 'src/lib/email'
import { createAudit } from '../services/audits/audits'
export const handler = async (event, context) => {
const forgotPasswordOptions = {
handler: async ({ id }: Prisma.UserWhereUniqueInput) => {
const user = await db.user.findUnique({
where: { id },
})
function sendForgotPasswordEmail(emailAddress: string) {
const resetLink = `${process.env.APP_URL}/reset-password?resetToken=${user.resetToken}`
const subject = 'Reset your forgotten password'
const text = `Here is a link reset your password. It will expire after 4hrs. <a href="${resetLink}">Reset my Password</>`
const html = `Here is a link reset your password. It will expire after 4hrs. <a href="${resetLink}">Reset my Password</>`
return sendEmail({ to: emailAddress, subject, text, html })
}
await sendForgotPasswordEmail(user.email)
await createAudit({
input: {
user: { connect: { id } },
log: 'Reset password email was sent to user.',
},
})
return user
},
expires: 60 * 60 * 24,
errors: {
usernameNotFound: 'Username not found',
usernameRequired: 'Username is required',
},
}
Given the .env variable for APP_URL is set.
@rob does this all look correct? Also, thanks for jumping on this post!
Not sure about that, I avoid Typescript like the plague! @Tobbe updated the cookbook article for TS, maybe he knows? I’d just rename the file to .js to get rid of the squiggles