/
PhoneAuthActivity.kt
360 lines (316 loc) · 14.2 KB
/
PhoneAuthActivity.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package com.google.firebase.quickstart.auth.kotlin
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.google.firebase.FirebaseException
import com.google.firebase.FirebaseTooManyRequestsException
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.PhoneAuthCredential
import com.google.firebase.auth.PhoneAuthProvider
import com.google.firebase.quickstart.auth.R
import kotlinx.android.synthetic.main.activity_phone_auth.buttonResend
import kotlinx.android.synthetic.main.activity_phone_auth.buttonStartVerification
import kotlinx.android.synthetic.main.activity_phone_auth.buttonVerifyPhone
import kotlinx.android.synthetic.main.activity_phone_auth.detail
import kotlinx.android.synthetic.main.activity_phone_auth.fieldPhoneNumber
import kotlinx.android.synthetic.main.activity_phone_auth.fieldVerificationCode
import kotlinx.android.synthetic.main.activity_phone_auth.phoneAuthFields
import kotlinx.android.synthetic.main.activity_phone_auth.signOutButton
import kotlinx.android.synthetic.main.activity_phone_auth.signedInButtons
import kotlinx.android.synthetic.main.activity_phone_auth.status
import java.util.concurrent.TimeUnit
class PhoneAuthActivity : AppCompatActivity(), View.OnClickListener {
// [START declare_auth]
private lateinit var auth: FirebaseAuth
// [END declare_auth]
private var verificationInProgress = false
private var storedVerificationId: String? = ""
private lateinit var resendToken: PhoneAuthProvider.ForceResendingToken
private lateinit var callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_phone_auth)
// Restore instance state
if (savedInstanceState != null) {
onRestoreInstanceState(savedInstanceState)
}
// Assign click listeners
buttonStartVerification.setOnClickListener(this)
buttonVerifyPhone.setOnClickListener(this)
buttonResend.setOnClickListener(this)
signOutButton.setOnClickListener(this)
// [START initialize_auth]
// Initialize Firebase Auth
auth = FirebaseAuth.getInstance()
// [END initialize_auth]
// Initialize phone auth callbacks
// [START phone_auth_callbacks]
callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
// This callback will be invoked in two situations:
// 1 - Instant verification. In some cases the phone number can be instantly
// verified without needing to send or enter a verification code.
// 2 - Auto-retrieval. On some devices Google Play services can automatically
// detect the incoming verification SMS and perform verification without
// user action.
Log.d(TAG, "onVerificationCompleted:$credential")
// [START_EXCLUDE silent]
verificationInProgress = false
// [END_EXCLUDE]
// [START_EXCLUDE silent]
// Update the UI and attempt sign in with the phone credential
updateUI(STATE_VERIFY_SUCCESS, credential)
// [END_EXCLUDE]
signInWithPhoneAuthCredential(credential)
}
override fun onVerificationFailed(e: FirebaseException) {
// This callback is invoked in an invalid request for verification is made,
// for instance if the the phone number format is not valid.
Log.w(TAG, "onVerificationFailed", e)
// [START_EXCLUDE silent]
verificationInProgress = false
// [END_EXCLUDE]
if (e is FirebaseAuthInvalidCredentialsException) {
// Invalid request
// [START_EXCLUDE]
fieldPhoneNumber.error = "Invalid phone number."
// [END_EXCLUDE]
} else if (e is FirebaseTooManyRequestsException) {
// The SMS quota for the project has been exceeded
// [START_EXCLUDE]
Snackbar.make(findViewById(android.R.id.content), "Quota exceeded.",
Snackbar.LENGTH_SHORT).show()
// [END_EXCLUDE]
}
// Show a message and update the UI
// [START_EXCLUDE]
updateUI(STATE_VERIFY_FAILED)
// [END_EXCLUDE]
}
override fun onCodeSent(
verificationId: String?,
token: PhoneAuthProvider.ForceResendingToken
) {
// The SMS verification code has been sent to the provided phone number, we
// now need to ask the user to enter the code and then construct a credential
// by combining the code with a verification ID.
Log.d(TAG, "onCodeSent:" + verificationId!!)
// Save verification ID and resending token so we can use them later
storedVerificationId = verificationId
resendToken = token
// [START_EXCLUDE]
// Update UI
updateUI(STATE_CODE_SENT)
// [END_EXCLUDE]
}
}
// [END phone_auth_callbacks]
}
// [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)
// [START_EXCLUDE]
if (verificationInProgress && validatePhoneNumber()) {
startPhoneNumberVerification(fieldPhoneNumber.text.toString())
}
// [END_EXCLUDE]
}
// [END on_start_check_user]
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(KEY_VERIFY_IN_PROGRESS, verificationInProgress)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
verificationInProgress = savedInstanceState.getBoolean(KEY_VERIFY_IN_PROGRESS)
}
private fun startPhoneNumberVerification(phoneNumber: String) {
// [START start_phone_auth]
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
callbacks) // OnVerificationStateChangedCallbacks
// [END start_phone_auth]
verificationInProgress = true
}
private fun verifyPhoneNumberWithCode(verificationId: String?, code: String) {
// [START verify_with_code]
val credential = PhoneAuthProvider.getCredential(verificationId!!, code)
// [END verify_with_code]
signInWithPhoneAuthCredential(credential)
}
// [START resend_verification]
private fun resendVerificationCode(
phoneNumber: String,
token: PhoneAuthProvider.ForceResendingToken?
) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
callbacks, // OnVerificationStateChangedCallbacks
token) // ForceResendingToken from callbacks
}
// [END resend_verification]
// [START sign_in_with_phone]
private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) {
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
val user = task.result?.user
// [START_EXCLUDE]
updateUI(STATE_SIGNIN_SUCCESS, user)
// [END_EXCLUDE]
} else {
// Sign in failed, display a message and update the UI
Log.w(TAG, "signInWithCredential:failure", task.exception)
if (task.exception is FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
// [START_EXCLUDE silent]
fieldVerificationCode.error = "Invalid code."
// [END_EXCLUDE]
}
// [START_EXCLUDE silent]
// Update UI
updateUI(STATE_SIGNIN_FAILED)
// [END_EXCLUDE]
}
}
}
// [END sign_in_with_phone]
private fun signOut() {
auth.signOut()
updateUI(STATE_INITIALIZED)
}
private fun updateUI(user: FirebaseUser?) {
if (user != null) {
updateUI(STATE_SIGNIN_SUCCESS, user)
} else {
updateUI(STATE_INITIALIZED)
}
}
private fun updateUI(uiState: Int, cred: PhoneAuthCredential) {
updateUI(uiState, null, cred)
}
private fun updateUI(
uiState: Int,
user: FirebaseUser? = auth.currentUser,
cred: PhoneAuthCredential? = null
) {
when (uiState) {
STATE_INITIALIZED -> {
// Initialized state, show only the phone number field and start button
enableViews(buttonStartVerification, fieldPhoneNumber)
disableViews(buttonVerifyPhone, buttonResend, fieldVerificationCode)
detail.text = null
}
STATE_CODE_SENT -> {
// Code sent state, show the verification field, the
enableViews(buttonVerifyPhone, buttonResend, fieldPhoneNumber, fieldVerificationCode)
disableViews(buttonStartVerification)
detail.setText(R.string.status_code_sent)
}
STATE_VERIFY_FAILED -> {
// Verification has failed, show all options
enableViews(buttonStartVerification, buttonVerifyPhone, buttonResend, fieldPhoneNumber,
fieldVerificationCode)
detail.setText(R.string.status_verification_failed)
}
STATE_VERIFY_SUCCESS -> {
// Verification has succeeded, proceed to firebase sign in
disableViews(buttonStartVerification, buttonVerifyPhone, buttonResend, fieldPhoneNumber,
fieldVerificationCode)
detail.setText(R.string.status_verification_succeeded)
// Set the verification text based on the credential
if (cred != null) {
if (cred.smsCode != null) {
fieldVerificationCode.setText(cred.smsCode)
} else {
fieldVerificationCode.setText(R.string.instant_validation)
}
}
}
STATE_SIGNIN_FAILED ->
// No-op, handled by sign-in check
detail.setText(R.string.status_sign_in_failed)
STATE_SIGNIN_SUCCESS -> {
}
} // Np-op, handled by sign-in check
if (user == null) {
// Signed out
phoneAuthFields.visibility = View.VISIBLE
signedInButtons.visibility = View.GONE
status.setText(R.string.signed_out)
} else {
// Signed in
phoneAuthFields.visibility = View.GONE
signedInButtons.visibility = View.VISIBLE
enableViews(fieldPhoneNumber, fieldVerificationCode)
fieldPhoneNumber.text = null
fieldVerificationCode.text = null
status.setText(R.string.signed_in)
detail.text = getString(R.string.firebase_status_fmt, user.uid)
}
}
private fun validatePhoneNumber(): Boolean {
val phoneNumber = fieldPhoneNumber.text.toString()
if (TextUtils.isEmpty(phoneNumber)) {
fieldPhoneNumber.error = "Invalid phone number."
return false
}
return true
}
private fun enableViews(vararg views: View) {
for (v in views) {
v.isEnabled = true
}
}
private fun disableViews(vararg views: View) {
for (v in views) {
v.isEnabled = false
}
}
override fun onClick(view: View) {
when (view.id) {
R.id.buttonStartVerification -> {
if (!validatePhoneNumber()) {
return
}
startPhoneNumberVerification(fieldPhoneNumber.text.toString())
}
R.id.buttonVerifyPhone -> {
val code = fieldVerificationCode.text.toString()
if (TextUtils.isEmpty(code)) {
fieldVerificationCode.error = "Cannot be empty."
return
}
verifyPhoneNumberWithCode(storedVerificationId, code)
}
R.id.buttonResend -> resendVerificationCode(fieldPhoneNumber.text.toString(), resendToken)
R.id.signOutButton -> signOut()
}
}
companion object {
private const val TAG = "PhoneAuthActivity"
private const val KEY_VERIFY_IN_PROGRESS = "key_verify_in_progress"
private const val STATE_INITIALIZED = 1
private const val STATE_VERIFY_FAILED = 3
private const val STATE_VERIFY_SUCCESS = 4
private const val STATE_CODE_SENT = 2
private const val STATE_SIGNIN_FAILED = 5
private const val STATE_SIGNIN_SUCCESS = 6
}
}