/
AnonymousAuthActivity.kt
91 lines (82 loc) · 3.01 KB
/
AnonymousAuthActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.google.firebase.quickstart.auth.kotlin
import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.google.firebase.auth.EmailAuthProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.auth
import com.google.firebase.Firebase
/**
* Activity to demonstrate anonymous login and account linking (with an email/password account).
*/
class AnonymousAuthActivity : Activity() {
// [START declare_auth]
private lateinit var auth: FirebaseAuth
// [END declare_auth]
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// [START initialize_auth]
// Initialize Firebase Auth
auth = Firebase.auth
// [END initialize_auth]
}
// [START on_start_check_user]
public override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updateUI(currentUser)
}
// [END on_start_check_user]
private fun signInAnonymously() {
// [START signin_anonymously]
auth.signInAnonymously()
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInAnonymously:success")
val user = auth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInAnonymously:failure", task.exception)
Toast.makeText(
baseContext,
"Authentication failed.",
Toast.LENGTH_SHORT,
).show()
updateUI(null)
}
}
// [END signin_anonymously]
}
private fun linkAccount() {
// Create EmailAuthCredential with email and password
val credential = EmailAuthProvider.getCredential("", "")
// [START link_credential]
auth.currentUser!!.linkWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Log.d(TAG, "linkWithCredential:success")
val user = task.result?.user
updateUI(user)
} else {
Log.w(TAG, "linkWithCredential:failure", task.exception)
Toast.makeText(
baseContext,
"Authentication failed.",
Toast.LENGTH_SHORT,
).show()
updateUI(null)
}
}
// [END link_credential]
}
private fun updateUI(user: FirebaseUser?) {
}
companion object {
private const val TAG = "AnonymousAuth"
}
}