Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test(examples): added server action email verification code #215

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions examples/next-typescript-starter/app/code/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { redirect } from 'next/navigation';
import { verifyEmailUpdate } from '../profile/UserProfile/verify-email-update';

export default async function VerifyCode({
searchParams
}: {
searchParams?: {[key: string]: string | string[] | undefined};
}) {
const code = searchParams?.code;
if (!code || typeof code !== 'string') redirect('/');
try {
await verifyEmailUpdate(code);
} catch (err) {
console.log(err);
return <div>ERR: {err?.toString()}</div>;
}

return <div>SUCCESS</div>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ import {getToken} from '@firebase/app-check';
import * as React from 'react';
import {useLoadingCallback} from 'react-loading-hook';

import {signOut} from 'firebase/auth';
import {useRouter} from 'next/navigation';
import {
sendEmailVerification,
signInWithCustomToken,
signOut
} from 'firebase/auth';
import {useRouter, useSearchParams} from 'next/navigation';
import {checkEmailVerification, logout} from '../../../api';
import {getAppCheck} from '../../../app-check';
import {Badge} from '../../../ui/Badge';
Expand All @@ -16,6 +20,8 @@ import {useAuth} from '../../auth/AuthContext';
import {getFirebaseAuth} from '../../auth/firebase';
import styles from './UserProfile.module.css';
import {incrementCounterUsingClientFirestore} from './user-counters';
import {verifyEmailUpdate} from './verify-email-update';
import {FormError} from '../../../ui/FormError';

interface UserProfileProps {
count: number;
Expand All @@ -24,6 +30,8 @@ interface UserProfileProps {

export function UserProfile({count, incrementCounter}: UserProfileProps) {
const router = useRouter();
const searchParams = useSearchParams();

const {user} = useAuth();
const [hasLoggedOut, setHasLoggedOut] = React.useState(false);
const [handleLogout, isLogoutLoading] = useLoadingCallback(async () => {
Expand Down Expand Up @@ -100,13 +108,44 @@ export function UserProfile({count, incrementCounter}: UserProfileProps) {
router.refresh();
});

const [handleAuthCode, isAuthCodeLoading, authCodeError] = useLoadingCallback(
async () => {
const code = window.prompt('Enter oobCode')

if (!code) {
return;
}

await verifyEmailUpdate(code);
router.refresh();
}
);

const [handleVerification, isVerificationLoading, verificationError] =
useLoadingCallback(async () => {
if (!user) {
throw new Error('No access');
}

//https://next-firebase-auth-edge-demo.firebaseapp.com/__/auth/action?mode=resetPassword&oobCode=&lang=en
const credential = await signInWithCustomToken(
getFirebaseAuth(),
user.customToken
);
await sendEmailVerification(credential.user, {
url: `http://localhost/profile?code=code`
});
});

let [isIncrementCounterActionPending, startTransition] =
React.useTransition();

if (!user) {
return null;
}

const error = authCodeError ?? verificationError;

const isIncrementLoading =
isIncrementCounterApiLoading ||
isIncrementCounterActionPending ||
Expand Down Expand Up @@ -142,13 +181,28 @@ export function UserProfile({count, incrementCounter}: UserProfileProps) {
<h5>Custom claims</h5>
<pre>{JSON.stringify(user.customClaims, undefined, 2)}</pre>
</div>
{error && <FormError>{error.message}</FormError>}
<Button
loading={isClaimsLoading}
disabled={isClaimsLoading}
onClick={handleClaims}
>
Refresh custom user claims
</Button>
<Button
loading={isVerificationLoading}
disabled={isVerificationLoading}
onClick={handleVerification}
>
Send verification email
</Button>
<Button
loading={isAuthCodeLoading}
disabled={isAuthCodeLoading}
onClick={handleAuthCode}
>
Verify code
</Button>
{process.env.NEXT_PUBLIC_FIREBASE_APP_CHECK_KEY && (
<Button
onClick={handleAppCheck}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'use server'

import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { refreshServerCookies } from "next-firebase-auth-edge/lib/next/cookies";
import { applyActionCode, checkActionCode, sendEmailVerification } from "firebase/auth";
import { getTokens } from "next-firebase-auth-edge";
import { getFirebaseAuth } from "../../auth/firebase";
import { authConfig } from "../../../config/server-config";

export const verifyEmailUpdate = async (code: string) => {
if (!code) throw new Error("No code provided");

const res = await checkActionCode(getFirebaseAuth(), code);

if (!res.data.email && !res.data.previousEmail)
throw new Error("Wrong action code for this operation");

await applyActionCode(getFirebaseAuth(), code);

const auth = await getTokens(cookies(), authConfig);
if (!auth) return redirect("/sign-in");
else {
await refreshServerCookies(
cookies(),
// https://github.com/vercel/next.js/discussions/63236
new Headers(headers()),
authConfig
);
return true;
}
};
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
'use client';

import * as React from 'react';
import {sendPasswordResetEmail} from 'firebase/auth';
import {
sendPasswordResetEmail
} from 'firebase/auth';
import Link from 'next/link';
import {useLoadingCallback} from 'react-loading-hook';
import {getFirebaseAuth} from '../auth/firebase';
import {Button} from '../../ui/Button';
import {FormError} from '../../ui/FormError';
import {Input} from '../../ui/Input';
import {MainTitle} from '../../ui/MainTitle';
import {appendRedirectParam} from '../shared/redirect';
import {useRedirectParam} from '../shared/useRedirectParam';
import * as React from 'react';
import { useLoadingCallback } from 'react-loading-hook';
import { Button } from '../../ui/Button';
import { FormError } from '../../ui/FormError';
import { Input } from '../../ui/Input';
import { MainTitle } from '../../ui/MainTitle';
import { getFirebaseAuth } from '../auth/firebase';
import { appendRedirectParam } from '../shared/redirect';
import { useRedirectParam } from '../shared/useRedirectParam';
import styles from './ResetPasswordPage.module.css';

export function ResetPasswordPage() {
Expand All @@ -25,6 +27,7 @@ export function ResetPasswordPage() {
const auth = getFirebaseAuth();
setIsSent(false);
await sendPasswordResetEmail(auth, email);

setEmail('');
setIsSent(true);
}
Expand Down
2 changes: 1 addition & 1 deletion examples/next-typescript-starter/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"firebase": "^10.4.0",
"firebase-admin": "^11.10.1",
"next": "14.2.3",
"next-firebase-auth-edge": "1.6.1",
"next-firebase-auth-edge": "1.6.2",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-loading-hook": "^1.0.0",
Expand Down
8 changes: 4 additions & 4 deletions examples/next-typescript-starter/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1619,10 +1619,10 @@ nanoid@^3.3.6:
resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.6.tgz#443380c856d6e9f9824267d960b4236ad583ea4c"
integrity sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==

next-firebase-auth-edge@1.6.1:
version "1.6.1"
resolved "https://registry.yarnpkg.com/next-firebase-auth-edge/-/next-firebase-auth-edge-1.6.1.tgz#62895cf9ad209938f3a8d2066c410327258d9096"
integrity sha512-F/MQrhqMXFQI7eReBNnors+LVKX47Hd07ZSarZIa6FxiyBahVtahI413lnBFjMO1AWyEx15nBZ5R5e0JCeodug==
next-firebase-auth-edge@1.6.2:
version "1.6.2"
resolved "https://registry.yarnpkg.com/next-firebase-auth-edge/-/next-firebase-auth-edge-1.6.2.tgz#31095119d344c4582a3f238bcf70370caa00f1ea"
integrity sha512-beRcgzxU8nvJ5grUYFRcgECr9pLzT5MaTSxi+yRZJsbYnYPbWZSoh0PmXB+WiDGAYOoWYLyerSSWmuH+YSKdsQ==
dependencies:
cookie "^0.5.0"
encoding "^0.1.13"
Expand Down
Loading