Created
June 8, 2023 12:05
-
-
Save perkinsjr/671a16244959e745f393f231705f5796 to your computer and use it in GitHub Desktop.
Example of MFA Creation in a custom flow.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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