Skip to content

Commit d9dc949

Browse files
committed
Updated FireBase example, but isn't working
1 parent 65c2f88 commit d9dc949

File tree

2 files changed

+142
-65
lines changed

2 files changed

+142
-65
lines changed

android-firebase-example/app/build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ dependencies {
3737
implementation 'com.google.android.material:material:1.7.0'
3838
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
3939
implementation 'com.google.code.gson:gson:2.9.1'
40-
implementation 'com.github.web3auth:web3auth-android-sdk:9.0.4'
40+
implementation 'com.github.web3auth:web3auth-android-sdk:10.0.0'
4141
implementation 'org.web3j:core:4.8.7-android'
4242
implementation platform('com.google.firebase:firebase-bom:31.0.2')
4343
implementation 'com.google.firebase:firebase-auth-ktx'

android-firebase-example/app/src/main/java/com/sbz/web3authdemoapp/MainActivity.kt

Lines changed: 141 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
package com.sbz.web3authdemoapp
22

3-
import android.content.ContentValues.TAG
43
import android.content.Intent
5-
import android.net.Uri
64
import android.os.Bundle
75
import android.util.Log
86
import android.view.View
@@ -19,6 +17,7 @@ import com.google.gson.Gson
1917
import com.google.gson.JsonArray
2018
import com.web3auth.core.Web3Auth
2119
import com.web3auth.core.types.*
20+
import org.torusresearch.fetchnodedetails.types.Web3AuthNetwork
2221
import org.web3j.crypto.Credentials
2322
import org.web3j.crypto.Hash
2423
import org.web3j.crypto.RawTransaction
@@ -47,45 +46,53 @@ class MainActivity : AppCompatActivity() {
4746
private val rpcUrl = "https://1rpc.io/sepolia"
4847

4948
private val gson = Gson()
49+
companion object {
50+
private const val TAG = "MainActivity_Web3Auth"
51+
}
5052

5153
override fun onCreate(savedInstanceState: Bundle?) {
5254
super.onCreate(savedInstanceState)
5355
setContentView(R.layout.activity_main)
54-
auth = Firebase.auth
56+
try {
57+
auth = Firebase.auth
58+
} catch (e: Exception) {
59+
Log.e(TAG, "Failed to initialize Firebase Auth", e)
60+
Toast.makeText(this, "Failed to initialize Firebase: ${e.message}",
61+
Toast.LENGTH_LONG).show()
62+
return
63+
}
5564
web3 = Web3j.build(HttpService(rpcUrl))
5665

5766
web3Auth = Web3Auth(
5867
Web3AuthOptions(
5968
clientId = getString(R.string.web3auth_project_id), // pass over your Web3Auth Client ID from Developer Dashboard
60-
network = Network.SAPPHIRE_MAINNET, // pass over the network you want to use (MAINNET or TESTNET or CYAN, AQUA, SAPPHIRE_MAINNET or SAPPHIRE_TESTNET)
61-
buildEnv = BuildEnv.PRODUCTION,
62-
redirectUrl = Uri.parse("com.sbz.web3authdemoapp://auth"), // your app's redirect URL
69+
web3AuthNetwork = Web3AuthNetwork.SAPPHIRE_MAINNET, // pass over the network you want to use
70+
redirectUrl = "com.sbz.web3authdemoapp://auth", // your app's redirect URL
71+
6372
// Optional parameters
64-
whiteLabel = WhiteLabelData(
65-
"Web3Auth Android FireBase Example",
66-
null,
67-
"https://cryptologos.cc/logos/ethereum-eth-logo.png",
68-
"https://cryptologos.cc/logos/ethereum-eth-logo.png",
69-
Language.EN,
70-
ThemeModes.LIGHT,
71-
true,
72-
hashMapOf(
73-
"primary" to "#eb5424"
74-
)
75-
),
76-
mfaSettings = MfaSettings(
77-
deviceShareFactor = MfaSetting(true, 1, true),
78-
socialBackupFactor = MfaSetting(true, 2, true),
79-
passwordFactor = MfaSetting(true, 3, false),
80-
backUpShareFactor = MfaSetting(true, 4, false),
73+
walletServicesConfig = WalletServicesConfig(
74+
whiteLabel = WhiteLabelData(
75+
"Web3Auth Android FireBase Example",
76+
null,
77+
"https://cryptologos.cc/logos/ethereum-eth-logo.png",
78+
"https://cryptologos.cc/logos/ethereum-eth-logo.png",
79+
Language.EN,
80+
ThemeModes.LIGHT,
81+
true,
82+
hashMapOf(
83+
"primary" to "#eb5424"
84+
)
85+
),
86+
8187
),
82-
loginConfig = hashMapOf("jwt" to LoginConfigItem(
83-
verifier = "w3a-firebase-demo",
84-
typeOfLogin = TypeOfLogin.JWT,
85-
name = "Firebase login",
86-
clientId = getString(R.string.web3auth_project_id)
87-
))
88-
), context = this
88+
authConnectionConfig = listOf(
89+
AuthConnectionConfig(
90+
authConnection = AuthConnection.CUSTOM,
91+
authConnectionId = "w3a-firebase-demo",
92+
clientId = getString(R.string.web3auth_project_id)
93+
)
94+
)
95+
), this
8996
)
9097

9198
// Handle user signing in when app is not alive
@@ -96,10 +103,10 @@ class MainActivity : AppCompatActivity() {
96103
sessionResponse.whenComplete { _, error ->
97104
if (error == null) {
98105
reRender()
99-
println("PrivKey: " + web3Auth.getPrivkey())
100-
println("ed25519PrivKey: " + web3Auth.getEd25519PrivKey())
106+
println("PrivKey: " + web3Auth.getPrivateKey())
107+
println("ed25519PrivKey: " + web3Auth.getEd25519PrivateKey())
101108
println("Web3Auth UserInfo" + web3Auth.getUserInfo())
102-
credentials = Credentials.create(web3Auth.getPrivkey())
109+
credentials = Credentials.create(web3Auth.getPrivateKey())
103110

104111
} else {
105112
Log.d("MainActivity_Web3Auth", error.message ?: "Something went wrong")
@@ -157,37 +164,111 @@ class MainActivity : AppCompatActivity() {
157164
}
158165

159166
private fun signIn() {
160-
auth.signInWithEmailAndPassword("[email protected]", "Android@Web3Auth")
161-
.addOnCompleteListener(this) { task ->
167+
try {
168+
if (!::auth.isInitialized) {
169+
Log.e(TAG, "Firebase Auth is not initialized")
170+
Toast.makeText(this, "Firebase Auth is not initialized",
171+
Toast.LENGTH_SHORT).show()
172+
return
173+
}
174+
Log.d(TAG, "Attempting Firebase sign in...")
175+
auth.signInWithEmailAndPassword("[email protected]", "Android@Web3Auth")
176+
.addOnCompleteListener(this) { task ->
162177
if (task.isSuccessful) {
163178
// Sign in success, update UI with the signed-in user's information
164179
Log.d(TAG, "signInWithEmail:success")
165180
val user = auth.currentUser
166-
user!!.getIdToken(true).addOnSuccessListener { result ->
167-
val idToken = result.token
168-
//Do whatever
169-
Log.d(TAG, "GetTokenResult result = $idToken")
170-
val selectedLoginProvider = Provider.JWT
171-
val loginParams = LoginParams(selectedLoginProvider, extraLoginOptions = ExtraLoginOptions(domain= "firebase", id_token = idToken, verifierIdField = "sub"))
172-
val loginCompletableFuture: CompletableFuture<Web3AuthResponse> = web3Auth.login(loginParams)
173-
174-
loginCompletableFuture.whenComplete { _, error ->
175-
if (error == null) {
176-
credentials = Credentials.create(web3Auth.getPrivkey())
177-
reRender()
178-
} else {
179-
Log.d("MainActivity_Web3Auth", error.message ?: "Something went wrong" )
181+
if (user != null) {
182+
user.getIdToken(true).addOnSuccessListener { result ->
183+
try {
184+
val idToken = result.token
185+
//Do whatever
186+
Log.d(TAG, "GetTokenResult result = $idToken")
187+
if (idToken != null) {
188+
if (!::web3Auth.isInitialized) {
189+
Log.e(TAG, "Web3Auth is not initialized")
190+
if (!isFinishing && !isDestroyed) {
191+
Toast.makeText(this@MainActivity, "Web3Auth is not initialized",
192+
Toast.LENGTH_SHORT).show()
193+
}
194+
return@addOnSuccessListener
195+
}
196+
val loginParams = LoginParams(
197+
authConnection = AuthConnection.CUSTOM,
198+
authConnectionId = "w3a-firebase-demo",
199+
idToken = idToken
200+
)
201+
val loginCompletableFuture: CompletableFuture<Web3AuthResponse> = web3Auth.connectTo(loginParams)
202+
203+
loginCompletableFuture.whenComplete { _, error ->
204+
runOnUiThread {
205+
if (isFinishing || isDestroyed) {
206+
Log.w(TAG, "Activity is finishing/destroyed, skipping UI update")
207+
return@runOnUiThread
208+
}
209+
if (error == null) {
210+
credentials = Credentials.create(web3Auth.getPrivateKey())
211+
reRender()
212+
} else {
213+
Log.e(TAG, "Web3Auth login failed", error)
214+
error.printStackTrace()
215+
Toast.makeText(this@MainActivity, "Web3Auth login failed: ${error.message}",
216+
Toast.LENGTH_SHORT).show()
217+
}
218+
}
219+
}
220+
} else {
221+
Log.e(TAG, "ID token is null")
222+
if (!isFinishing && !isDestroyed) {
223+
Toast.makeText(this@MainActivity, "Failed to get ID token.",
224+
Toast.LENGTH_SHORT).show()
225+
}
226+
}
227+
} catch (e: Exception) {
228+
Log.e(TAG, "Exception in getIdToken success callback", e)
229+
e.printStackTrace()
230+
if (!isFinishing && !isDestroyed) {
231+
Toast.makeText(this@MainActivity, "Error processing ID token: ${e.message}",
232+
Toast.LENGTH_SHORT).show()
233+
}
234+
}
235+
}.addOnFailureListener { exception ->
236+
Log.e(TAG, "Failed to get ID token", exception)
237+
exception.printStackTrace()
238+
if (!isFinishing && !isDestroyed) {
239+
Toast.makeText(this@MainActivity, "Failed to get ID token: ${exception.message}",
240+
Toast.LENGTH_SHORT).show()
180241
}
181242
}
243+
} else {
244+
Log.e(TAG, "Current user is null after successful sign in")
245+
if (!isFinishing && !isDestroyed) {
246+
Toast.makeText(this@MainActivity, "User is null after sign in.",
247+
Toast.LENGTH_SHORT).show()
248+
}
182249
}
183250
} else {
184251
// If sign in fails, display a message to the user.
185-
Log.w(TAG, "signInWithEmail:failure", task.exception)
186-
Toast.makeText(baseContext, "Authentication failed.",
187-
Toast.LENGTH_SHORT).show()
188-
252+
val exception = task.exception
253+
Log.e(TAG, "signInWithEmail:failure", exception)
254+
val errorMessage = when {
255+
exception?.message?.contains("no user record") == true ->
256+
"User does not exist. Please create the user in Firebase Console first."
257+
exception?.message?.contains("password") == true ->
258+
"Invalid password."
259+
else ->
260+
"Authentication failed: ${exception?.message ?: "Unknown error"}"
261+
}
262+
Toast.makeText(this@MainActivity, errorMessage,
263+
Toast.LENGTH_LONG).show()
189264
}
190265
}
266+
} catch (e: Exception) {
267+
Log.e(TAG, "Exception during sign in", e)
268+
e.printStackTrace()
269+
Toast.makeText(this, "Sign in error: ${e.message}",
270+
Toast.LENGTH_SHORT).show()
271+
}
191272
}
192273

193274
private fun signOut() {
@@ -221,19 +302,15 @@ class MainActivity : AppCompatActivity() {
221302
}
222303

223304
private fun prepareLoginParams(result: GetTokenResult): LoginParams {
224-
val selectedLoginProvider = Provider.JWT
225-
return LoginParams(selectedLoginProvider, extraLoginOptions = ExtraLoginOptions(domain= "firebase", id_token = result.token, verifierIdField = "sub"))
305+
return LoginParams(
306+
authConnection = AuthConnection.CUSTOM,
307+
authConnectionId = "w3a-firebase-demo",
308+
idToken = result.token
309+
)
226310
}
227311

228312
private fun launchWalletServices() {
229-
val completableFuture = web3Auth.launchWalletServices(
230-
ChainConfig(
231-
chainId = "0x1",
232-
rpcTarget = "https://1rpc.io/eth",
233-
ticker = "ETH",
234-
chainNamespace = ChainNamespace.EIP155
235-
)
236-
)
313+
val completableFuture = web3Auth.showWalletUI()
237314

238315
completableFuture.whenComplete{_, error ->
239316
if(error == null) {
@@ -325,7 +402,7 @@ class MainActivity : AppCompatActivity() {
325402
var key: String? = null
326403
var userInfo: UserInfo? = null
327404
try {
328-
key = web3Auth.getPrivkey()
405+
key = web3Auth.getPrivateKey()
329406
userInfo = web3Auth.getUserInfo()
330407
} catch (ex: Exception) {
331408
print(ex)

0 commit comments

Comments
 (0)