Skip to content

Commit 28de26b

Browse files
committed
launchwalletservices and enableMFA fucntion added
1 parent a90e070 commit 28de26b

File tree

5 files changed

+185
-15
lines changed

5 files changed

+185
-15
lines changed

demo/rn-bare-example/App.tsx

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
1-
import React, {useEffect, useState} from 'react';
1+
import * as WebBrowser from '@toruslabs/react-native-web-browser';
2+
23
import {
3-
StyleSheet,
4-
Text,
5-
View,
64
Button,
7-
ScrollView,
85
Dimensions,
6+
ScrollView,
7+
StyleSheet,
8+
Text,
99
TextInput,
10+
View,
1011
} from 'react-native';
11-
import * as WebBrowser from '@toruslabs/react-native-web-browser';
12-
import EncryptedStorage from 'react-native-encrypted-storage';
12+
import React, { useEffect, useState } from 'react';
1313
import Web3Auth, {
14-
LOGIN_PROVIDER,
1514
IWeb3Auth,
15+
LOGIN_PROVIDER,
1616
OpenloginUserInfo,
1717
} from '@web3auth/react-native-sdk';
18+
19+
import EncryptedStorage from 'react-native-encrypted-storage';
1820
import RPC from './ethersRPC'; // for using ethers.js
1921

