Home > Net >  How Can I Create Custom Auth For Firebase (Kotlin)
How Can I Create Custom Auth For Firebase (Kotlin)

Time:11-07

I want to add users to Firebase with usernames,p passwords, and emails. I'm using the Email-Password sign-in method but how can I add the username to the database? Here is the basic code that I wrote for the email&password sign-in method:


    fun signup(view:View){
        val email = binding.emailText.text.toString()
        val username = binding.usernameText2.text.toString()
        val password = binding.passwordText2.text.toString()
        if(email.equals("") || username.equals("") || password.equals("")){
            Toast.makeText(this,"Don't Leave them empty!",Toast.LENGTH_LONG).show()
        }else{
            auth.createUserWithEmailAndPassword(email,password).addOnSuccessListener {
                //sucess
                val intent = Intent(this@SignupActivity,FeedsActivity::class.java)
                startActivity(intent)
                finish()
            }.addOnFailureListener {
                //failed
                Toast.makeText(this,it.localizedMessage,Toast.LENGTH_LONG).show()
            }

        }

    }

CodePudding user response:

In order to add some data to the database, you have to choose which database you want to use. You can use either Cloud Firestore, or the Realtime Database. Now, since the sign-in operation is asynchronous, the code that writes data to the database should be added inside the callback. That being said, get the data from the FirebaseUser object:

val firebaseUser = FirebaseAuth.getInstance().currentUser
val email = firebaseUser?.email
val displayName = firebaseUser?.displayName
val user = mapOf(
    displayName to displayName,
    email to email
)

And add it to Firestore:

val db = FirebaseFirestore.getInstance()
val usersRef = db.collection("users")
usersRef.document(uid).set(user)

Or in the Realtime Database:

val db = FirebaseDatabase.getInstance().reference
val usersRef = db.child("users")
usersRef.child(uid).setValue(user)
  • Related