Skip to content

Instantly share code, notes, and snippets.

@perkinsjr
Created June 8, 2023 12:05
Show Gist options
  • Save perkinsjr/671a16244959e745f393f231705f5796 to your computer and use it in GitHub Desktop.
Save perkinsjr/671a16244959e745f393f231705f5796 to your computer and use it in GitHub Desktop.
Example of MFA Creation in a custom flow.
import { useUser } from "@clerk/nextjs";
import { type NextPage } from "next";
import { useState } from "react";
import QRCode from "react-qr-code";
const MFACreator: NextPage = () => {
const [qrUri, setQRURI] = useState("");
const [readyToVerify, setReadyToVerify] = useState(false);
const [verified, setVerified] = useState(false);
const [code, setCode] = useState("");
const [backupCodes, setBackUpCodes] = useState([]);
const { user, isLoaded, isSignedIn } = useUser();
if (!isLoaded || !isSignedIn) return null;
const createMFAForUser = async (e) => {
e.preventDefault();
const MFA = await user.createTOTP();
setQRURI(MFA.uri);
};
const verifyMFAForUser = async (e) => {
e.preventDefault();
const MFA = await user?.verifyTOTP({
code: code,
});
setVerified(true);
setBackUpCodes(MFA.backupCodes);
};
return (
<>
{!qrUri && (
<>
<p>Click the button to create a new MFA</p>
<button onClick={createMFAForUser}>Click me</button>
</>
)}
{qrUri && (
<>
<p>Scan the QR code below with your authenticator app</p>{" "}
<QRCode value={qrUri} />
<button onClick={() => setReadyToVerify(true)}>
Ready to Verify
</button>{" "}
</>
)}
{readyToVerify && (
<>
<p>Enter the code from your authenticator app</p>
<input
value={code}
onChange={(e) => {
setCode(e.target.value);
}}
type="text"
/>
<button onClick={verifyMFAForUser}>Verify</button>
</>
)}
{verified && (
<>
<p>Verified! here are your back up codes</p>{" "}
{backupCodes.map((code) => (
<p key={code}>{code}</p>
))}
</>
)}
</>
);
};
export default MFACreator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment