From 8358c330a20b0ad14ad0b93580df438d11a9de37 Mon Sep 17 00:00:00 2001 From: Yashovardhan Agrawal Date: Sun, 26 Jan 2025 16:44:05 +0530 Subject: [PATCH] Add logout from auth0 --- .../mpc-core-kit-rn-auth0/App.tsx | 267 +++++++++++------- .../mpc-core-kit-rn-expo-auth0/App.tsx | 10 +- 2 files changed, 170 insertions(+), 107 deletions(-) diff --git a/mpc-core-kit-react-native/mpc-core-kit-rn-auth0/App.tsx b/mpc-core-kit-react-native/mpc-core-kit-rn-auth0/App.tsx index 5a7d8412..54084309 100644 --- a/mpc-core-kit-react-native/mpc-core-kit-rn-auth0/App.tsx +++ b/mpc-core-kit-react-native/mpc-core-kit-rn-auth0/App.tsx @@ -1,9 +1,9 @@ -import "./globals"; -import "@ethersproject/shims"; +import './globals'; +import '@ethersproject/shims'; -import { Point, secp256k1 } from "@tkey/common-types"; -import { CHAIN_NAMESPACES } from "@web3auth/base"; -import { EthereumSigningProvider } from "@web3auth/ethereum-mpc-provider"; +import {Point, secp256k1} from '@tkey/common-types'; +import {CHAIN_NAMESPACES} from '@web3auth/base'; +import {EthereumSigningProvider} from '@web3auth/ethereum-mpc-provider'; // IMP START - Quick Start import { Bridge, @@ -18,36 +18,45 @@ import { TssDklsLib, TssShareType, WEB3AUTH_NETWORK, -} from "@web3auth/react-native-mpc-core-kit"; +} from '@web3auth/react-native-mpc-core-kit'; // IMP END - Quick Start -import { BN } from "bn.js"; -import { ethers } from "ethers"; +import {BN} from 'bn.js'; +import {ethers} from 'ethers'; import EncryptedStorage from 'react-native-encrypted-storage'; -import React, { useEffect, useState } from "react"; -import { ActivityIndicator, Button, Dimensions, ScrollView, StyleSheet, Text, TextInput, View } from "react-native"; +import React, {useEffect, useState} from 'react'; +import { + ActivityIndicator, + Button, + Dimensions, + ScrollView, + StyleSheet, + Text, + TextInput, + View, +} from 'react-native'; // IMP START - Auth Provider Login -import { Auth0Provider, useAuth0 } from "react-native-auth0"; +import {Auth0Provider, useAuth0} from 'react-native-auth0'; // IMP END - Auth Provider Login - // IMP START - Dashboard Registration -const web3AuthClientId = "BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ"; // get from https://dashboard.web3auth.io +const web3AuthClientId = + 'BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ'; // get from https://dashboard.web3auth.io // IMP END - Dashboard Registration // IMP START - Verifier Creation -const verifier = "w3a-auth0-demo"; +const verifier = 'w3a-auth0-demo'; // IMP END - Verifier Creation // IMP START - Chain Config const chainConfig = { chainNamespace: CHAIN_NAMESPACES.EIP155, - chainId: "0xaa36a7", // Please use 0x1 for Mainnet - rpcTarget: "https://rpc.ankr.com/eth_sepolia", - displayName: "Ethereum Sepolia Testnet", - blockExplorerUrl: "https://sepolia.etherscan.io/", - blockExplorer: "https://sepolia.etherscan.io/", - ticker: "ETH", - tickerName: "Ethereum", + chainId: '0xaa36a7', // Please use 0x1 for Mainnet + rpcTarget: 'https://rpc.ankr.com/eth_sepolia', + displayName: 'Ethereum Sepolia Testnet', + blockExplorerUrl: 'https://sepolia.etherscan.io/', + blockExplorer: 'https://sepolia.etherscan.io/', + ticker: 'ETH', + tickerName: 'Ethereum', }; // IMP END - Chain Config @@ -66,24 +75,26 @@ const coreKitInstance = new mpclib.Web3AuthMPCCoreKitRN({ web3AuthClientId, web3AuthNetwork: WEB3AUTH_NETWORK.MAINNET, // setupProviderOnInit: false, // needed to skip the provider setup - uxMode: "react-native", + uxMode: 'react-native', tssLib: TssDklsLib, // tss lib bridge for react native manualSync: true, // This is the recommended approach storage: asyncStorageKey, // Add the storage property }); // Setup provider for EVM Chain -const evmProvider = new EthereumSigningProvider({ config: { chainConfig } }); +const evmProvider = new EthereumSigningProvider({config: {chainConfig}}); evmProvider.setupProvider(makeEthereumSigner(coreKitInstance)); // IMP END - SDK Initialization function Home() { const [loading, setLoading] = useState(false); const [bridgeReady, setBridgeReady] = useState(false); - const [consoleUI, setConsoleUI] = useState(""); - const [coreKitStatus, setCoreKitStatus] = useState(COREKIT_STATUS.NOT_INITIALIZED); - const [backupFactorKey, setBackupFactorKey] = useState(""); - const [mnemonicFactor, setMnemonicFactor] = useState(""); + const [consoleUI, setConsoleUI] = useState(''); + const [coreKitStatus, setCoreKitStatus] = useState( + COREKIT_STATUS.NOT_INITIALIZED, + ); + const [backupFactorKey, setBackupFactorKey] = useState(''); + const [mnemonicFactor, setMnemonicFactor] = useState(''); const uiConsole = (...args: any) => { setConsoleUI(`${JSON.stringify(args || {}, null, 2)}\n\n\n\n${consoleUI}`); @@ -98,7 +109,7 @@ function Home() { await coreKitInstance.init(); // IMP END - SDK Initialization } catch (error: any) { - uiConsole(error.message, "mounted caught"); + uiConsole(error.message, 'mounted caught'); } setCoreKitStatus(coreKitInstance.status); }; @@ -106,16 +117,16 @@ function Home() { } }, [bridgeReady]); - const { authorize, getCredentials } = useAuth0(); + const {authorize, getCredentials, clearSession} = useAuth0(); // IMP START - Auth Provider Login const signInWithAuth0 = async () => { try { await authorize( { - scope: "openid profile email", + scope: 'openid profile email', // connection: 'google-oauth2', - } + }, // { // customScheme: 'com.mpccorekitrnauth0', // }, @@ -136,19 +147,19 @@ function Home() { const login = async () => { try { if (!coreKitInstance) { - throw new Error("initiated to login"); + throw new Error('initiated to login'); } - setConsoleUI("Logging in"); + setConsoleUI('Logging in'); setLoading(true); // IMP START - Auth Provider Login const idToken = await signInWithAuth0(); // IMP END - Auth Provider Login - uiConsole("idToken", idToken); + uiConsole('idToken', idToken); - uiConsole("idToken", idToken); + uiConsole('idToken', idToken); if (!idToken) { - throw new Error("idToken is null or undefined"); + throw new Error('idToken is null or undefined'); } const parsedToken = parseToken(idToken); @@ -169,7 +180,7 @@ function Home() { // IMP START - Recover MFA Enabled Account if (coreKitInstance.status === COREKIT_STATUS.REQUIRED_SHARE) { uiConsole( - "required more shares, please enter your backup/ device factor key, or reset account [unrecoverable once reset, please use it with caution]" + 'required more shares, please enter your backup/ device factor key, or reset account [unrecoverable once reset, please use it with caution]', ); } // IMP END - Recover MFA Enabled Account @@ -183,20 +194,20 @@ function Home() { // IMP START - Recover MFA Enabled Account const inputBackupFactorKey = async () => { if (!coreKitInstance) { - throw new Error("coreKitInstance not found"); + throw new Error('coreKitInstance not found'); } if (!backupFactorKey) { - throw new Error("backupFactorKey not found"); + throw new Error('backupFactorKey not found'); } setLoading(true); - const factorKey = new BN(backupFactorKey, "hex"); + const factorKey = new BN(backupFactorKey, 'hex'); await coreKitInstance.inputFactorKey(factorKey); setCoreKitStatus(coreKitInstance.status); setLoading(false); if (coreKitInstance.status === COREKIT_STATUS.REQUIRED_SHARE) { uiConsole( - "required more shares even after inputing backup factor key, please enter your backup/ device factor key, or reset account [unrecoverable once reset, please use it with caution]" + 'required more shares even after inputing backup factor key, please enter your backup/ device factor key, or reset account [unrecoverable once reset, please use it with caution]', ); } }; @@ -205,20 +216,28 @@ function Home() { // IMP START - Enable Multi Factor Authentication const enableMFA = async () => { if (!coreKitInstance) { - throw new Error("coreKitInstance is not set"); + throw new Error('coreKitInstance is not set'); } setLoading(true); try { - setConsoleUI("Enabling MFA, please wait"); + setConsoleUI('Enabling MFA, please wait'); const factorKey = generateFactorKey(); - await coreKitInstance.enableMFA({ factorKey: factorKey.private, shareDescription: FactorKeyTypeShareDescription.SeedPhrase }); - const factorKeyMnemonic = keyToMnemonic(factorKey.private.toString("hex")); + await coreKitInstance.enableMFA({ + factorKey: factorKey.private, + shareDescription: FactorKeyTypeShareDescription.SeedPhrase, + }); + const factorKeyMnemonic = keyToMnemonic( + factorKey.private.toString('hex'), + ); - uiConsole("MFA enabled, device factor stored in local store, deleted hashed cloud key, your backup factor key: ", factorKeyMnemonic); + uiConsole( + 'MFA enabled, device factor stored in local store, deleted hashed cloud key, your backup factor key: ', + factorKeyMnemonic, + ); } catch (error: any) { - uiConsole("Error", error); + uiConsole('Error', error); } setLoading(false); @@ -227,10 +246,10 @@ function Home() { } }; // IMP END - Enable Multi Factor Authentication - + const keyDetails = async () => { if (!coreKitInstance) { - throw new Error("coreKitInstance not found"); + throw new Error('coreKitInstance not found'); } uiConsole(await coreKitInstance.getKeyDetails()); }; @@ -239,7 +258,7 @@ function Home() { try { const factorKey = await coreKitInstance.getDeviceFactor(); setBackupFactorKey(factorKey!); - uiConsole("Device factor: ", factorKey); + uiConsole('Device factor: ', factorKey); } catch (error: any) { uiConsole(error.message); } @@ -249,16 +268,16 @@ function Home() { const storeDeviceFactor = async () => { try { if (!coreKitInstance) { - throw new Error("coreKitInstance is not set"); + throw new Error('coreKitInstance is not set'); } setLoading(true); - uiConsole("export share type: ", TssShareType.DEVICE); + uiConsole('export share type: ', TssShareType.DEVICE); const factorKey = generateFactorKey(); await coreKitInstance.createFactor({ shareType: TssShareType.DEVICE, factorKey: factorKey.private, }); - uiConsole("Stored factor: ", factorKey); + uiConsole('Stored factor: ', factorKey); } catch (error: any) { uiConsole(error.message); } @@ -268,20 +287,22 @@ function Home() { // IMP START - Export Mnemonic Factor const createMnemonicFactor = async (): Promise => { if (!coreKitInstance) { - throw new Error("coreKitInstance is not set"); + throw new Error('coreKitInstance is not set'); } setLoading(true); - uiConsole("share type: ", TssShareType.RECOVERY); + uiConsole('share type: ', TssShareType.RECOVERY); const factorKey = generateFactorKey(); await coreKitInstance.createFactor({ shareType: TssShareType.RECOVERY, factorKey: factorKey.private, shareDescription: FactorKeyTypeShareDescription.SeedPhrase, }); - const factorKeyMnemonic = await keyToMnemonic(factorKey.private.toString("hex")); + const factorKeyMnemonic = await keyToMnemonic( + factorKey.private.toString('hex'), + ); setLoading(false); - uiConsole("New factor key mnemonic: ", factorKeyMnemonic); + uiConsole('New factor key mnemonic: ', factorKeyMnemonic); if (coreKitInstance.status === COREKIT_STATUS.LOGGED_IN) { await coreKitInstance.commitChanges(); } @@ -290,7 +311,7 @@ function Home() { const MnemonicToFactorKeyHex = async (mnemonic: string) => { if (!coreKitInstance) { - throw new Error("coreKitInstance is not set"); + throw new Error('coreKitInstance is not set'); } try { const factorKey = await mnemonicToKey(mnemonic); @@ -304,7 +325,9 @@ function Home() { // IMP START - Delete Factor const deleteFactor = async () => { let factorPub: string | undefined; - for (const [key, value] of Object.entries((await coreKitInstance.getKeyDetails()).shareDescriptions)) { + for (const [key, value] of Object.entries( + (await coreKitInstance.getKeyDetails()).shareDescriptions, + )) { if (value.length > 0) { const parsedData = JSON.parse(value[0]); if (parsedData.module === FactorKeyTypeShareDescription.SeedPhrase) { @@ -313,13 +336,17 @@ function Home() { } } if (factorPub) { - uiConsole("Deleting Mnemonic Factor, please wait...", "Factor Pub:", factorPub); + uiConsole( + 'Deleting Mnemonic Factor, please wait...', + 'Factor Pub:', + factorPub, + ); const pub = Point.fromSEC1(secp256k1, factorPub); await coreKitInstance.deleteFactor(pub); await coreKitInstance.commitChanges(); - uiConsole("Mnemonic Factor deleted"); + uiConsole('Mnemonic Factor deleted'); } else { - uiConsole("No Mnemonic factor found to delete"); + uiConsole('No Mnemonic factor found to delete'); } }; // IMP END - Delete Factor @@ -337,19 +364,25 @@ function Home() { await coreKitInstance.logout(); // IMP END - Logout setCoreKitStatus(coreKitInstance.status); + uiConsole('logged out from web3auth'); // Log out from Auth0 + try { + await clearSession(); + uiConsole('logged out from auth0'); + } catch (error: any) { + uiConsole('logout from auth0 unsuccessful', error.message); + } setLoading(false); - uiConsole("logged out from web3auth"); }; // IMP START - Blockchain Calls const getAccounts = async () => { if (!coreKitInstance) { - uiConsole("provider not initialized yet"); + uiConsole('provider not initialized yet'); return; } setLoading(true); - setConsoleUI("Getting account"); + setConsoleUI('Getting account'); // For ethers v5 // const ethersProvider = new ethers.providers.Web3Provider(this.provider); @@ -367,11 +400,11 @@ function Home() { const getBalance = async () => { if (!coreKitInstance) { - uiConsole("provider not initialized yet"); + uiConsole('provider not initialized yet'); return; } setLoading(true); - setConsoleUI("Fetching balance"); + setConsoleUI('Fetching balance'); // For ethers v5 // const ethersProvider = new ethers.providers.Web3Provider(this.provider); @@ -390,7 +423,7 @@ function Home() { // await ethersProvider.getBalance(address) // Balance is in wei // ); const balance = ethers.formatEther( - await ethersProvider.getBalance(address) // Balance is in wei + await ethersProvider.getBalance(address), // Balance is in wei ); setLoading(false); @@ -399,11 +432,11 @@ function Home() { const signMessage = async () => { if (!coreKitInstance) { - uiConsole("provider not initialized yet"); + uiConsole('provider not initialized yet'); return; } setLoading(true); - setConsoleUI("Signing message"); + setConsoleUI('Signing message'); // For ethers v5 // const ethersProvider = new ethers.providers.Web3Provider(this.provider); @@ -412,7 +445,7 @@ function Home() { // For ethers v5 // const signer = ethersProvider.getSigner(); const signer = await ethersProvider.getSigner(); - const originalMessage = "YOUR_MESSAGE"; + const originalMessage = 'YOUR_MESSAGE'; // Sign the message const signedMessage = await signer.signMessage(originalMessage); @@ -422,11 +455,11 @@ function Home() { const sendTransaction = async () => { if (!coreKitInstance) { - uiConsole("provider not initialized yet"); + uiConsole('provider not initialized yet'); return; } setLoading(true); - setConsoleUI("Sending transaction"); + setConsoleUI('Sending transaction'); // For ethers v5 // const ethersProvider = new ethers.providers.Web3Provider(this.provider); @@ -434,8 +467,8 @@ function Home() { const signer = await ethersProvider.getSigner(); - const destination = "0xeaA8Af602b2eDE45922818AE5f9f7FdE50cFa1A8"; - const amount = ethers.parseEther("0.005"); // Convert 1 ether to wei + const destination = '0xeaA8Af602b2eDE45922818AE5f9f7FdE50cFa1A8'; + const amount = ethers.parseEther('0.005'); // Convert 1 ether to wei // Submit transaction to the blockchain const tx = await signer.sendTransaction({ @@ -455,12 +488,12 @@ function Home() { // Resetting your account means clearing all the metadata associated with it from the metadata server // The key details will be deleted from our server and you will not be able to recover your account if (!coreKitInstance) { - throw new Error("coreKitInstance is not set"); + throw new Error('coreKitInstance is not set'); } setLoading(true); await coreKitInstance._UNSAFE_resetAccount(); - uiConsole("reset"); + uiConsole('reset'); if (coreKitInstance.status === COREKIT_STATUS.LOGGED_IN) { await coreKitInstance.commitChanges(); } @@ -480,7 +513,10 @@ function Home() {