feat: added email change feature (#5837)

Co-authored-by: Paribesh01 <nepalparibesh01@gmail.com>
Co-authored-by: Paribesh Nepal <100255987+Paribesh01@users.noreply.github.com>
This commit is contained in:
Piyush Gupta
2025-05-21 16:53:12 +05:30
committed by GitHub
parent 745f5487e9
commit f7e5ef96d2
34 changed files with 1286 additions and 205 deletions
@@ -0,0 +1,61 @@
import "@testing-library/jest-dom/vitest";
import { cleanup, render, screen } from "@testing-library/react";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import { afterEach, describe, expect, test, vi } from "vitest";
import { EmailChangeWithoutVerificationSuccessPage } from "./page";
// Mock the necessary dependencies
vi.mock("@/modules/auth/components/back-to-login-button", () => ({
BackToLoginButton: () => <div data-testid="back-to-login">Back to Login</div>,
}));
vi.mock("@/modules/auth/components/form-wrapper", () => ({
FormWrapper: ({ children }: { children: React.ReactNode }) => (
<div data-testid="form-wrapper">{children}</div>
),
}));
vi.mock("@/modules/auth/lib/authOptions", () => ({
authOptions: {},
}));
vi.mock("next-auth", () => ({
getServerSession: vi.fn(),
}));
vi.mock("next/navigation", () => ({
redirect: vi.fn(),
}));
vi.mock("@/tolgee/server", () => ({ getTranslate: () => Promise.resolve((key: string) => key) }));
describe("EmailChangeWithoutVerificationSuccessPage", () => {
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
test("renders success page with correct translations when user is not logged in", async () => {
vi.mocked(getServerSession).mockResolvedValue(null);
const page = await EmailChangeWithoutVerificationSuccessPage();
render(page);
expect(screen.getByTestId("form-wrapper")).toBeInTheDocument();
expect(screen.getByTestId("back-to-login")).toBeInTheDocument();
expect(screen.getByText("auth.email-change.email_change_success")).toBeInTheDocument();
expect(screen.getByText("auth.email-change.email_change_success_description")).toBeInTheDocument();
});
test("redirects to home page when user is logged in", async () => {
vi.mocked(getServerSession).mockResolvedValue({
user: { id: "123", email: "test@example.com" },
expires: new Date().toISOString(),
});
await EmailChangeWithoutVerificationSuccessPage();
expect(redirect).toHaveBeenCalledWith("/");
});
});
@@ -0,0 +1,29 @@
import { BackToLoginButton } from "@/modules/auth/components/back-to-login-button";
import { FormWrapper } from "@/modules/auth/components/form-wrapper";
import { authOptions } from "@/modules/auth/lib/authOptions";
import { getTranslate } from "@/tolgee/server";
import { getServerSession } from "next-auth";
import type { Session } from "next-auth";
import { redirect } from "next/navigation";
export const EmailChangeWithoutVerificationSuccessPage = async () => {
const t = await getTranslate();
const session: Session | null = await getServerSession(authOptions);
if (session) {
redirect("/");
}
return (
<div className="bg-gradient-radial flex min-h-screen from-slate-200 to-slate-50">
<FormWrapper>
<h1 className="leading-2 mb-4 text-center font-bold">
{t("auth.email-change.email_change_success")}
</h1>
<p className="text-center text-sm">{t("auth.email-change.email_change_success_description")}</p>
<hr className="my-4" />
<BackToLoginButton />
</FormWrapper>
</div>
);
};
@@ -5,15 +5,17 @@ import { getTranslate } from "@/tolgee/server";
export const SignupWithoutVerificationSuccessPage = async () => {
const t = await getTranslate();
return (
<FormWrapper>
<h1 className="leading-2 mb-4 text-center font-bold">
{t("auth.signup_without_verification_success.user_successfully_created")}
</h1>
<p className="text-center text-sm">
{t("auth.signup_without_verification_success.user_successfully_created_description")}
</p>
<hr className="my-4" />
<BackToLoginButton />
</FormWrapper>
<div className="bg-gradient-radial flex min-h-screen from-slate-200 to-slate-50">
<FormWrapper>
<h1 className="leading-2 mb-4 text-center font-bold">
{t("auth.signup_without_verification_success.user_successfully_created")}
</h1>
<p className="text-center text-sm">
{t("auth.signup_without_verification_success.user_successfully_created_description")}
</p>
<hr className="my-4" />
<BackToLoginButton />
</FormWrapper>
</div>
);
};
@@ -0,0 +1,21 @@
"use server";
import { verifyEmailChangeToken } from "@/lib/jwt";
import { actionClient } from "@/lib/utils/action-client";
import { updateUser } from "@/modules/auth/lib/user";
import { z } from "zod";
export const verifyEmailChangeAction = actionClient
.schema(z.object({ token: z.string() }))
.action(async ({ parsedInput }) => {
const { id, email } = await verifyEmailChangeToken(parsedInput.token);
if (!email) {
throw new Error("Email not found in token");
}
const user = await updateUser(id, { email, emailVerified: new Date() });
if (!user) {
throw new Error("User not found or email update failed");
}
return user;
});
@@ -0,0 +1,68 @@
import { verifyEmailChangeAction } from "@/modules/auth/verify-email-change/actions";
import "@testing-library/jest-dom/vitest";
import { cleanup, render, screen, waitFor } from "@testing-library/react";
import { signOut } from "next-auth/react";
import { afterEach, describe, expect, test, vi } from "vitest";
import { EmailChangeSignIn } from "./email-change-sign-in";
// Mock dependencies
vi.mock("@tolgee/react", () => ({
useTranslate: () => ({
t: (key: string) => key,
}),
}));
vi.mock("next-auth/react", () => ({
signOut: vi.fn(),
}));
vi.mock("@/modules/auth/verify-email-change/actions", () => ({
verifyEmailChangeAction: vi.fn(),
}));
describe("EmailChangeSignIn", () => {
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
test("shows loading state initially", () => {
render(<EmailChangeSignIn token="valid-token" />);
expect(screen.getByText("auth.email-change.email_verification_failed")).toBeInTheDocument();
});
test("handles successful email change verification", async () => {
vi.mocked(verifyEmailChangeAction).mockResolvedValueOnce({
data: { id: "123", email: "test@example.com", emailVerified: new Date(), locale: "en-US" },
});
render(<EmailChangeSignIn token="valid-token" />);
await waitFor(() => {
expect(screen.getByText("auth.email-change.email_change_success")).toBeInTheDocument();
expect(screen.getByText("auth.email-change.email_change_success_description")).toBeInTheDocument();
});
expect(signOut).toHaveBeenCalledWith({ redirect: false });
});
test("handles failed email change verification", async () => {
vi.mocked(verifyEmailChangeAction).mockResolvedValueOnce({ serverError: "Error" });
render(<EmailChangeSignIn token="invalid-token" />);
await waitFor(() => {
expect(screen.getByText("auth.email-change.email_verification_failed")).toBeInTheDocument();
expect(screen.getByText("auth.email-change.invalid_or_expired_token")).toBeInTheDocument();
});
expect(signOut).not.toHaveBeenCalled();
});
test("handles empty token", () => {
render(<EmailChangeSignIn token="" />);
expect(screen.getByText("auth.email-change.email_verification_failed")).toBeInTheDocument();
expect(screen.getByText("auth.email-change.invalid_or_expired_token")).toBeInTheDocument();
});
});
@@ -0,0 +1,55 @@
"use client";
import { verifyEmailChangeAction } from "@/modules/auth/verify-email-change/actions";
import { useTranslate } from "@tolgee/react";
import { signOut } from "next-auth/react";
import { useEffect, useState } from "react";
export const EmailChangeSignIn = ({ token }: { token: string }) => {
const { t } = useTranslate();
const [status, setStatus] = useState<"success" | "error" | "loading">("loading");
useEffect(() => {
const validateToken = async () => {
if (typeof token === "string" && token.trim() !== "") {
const result = await verifyEmailChangeAction({ token });
if (!result?.data) {
setStatus("error");
} else {
setStatus("success");
}
} else {
setStatus("error");
}
};
if (token) {
validateToken();
} else {
setStatus("error");
}
}, [token]);
useEffect(() => {
if (status === "success") {
signOut({ redirect: false });
}
}, [status]);
return (
<>
<h1 className={`leading-2 mb-4 text-center font-bold ${status === "error" ? "text-red-600" : ""}`}>
{status === "success"
? t("auth.email-change.email_change_success")
: t("auth.email-change.email_verification_failed")}
</h1>
<p className="text-center text-sm">
{status === "success"
? t("auth.email-change.email_change_success_description")
: t("auth.email-change.invalid_or_expired_token")}
</p>
<hr className="my-4" />
</>
);
};
@@ -0,0 +1,47 @@
import "@testing-library/jest-dom/vitest";
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, test, vi } from "vitest";
import { VerifyEmailChangePage } from "./page";
// Mock the necessary dependencies
vi.mock("@/modules/auth/components/back-to-login-button", () => ({
BackToLoginButton: () => <div data-testid="back-to-login">Back to Login</div>,
}));
vi.mock("@/modules/auth/components/form-wrapper", () => ({
FormWrapper: ({ children }: { children: React.ReactNode }) => (
<div data-testid="form-wrapper">{children}</div>
),
}));
vi.mock("@/modules/auth/verify-email-change/components/email-change-sign-in", () => ({
EmailChangeSignIn: ({ token }: { token: string }) => (
<div data-testid="email-change-sign-in">Email Change Sign In with token: {token}</div>
),
}));
describe("VerifyEmailChangePage", () => {
afterEach(() => {
cleanup();
});
test("renders the page with form wrapper and components", async () => {
const searchParams = { token: "test-token" };
render(await VerifyEmailChangePage({ searchParams }));
expect(screen.getByTestId("form-wrapper")).toBeInTheDocument();
expect(screen.getByTestId("email-change-sign-in")).toBeInTheDocument();
expect(screen.getByTestId("back-to-login")).toBeInTheDocument();
expect(screen.getByText("Email Change Sign In with token: test-token")).toBeInTheDocument();
});
test("handles missing token", async () => {
const searchParams = {};
render(await VerifyEmailChangePage({ searchParams }));
expect(screen.getByTestId("form-wrapper")).toBeInTheDocument();
expect(screen.getByTestId("email-change-sign-in")).toBeInTheDocument();
expect(screen.getByTestId("back-to-login")).toBeInTheDocument();
expect(screen.getByText("Email Change Sign In with token:")).toBeInTheDocument();
});
});
@@ -0,0 +1,16 @@
import { BackToLoginButton } from "@/modules/auth/components/back-to-login-button";
import { FormWrapper } from "@/modules/auth/components/form-wrapper";
import { EmailChangeSignIn } from "@/modules/auth/verify-email-change/components/email-change-sign-in";
export const VerifyEmailChangePage = async ({ searchParams }) => {
const { token } = await searchParams;
return (
<div className="bg-gradient-radial flex min-h-screen from-slate-200 to-slate-50">
<FormWrapper>
<EmailChangeSignIn token={token} />
<BackToLoginButton />
</FormWrapper>
</div>
);
};
@@ -0,0 +1,34 @@
import { getTranslate } from "@/tolgee/server";
import { Container, Heading, Link, Text } from "@react-email/components";
import React from "react";
import { EmailButton } from "../../components/email-button";
import { EmailFooter } from "../../components/email-footer";
import { EmailTemplate } from "../../components/email-template";
interface VerificationEmailProps {
readonly verifyLink: string;
}
export async function NewEmailVerification({
verifyLink,
}: VerificationEmailProps): Promise<React.JSX.Element> {
const t = await getTranslate();
return (
<EmailTemplate t={t}>
<Container>
<Heading>{t("emails.verification_email_heading")}</Heading>
<Text>{t("emails.new_email_verification_text")}</Text>
<Text>{t("emails.verification_security_notice")}</Text>
<EmailButton href={verifyLink} label={t("emails.verification_email_verify_email")} />
<Text>{t("emails.verification_email_click_on_this_link")}</Text>
<Link className="break-all text-black" href={verifyLink}>
{verifyLink}
</Link>
<Text className="font-bold">{t("emails.verification_email_link_valid_for_24_hours")}</Text>
<EmailFooter t={t} />
</Container>
</EmailTemplate>
);
}
export default NewEmailVerification;
+21 -1
View File
@@ -12,8 +12,9 @@ import {
WEBAPP_URL,
} from "@/lib/constants";
import { getSurveyDomain } from "@/lib/getSurveyUrl";
import { createInviteToken, createToken, createTokenForLinkSurvey } from "@/lib/jwt";
import { createEmailChangeToken, createInviteToken, createToken, createTokenForLinkSurvey } from "@/lib/jwt";
import { getOrganizationByEnvironmentId } from "@/lib/organization/service";
import NewEmailVerification from "@/modules/email/emails/auth/new-email-verification";
import { EmailCustomizationPreviewEmail } from "@/modules/email/emails/general/email-customization-preview-email";
import { getTranslate } from "@/tolgee/server";
import { render } from "@react-email/render";
@@ -86,6 +87,25 @@ export const sendEmail = async (emailData: SendEmailDataProps): Promise<boolean>
}
};
export const sendVerificationNewEmail = async (id: string, email: string): Promise<boolean> => {
try {
const t = await getTranslate();
const token = createEmailChangeToken(id, email);
const verifyLink = `${WEBAPP_URL}/verify-email-change?token=${encodeURIComponent(token)}`;
const html = await render(await NewEmailVerification({ verifyLink }));
return await sendEmail({
to: email,
subject: t("emails.verification_new_email_subject"),
html,
});
} catch (error) {
logger.error(error, "Error in sendVerificationNewEmail");
throw error;
}
};
export const sendVerificationEmail = async ({
id,
email,