Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

2.0 KB
Raw Blame
"use server";

import { prisma } from "@/lib/prisma";
import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { sendEmail } from "@dub/email";
import ResetPasswordLink from "@dub/email/templates/reset-password-link";
import { APP_DOMAIN } from "@dub/utils";
import { randomBytes } from "crypto";
import { flattenValidationErrors } from "next-safe-action";
import { PASSWORD_RESET_TOKEN_EXPIRY } from "../auth/constants";
import { requestPasswordResetSchema } from "../zod/schemas/auth";
import { throwIfAuthenticated } from "./auth/throw-if-authenticated";
import { actionClient } from "./safe-action";

// Request a password reset email
export const requestPasswordResetAction = actionClient
  .inputSchema(requestPasswordResetSchema, {
    handleValidationErrorsShape: async (ve) =>
      flattenValidationErrors(ve).fieldErrors,
  })
  .use(throwIfAuthenticated)
  .action(async ({ parsedInput }) => {
    const { email } = parsedInput;

    await assertRateLimit({
      policy: RATELIMIT_POLICIES.passwordResetRequest,
      identifier: email.toLowerCase(),
    });

    const user = await prisma.user.findUnique({
      where: {
        email,
      },
    });

    if (!user) {
      return { ok: true };
    }

    const token = randomBytes(32).toString("hex");

    // Run this sequentially to avoid race conditions
    await prisma.$transaction([
      // Remove old password reset tokens
      prisma.passwordResetToken.deleteMany({
        where: {
          identifier: email,
        },
      }),

      // Create a password reset token
      prisma.passwordResetToken.create({
        data: {
          identifier: email,
          token,
          expires: new Date(Date.now() + PASSWORD_RESET_TOKEN_EXPIRY * 1000),
        },
      }),
    ]);

    await sendEmail({
      subject: "Dub: Password reset instructions",
      to: email,
      react: ResetPasswordLink({
        email,
        url: `${APP_DOMAIN}/auth/reset-password/${token}`,
      }),
    });

    return { ok: true };
  });