2022
const scheme = 'web3authrnbareexample'; // Or your desired app redirection scheme
@@ -27,7 +29,7 @@ export default function App() {
2729
const [key, setKey] = useState<string | undefined>('');
2830
const [console, setConsole] = useState<string>('');
2931
const [web3auth, setWeb3Auth] = useState<IWeb3Auth | null>(null);
30-
const [email, setEmail] = React.useState('[email protected]');
32+
const [email, setEmail] = React.useState('[email protected]');
3133

3234
const login = async () => {
3335
try {
@@ -75,6 +77,27 @@ export default function App() {
7577
}
7678
};
7779

80+
const enableMFA = async () => {
81+
if (!web3auth) {
82+
setConsole('Web3auth not initialized');
83+
return;
84+
}
85+
86+
setConsole('Enable MFA');
87+
await web3auth.enableMFA();
88+
uiConsole('MFA enabled')
89+
}
90+
91+
const launchWallerSerices = async () => {
92+
if (!web3auth) {
93+
setConsole('Web3auth not initialized');
94+
return;
95+
}
96+
97+
setConsole('Launch Wallet Services');
98+
await web3auth.launchWalletServices();
99+
}
100+
78101
useEffect(() => {
79102
const init = async () => {
80103
const auth = new Web3Auth(WebBrowser, EncryptedStorage, {
@@ -83,7 +106,7 @@ export default function App() {
83106
useCoreKitKey: false,
84107
loginConfig: {},
85108
enableLogging: true,
86-
buildEnv: 'development',
109+
buildEnv: 'testing',
87110
});
88111
setWeb3Auth(auth);
89112
await auth.init();
@@ -146,6 +169,8 @@ export default function App() {
146169
const loggedInView = (
147170
<View style={styles.buttonArea}>
148171
<Button title="Get User Info" onPress={() => uiConsole(userInfo)} />
172+
<Button title="Enable MFA" onPress={() => enableMFA()} />
173+
<Button title="launch Wallet Services" onPress={() => launchWallerSerices()} />
149174
<Button title="Get Chain ID" onPress={() => getChainId()} />
150175
<Button title="Get Accounts" onPress={() => getAccounts()} />
151176
<Button title="Get Balance" onPress={() => getBalance()} />
@@ -163,7 +188,7 @@ export default function App() {
163188
onChangeText={text => setEmail(text)}
164189
value={email}
165190
// eslint-disable-next-line react-native/no-inline-styles
166-
style={{padding: 10}}
191+
style={{ padding: 10 }}
167192
/>
168193
<Button title="Login with Web3Auth" onPress={login} />
169194
</View>

demo/rn-bare-example/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
"dependencies": {
1313
"@ethersproject/shims": "^5.7.0",
1414
"@toruslabs/react-native-web-browser": "^1.1.0",
15-
"@web3auth/react-native-sdk": "file:../../web3auth-react-native-sdk-5.0.0.tgz",
15+
"@web3auth/react-native-sdk": "file:../../web3auth-react-native-sdk-5.1.0.tgz",
1616
"ethers": "^5.7.2",
1717
"react": "18.2.0",
1818
"react-native": "0.71.8",

src/Web3Auth.ts

Lines changed: 121 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
import { OpenloginSessionManager } from "@toruslabs/openlogin-session-manager";
2-
import { BaseLoginParams, BUILD_ENV, jsonToBase64, OPENLOGIN_ACTIONS, OPENLOGIN_NETWORK, OpenloginSessionConfig } from "@toruslabs/openlogin-utils";
2+
import {
3+
BaseLoginParams,
4+
BUILD_ENV,
5+
jsonToBase64,
6+
MFA_LEVELS,
7+
OPENLOGIN_ACTIONS,
8+
OPENLOGIN_NETWORK,
9+
OpenloginSessionConfig,
10+
} from "@toruslabs/openlogin-utils";
311
import log from "loglevel";
412

513
import { InitializationError, LoginError } from "./errors";
@@ -88,7 +96,20 @@ class Web3Auth implements IWeb3Auth {
8896
private get baseUrl(): string {
8997
// testing and develop don't have versioning
9098
if (this.initParams.buildEnv === BUILD_ENV.DEVELOPMENT || this.initParams.buildEnv === BUILD_ENV.TESTING) return `${this.initParams.sdkUrl}`;
91-
return `${this.initParams.sdkUrl}/v6`;
99+
return `${this.initParams.sdkUrl}/v7`;
100+
}
101+
102+
private get walletSdkUrl(): string {
103+
const walletServicesVersion: string = "v1";
104+
let sdkUrl: string;
105+
if (this.initParams.buildEnv === BUILD_ENV.TESTING) {
106+
sdkUrl = "https://develop-wallet.web3auth.io";
107+
} else if (this.initParams.buildEnv === BUILD_ENV.STAGING) {
108+
sdkUrl = `https://staging-wallet.web3auth.io/${walletServicesVersion}`;
109+
} else {
110+
sdkUrl = `https://wallet.web3auth.io/${walletServicesVersion}`;
111+
}
112+
return sdkUrl;
92113
}
93114

94115
async init(): Promise<void> {
@@ -194,6 +215,104 @@ class Web3Auth implements IWeb3Auth {
194215
this._syncState({});
195216
}
196217

218+
async launchWalletServices(loginParams: SdkLoginParams, path: string | null = "wallet"): Promise<void> {
219+
if (!this.ready) throw InitializationError.notInitialized("Please call init first.");
220+
if (!this.sessionManager.sessionId) {
221+
throw new Error("user should be logged in.");
222+
}
223+
224+
const dataObject: OpenloginSessionConfig = {
225+
actionType: OPENLOGIN_ACTIONS.LOGIN,
226+
options: this.initParams,
227+
params: {
228+
...loginParams,
229+
redirectUrl: loginParams.redirectUrl || this.initParams.redirectUrl,
230+
},
231+
};
232+
233+
const url = `${this.walletSdkUrl}/${path}`;
234+
log.debug(`[Web3Auth] config passed: ${JSON.stringify(dataObject)}`);
235+
const loginId = await this.getLoginId(dataObject);
236+
237+
const configParams: BaseLoginParams = {
238+
loginId,
239+
sessionNamespace: "",
240+
};
241+
242+
const loginUrl = constructURL({
243+
baseURL: url,
244+
hash: { b64Params: jsonToBase64(configParams) },
245+
});
246+
247+
this.webBrowser.openAuthSessionAsync(loginUrl, dataObject.params.redirectUrl);
248+
}
249+
250+
async enableMFA(): Promise<void> {
251+
log.debug("enableMFA_1 starts");
252+
if (!this.ready) throw InitializationError.notInitialized("Please call init first.");
253+
if (!this.sessionManager.sessionId) {
254+
throw new Error("user should be logged in.");
255+
}
256+
257+
const loginParams: SdkLoginParams = {
258+
loginProvider: this.state.userInfo?.typeOfLogin,
259+
mfaLevel: MFA_LEVELS.MANDATORY,
260+
extraLoginOptions: {
261+
login_hint: this.state.userInfo?.verifierId,
262+
},
263+
redirectUrl: this.initParams.redirectUrl,
264+
};
265+
266+
log.debug("enableMFA_2 starts");
267+
const dataObject: OpenloginSessionConfig = {
268+
actionType: OPENLOGIN_ACTIONS.ENABLE_MFA,
269+
options: this.initParams,
270+
params: {
271+
...loginParams,
272+
redirectUrl: loginParams.redirectUrl || this.initParams.redirectUrl,
273+
},
274+
sessionId: this.sessionManager.sessionId,
275+
};
276+
277+
log.debug("enableMFA_3 starts");
278+
const result = await this.openloginHandler(`${this.baseUrl}/start`, dataObject);
279+
280+
log.debug("enableMFA_4", result);
281+
if (result.type !== "success" || !result.url) {
282+
log.error(`[Web3Auth] login flow failed with error type ${result.type}`);
283+
throw new Error(`login flow failed with error type ${result.type}`);
284+
}
285+
286+
log.debug("enableMFA_5");
287+
const { sessionId, sessionNamespace, error } = extractHashValues(result.url);
288+
if (error || !sessionId) {
289+
throw LoginError.loginFailed(error || "SessionId is missing");
290+
}
291+
292+
log.debug("enableMFA_6");
293+
if (sessionId) {
294+
await this.keyStore.set("sessionId", sessionId);
295+
this.sessionManager.sessionId = sessionId;
296+
this.sessionManager.sessionNamespace = sessionNamespace || "";
297+
}
298+
299+
const sessionData = await this._authorizeSession();
300+
301+
if (sessionData.userInfo?.dappShare.length > 0) {
302+
const verifier = sessionData.userInfo?.aggregateVerifier || sessionData.userInfo?.verifier;
303+
await this.keyStore.set(verifier, sessionData.userInfo?.dappShare);
304+
}
305+
306+
this._syncState({
307+
privKey: sessionData.privKey,
308+
coreKitKey: sessionData.coreKitKey,
309+
coreKitEd25519PrivKey: sessionData.coreKitEd25519PrivKey,
310+
ed25519PrivKey: sessionData.ed25519PrivKey,
311+
sessionId: sessionData.sessionId,
312+
userInfo: sessionData.userInfo,
313+
});
314+
}
315+
197316
public userInfo(): State["userInfo"] {
198317
if (this.privKey) {
199318
const storeData = this.state.userInfo;

src/types/interface.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,19 @@ export interface IWeb3Auth {
5555
userInfo: () => State["userInfo"];
5656
}
5757

58+
export type SessionResponse = {
59+
sessionId?: string;
60+
};
61+
62+
export type ChainConfig = {
63+
decimals: number,
64+
blockExplorerUrl?: String,
65+
chainId: String,
66+
displayName?: String,
67+
logo?: String,
68+
rpcTarget: String,
69+
ticker: String,
70+
tickerName?: String
71+
}
72+
5873
export { BUILD_ENV, OPENLOGIN_NETWORK, LANGUAGES, LOGIN_PROVIDER, SUPPORTED_KEY_CURVES, MFA_FACTOR, MFA_LEVELS, THEME_MODES };

src/utils.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1+
import { base64toJSON } from "@toruslabs/openlogin-utils";
2+
import log from "loglevel";
13
import { URL } from "react-native-url-polyfill";
24

5+
import { SessionResponse } from "./index";
6+
37
export function constructURL(params: { baseURL: string; query?: Record<string, unknown>; hash?: Record<string, unknown> }): string {
48
const { baseURL, query, hash } = params;
59

@@ -38,10 +42,17 @@ export function extractHashValues(url: string): { sessionId: string | null; sess
3842
});
3943

4044
// Get the values of sessionId and sessionNamespace
41-
const sessionId = params.sessionId || null;
4245
const sessionNamespace = params.sessionNamespace || null;
4346
const error = params.error || null;
4447

48+
const b64Params = params.b64Params || null;
49+
log.debug("b64Params", b64Params);
50+
const sessionResponse: SessionResponse = base64toJSON(b64Params);
51+
log.debug("sessionResponse", sessionResponse);
52+
const sessionId = sessionResponse.sessionId || null;
53+
log.debug("sessionId", sessionId);
54+
log.debug("sessionId", sessionId);
55+
4556
return { sessionId, sessionNamespace, error };
4657
}
4758

0 commit comments

Comments
 (0)