我是 Android 开发的初学者,正在制作一个非常简单的登录注册应用程序,该应用程序首先使用电子邮件和密码登录用户,然后继续进行电话身份验证以通过 OTP 验证他们的电话号码。现在我发现Firebase为电子邮件/密码身份验证和电话身份验证提供了不同的用户ID。但我需要他们都在同一个用户名下,以便他们可以通过电子邮件或电话号码登录他们的帐户。
我确实阅读了有关如何使用 linkWithCredential 链接多个身份验证提供商的各种答案和官方 Firebase 文档,并尝试在我的代码中实现它,但它总是无法显示此电子邮件已被另一个帐户使用的错误。 我无法遵循需要放置 linkWithCredential 方法的位置。
请指导我,我附上了这两项活动的代码。
1)登录活动
package com.example.bccl
import android.content.ContentValues.TAG
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import android.os.Handler
import android.os.Looper
import android.text.InputType
import android.util.Log
import androidx.core.view.WindowInsetsCompat
import com.example.bccl.databinding.ActivityLoginBinding
import com.google.firebase.FirebaseException
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.PhoneAuthCredential
import com.google.firebase.auth.PhoneAuthOptions
import com.google.firebase.auth.PhoneAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import java.util.concurrent.TimeUnit
class LoginActivity : AppCompatActivity() {
private val binding: ActivityLoginBinding by lazy {
ActivityLoginBinding.inflate(layoutInflater)
}
private lateinit var auth: FirebaseAuth
private var passwordShowing = false
private val db = Firebase.firestore
override fun onStart() {
super.onStart()
val currentUser = auth.currentUser
currentUser?.let {
Log.d(TAG,"user id is ${currentUser.uid}")
db.collection("user").document(currentUser.uid)
.get()
.addOnSuccessListener {
if (it != null && it.data?.get("otpverified") == true) {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(binding.root)
auth = Firebase.auth
binding.eyepassword2.setOnClickListener {
passwordShowing = !passwordShowing
if (passwordShowing) {
binding.editTextTextPassword.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
binding.eyepassword2.setImageResource(R.drawable.eye)
} else {
binding.editTextTextPassword.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
binding.eyepassword2.setImageResource(R.drawable.eye_off)
}
binding.editTextTextPassword.setSelection(binding.editTextTextPassword.text.length)
}
binding.SignUpText.setOnClickListener {
val intent = Intent(this, SignUp::class.java)
startActivity(intent)
finish()
}
val currentUser = auth.currentUser
if (currentUser != null) {
Log.d(TAG,"user id is ${currentUser.uid}")
}
binding.loginbutton.setOnClickListener {
val email = binding.editTextTextEmailAddress.text.toString().trim()
val password = binding.editTextTextPassword.text.toString().trim()
if (email.isBlank() || password.isBlank()) {
Toast.makeText(this, "Please Fill In All The Details", Toast.LENGTH_LONG).show()
} else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
Toast.makeText(this, "Please Enter a Valid Email", Toast.LENGTH_LONG).show()
} else {
binding.progressBar.visibility = View.VISIBLE
binding.loginbutton.visibility = View.INVISIBLE
binding.loginbutton.isEnabled = false
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
binding.progressBar.visibility = View.GONE
binding.loginbutton.visibility = View.VISIBLE
binding.loginbutton.isEnabled = true
if (task.isSuccessful) {
Log.d(TAG, "signInWithEmail:success")
val intent = Intent(this, OTPVerificationActivity::class.java)
val userId = auth.currentUser?.uid
userId?.let {
val ref = db.collection("user").document(it)
ref.get()
.addOnSuccessListener { document ->
if (document != null) {
val phoneNumber = document.data?.get("phone").toString()
val options = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber("+91$phoneNumber")
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
// Handle verification completion
}
override fun onVerificationFailed(e: FirebaseException) {
Toast.makeText(
this@LoginActivity,
e.message,
Toast.LENGTH_SHORT
).show()
}
override fun onCodeSent(
verificationId: String,
token: PhoneAuthProvider.ForceResendingToken
) {
intent.putExtra("verificationId", verificationId)
startActivity(intent)
finish()
}
override fun onCodeAutoRetrievalTimeOut(verificationId: String) {
// Handle code auto-retrieval timeout
}
})
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
}
}
}
} else {
Log.w(TAG, "signInWithEmail:failure", task.exception)
Toast.makeText(baseContext, "Invalid Credentials.", Toast.LENGTH_SHORT).show()
}
}
}
}
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
}
}
package com.example.bccl
import android.content.ContentValues.TAG
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.bccl.databinding.ActivityOtpverificationBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException
import com.google.firebase.auth.PhoneAuthCredential
import com.google.firebase.auth.PhoneAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class OTPVerificationActivity : AppCompatActivity() {
private val binding: ActivityOtpverificationBinding by lazy {
ActivityOtpverificationBinding.inflate(layoutInflater)
}
private val db = Firebase.firestore
private val auth = Firebase.auth
private var realuser: String? = null
private var hero : String? = null
override fun onStart() {
super.onStart()
Log.d(TAG,"onStart() method")
hero = auth.currentUser?.uid
if (hero != null) {
Log.d(TAG, "User ID :$hero")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(binding.root)
fetchPhoneNumber()
val otpbackend = intent.getStringExtra("verificationId")
binding.verifybutton.setOnClickListener {
Log.d(TAG,"User ID :" + auth.currentUser?.uid)
realuser= auth.currentUser?.uid
verifyOtp(otpbackend)
}
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
setupOtpInputs()
}
private fun fetchPhoneNumber() {
val userId = FirebaseAuth.getInstance().currentUser?.uid
userId?.let { uid ->
val ref = db.collection("user").document(uid)
ref.get()
.addOnSuccessListener {
it?.data?.get("phone")?.toString()?.let { phoneNumber ->
binding.phnnumber.text = String.format("+91-%s", phoneNumber)
Toast.makeText(this, "Phone Number Fetched Successfully", Toast.LENGTH_SHORT).show()
Log.d("Firebase", "DocumentSnapshot data: ${it.data}")
}
}
.addOnFailureListener { exception ->
Log.e("Firebase", "Error fetching phone number", exception)
}
}
}
private fun verifyOtp(otpbackend: String?) {
val otp = binding.editTextText1.text.toString() +
binding.editTextText2.text.toString() +
binding.editTextText3.text.toString() +
binding.editTextText4.text.toString() +
binding.editTextText5.text.toString() +
binding.editTextText6.text.toString()
if (otp.length != 6) {
Toast.makeText(this, "Please Enter OTP", Toast.LENGTH_SHORT).show()
return
}
if (otpbackend == null) {
Toast.makeText(this, "Please Check Internet Connection", Toast.LENGTH_SHORT).show()
return
}
binding.progressBar.visibility = View.VISIBLE
binding.verifybutton.visibility = View.GONE
val credential = PhoneAuthProvider.getCredential(otpbackend, otp)
auth.currentUser?.let { currentUser ->
currentUser.linkWithCredential(credential)
.addOnCompleteListener(this) { task ->
binding.progressBar.visibility = View.GONE
binding.verifybutton.visibility = View.VISIBLE
if (task.isSuccessful) {
Log.d(TAG, "linkWithCredential:success")
} else {
Log.w(TAG, "linkWithCredential:failure", task.exception)
if (task.exception is FirebaseAuthInvalidCredentialsException) {
Toast.makeText(this, "Invalid OTP.", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Log-in failed.", Toast.LENGTH_SHORT).show()
}
}
}
signInWithPhoneAuthCredential(credential)
}
}
private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) {
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
binding.progressBar.visibility = View.GONE
binding.verifybutton.visibility = View.VISIBLE
if (task.isSuccessful) {
Log.d(TAG, "signInWithCredential:success, user id : ${auth.currentUser?.uid}")
val currentUser = auth.currentUser
if (currentUser != null) {
markOTPVerification(currentUser.uid)
}
// Proceed to main activity
navigateToMainActivity()
} else {
Log.w(TAG, "signInWithCredential:failure", task.exception)
if (task.exception is FirebaseAuthInvalidCredentialsException) {
Toast.makeText(this, "Invalid OTP.", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Log-in failed.", Toast.LENGTH_SHORT).show()
}
}
}
}
private fun navigateToMainActivity() {
val intent = Intent(this, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
finish()
}
private fun markOTPVerification(uid: String) {
db.collection("user").document(uid)
.update("otpverified", true)
.addOnSuccessListener {
Log.d(TAG, "OTP Verification marked in database successfully")
}
.addOnFailureListener { e ->
Log.w(TAG, "Error marking OTP Verification", e)
Toast.makeText(this, "Failed to mark OTP Verification", Toast.LENGTH_SHORT).show()
}
}
private fun setupOtpInputs() {
val textWatcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (s?.length == 1) {
when (currentFocus?.id) {
R.id.editTextText1 -> binding.editTextText2.requestFocus()
R.id.editTextText2 -> binding.editTextText3.requestFocus()
R.id.editTextText3 -> binding.editTextText4.requestFocus()
R.id.editTextText4 -> binding.editTextText5.requestFocus()
R.id.editTextText5 -> binding.editTextText6.requestFocus()
}
}
}
override fun afterTextChanged(s: Editable?) {}
}
binding.editTextText1.addTextChangedListener(textWatcher)
binding.editTextText2.addTextChangedListener(textWatcher)
binding.editTextText3.addTextChangedListener(textWatcher)
binding.editTextText4.addTextChangedListener(textWatcher)
binding.editTextText5.addTextChangedListener(textWatcher)
binding.editTextText6.addTextChangedListener(textWatcher)
}
}
现在我发现Firebase为电子邮件/密码身份验证和电话身份验证提供了不同的用户ID。
是的,这是预期的行为,当使用两种不同类型的身份验证时,使用
signInWithEmailAndPassword()
时,有两个不同的 UID。
但我需要他们都在一个用户名下,以便他们可以通过电子邮件或电话号码登录他们的帐户。我确实阅读了有关如何使用 linkWithCredential 链接多个身份验证提供商的各种答案和官方 Firebase 文档。
是的,您可以链接多个身份验证提供商。根据官方文档:
您可以通过将身份验证提供程序凭据链接到现有用户帐户,允许用户使用多个身份验证提供程序登录您的应用程序。无论用户用于登录的身份验证提供商如何,都可以通过相同的 Firebase 用户 ID 来识别用户。例如,使用密码登录的用户可以关联 Google 帐户并在将来使用任一方法登录。
因此,在您的特定用例中,在使用电子邮件和密码进行 Firebase 身份验证完成后,您必须将电话身份验证提供程序链接到 FirebaseUser 对象。更多信息如下: