Firebase'de Kullanıcıları Yönetin

Kullanıcı oluşturma

Firebase projenizde createUserWithEmailAndPassword yöntemini çağırarak veya Google Sign-In ya da Facebook Login gibi birleşik bir kimlik sağlayıcı kullanarak bir kullanıcıyla ilk kez oturum açarak yeni bir kullanıcı oluşturursunuz.

Ayrıca, Kullanıcılar sayfasındaki Firebase konsolunun Kimlik Doğrulama bölümünden de şifre kimliği doğrulanmış yeni kullanıcılar oluşturabilirsiniz.

Şu anda oturum açmış olan kullanıcıyı alma

Geçerli kullanıcıyı edinmenin önerilen yolu getCurrentUser yöntemini çağırmaktır. Hiçbir kullanıcı oturum açmadıysa getCurrentUser, null değerini döndürür:

Kotlin+KTX

val user = Firebase.auth.currentUser
if (user != null) {
    // User is signed in
} else {
    // No user is signed in
}

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // User is signed in
} else {
    // No user is signed in
}

getCurrentUser bazı durumlarda boş olmayan bir FirebaseUser döndürür, ancak temel jetonun geçerli olmadığı durumlar vardır. Örneğin, kullanıcı başka bir cihazda silindiyse ve yerel jeton yenilenmemişse bu durum yaşanabilir. Bu durumda, geçerli bir kullanıcı getCurrentUser alabilirsiniz ancak kimliği doğrulanmış kaynaklara sonraki çağrılar başarısız olur.

Ayrıca getCurrentUser, kimlik doğrulama nesnesinin başlatılması tamamlanmadığı için null değerini de döndürebilir.

Bir AuthStateListener eklerseniz temel jeton durumu her değiştiğinde bir geri çağırma alırsınız. Bu, yukarıda bahsedilenler gibi uç durumlara tepki vermek için yararlı olabilir.

Kullanıcı profilini alma

Bir kullanıcının profil bilgilerini almak için bir FirebaseUser örneğindeki erişimci yöntemlerini kullanın. Örnek:

Kotlin+KTX

val user = Firebase.auth.currentUser
user?.let {
    // Name, email address, and profile photo Url
    val name = it.displayName
    val email = it.email
    val photoUrl = it.photoUrl

    // Check if user's email is verified
    val emailVerified = it.isEmailVerified

    // The user's ID, unique to the Firebase project. Do NOT use this value to
    // authenticate with your backend server, if you have one. Use
    // FirebaseUser.getIdToken() instead.
    val uid = it.uid
}

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // Name, email address, and profile photo Url
    String name = user.getDisplayName();
    String email = user.getEmail();
    Uri photoUrl = user.getPhotoUrl();

    // Check if user's email is verified
    boolean emailVerified = user.isEmailVerified();

    // The user's ID, unique to the Firebase project. Do NOT use this value to
    // authenticate with your backend server, if you have one. Use
    // FirebaseUser.getIdToken() instead.
    String uid = user.getUid();
}

Kullanıcının sağlayıcıya özel profil bilgilerini alma

Bir kullanıcıyla bağlantılı oturum açma sağlayıcılarından alınan profil bilgilerini almak için getProviderData yöntemini kullanın. Örnek:

Kotlin+KTX

val user = Firebase.auth.currentUser
user?.let {
    for (profile in it.providerData) {
        // Id of the provider (ex: google.com)
        val providerId = profile.providerId

        // UID specific to the provider
        val uid = profile.uid

        // Name, email address, and profile photo Url
        val name = profile.displayName
        val email = profile.email
        val photoUrl = profile.photoUrl
    }
}

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    for (UserInfo profile : user.getProviderData()) {
        // Id of the provider (ex: google.com)
        String providerId = profile.getProviderId();

        // UID specific to the provider
        String uid = profile.getUid();

        // Name, email address, and profile photo Url
        String name = profile.getDisplayName();
        String email = profile.getEmail();
        Uri photoUrl = profile.getPhotoUrl();
    }
}

Kullanıcı profilini güncelleme

Bir kullanıcının temel profil bilgilerini (kullanıcının görünen adı ve profil fotoğrafı URL'si) updateProfile yöntemini kullanarak güncelleyebilirsiniz. Örnek:

Kotlin+KTX

val user = Firebase.auth.currentUser

val profileUpdates = userProfileChangeRequest {
    displayName = "Jane Q. User"
    photoUri = Uri.parse("https://example.com/jane-q-user/profile.jpg")
}

user!!.updateProfile(profileUpdates)
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Log.d(TAG, "User profile updated.")
        }
    }

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
        .setDisplayName("Jane Q. User")
        .setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg"))
        .build();

user.updateProfile(profileUpdates)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "User profile updated.");
                }
            }
        });

Kullanıcının e-posta adresini ayarlayın

Kullanıcının e-posta adresini updateEmail yöntemiyle ayarlayabilirsiniz. Örnek:

Kotlin+KTX

val user = Firebase.auth.currentUser

user!!.updateEmail("user@example.com")
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Log.d(TAG, "User email address updated.")
        }
    }

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

user.updateEmail("user@example.com")
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "User email address updated.");
                }
            }
        });

Kullanıcıya doğrulama e-postası gönderme

sendEmailVerification yöntemiyle kullanıcılara adres doğrulama e-postası gönderebilirsiniz. Örnek:

Kotlin+KTX

val user = Firebase.auth.currentUser

user!!.sendEmailVerification()
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Log.d(TAG, "Email sent.")
        }
    }

Java

FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();

user.sendEmailVerification()
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "Email sent.");
                }
            }
        });

Firebase konsolunun Kimlik Doğrulama bölümünde kullanılan e-posta şablonunu E-posta Şablonları sayfasından özelleştirebilirsiniz. Firebase Yardım Merkezi'ndeki E-posta Şablonları bölümüne bakın.

Ayrıca, doğrulama e-postası gönderirken uygulamaya geri yönlendirmek için durumu bir devam URL'si aracılığıyla iletmek de mümkündür.

Ayrıca, e-postayı göndermeden önce Auth örneğindeki dil kodunu güncelleyerek doğrulama e-postasını yerelleştirebilirsiniz. Örnek:

Kotlin+KTX

auth.setLanguageCode("fr")
// To apply the default app language instead of explicitly setting it.
// auth.useAppLanguage()

Java

auth.setLanguageCode("fr");
// To apply the default app language instead of explicitly setting it.
// auth.useAppLanguage();

Kullanıcı şifresi belirleme

updatePassword yöntemiyle kullanıcı şifresi ayarlayabilirsiniz. Örnek:

Kotlin+KTX

val user = Firebase.auth.currentUser
val newPassword = "SOME-SECURE-PASSWORD"

user!!.updatePassword(newPassword)
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Log.d(TAG, "User password updated.")
        }
    }

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String newPassword = "SOME-SECURE-PASSWORD";

user.updatePassword(newPassword)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "User password updated.");
                }
            }
        });

Şifre sıfırlama e-postası gönderin

sendPasswordResetEmail yöntemini kullanarak bir kullanıcıya şifre sıfırlama e-postası gönderebilirsiniz. Örnek:

Kotlin+KTX

val emailAddress = "user@example.com"

Firebase.auth.sendPasswordResetEmail(emailAddress)
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Log.d(TAG, "Email sent.")
        }
    }

Java

FirebaseAuth auth = FirebaseAuth.getInstance();
String emailAddress = "user@example.com";

auth.sendPasswordResetEmail(emailAddress)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "Email sent.");
                }
            }
        });

Firebase konsolunun Kimlik Doğrulama bölümünde kullanılan e-posta şablonunu E-posta Şablonları sayfasından özelleştirebilirsiniz. Firebase Yardım Merkezi'ndeki E-posta Şablonları bölümüne bakın.

Şifre sıfırlama e-postası gönderirken uygulamaya geri yönlendirmek için durum devam URL'si aracılığıyla da iletilebilir.

Ayrıca, e-postayı göndermeden önce Auth örneğindeki dil kodunu güncelleyerek şifre sıfırlama e-postasını yerelleştirebilirsiniz. Örnek:

Kotlin+KTX

auth.setLanguageCode("fr")
// To apply the default app language instead of explicitly setting it.
// auth.useAppLanguage()

Java

auth.setLanguageCode("fr");
// To apply the default app language instead of explicitly setting it.
// auth.useAppLanguage();

Firebase konsolundan şifre sıfırlama e-postaları da gönderebilirsiniz.

Kullanıcı silme

Kullanıcı hesaplarını delete yöntemiyle silebilirsiniz. Örnek:

Kotlin+KTX

val user = Firebase.auth.currentUser!!

user.delete()
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Log.d(TAG, "User account deleted.")
        }
    }

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

user.delete()
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "User account deleted.");
                }
            }
        });

Kullanıcıları, Kullanıcılar sayfasındaki Firebase konsolunun Kimlik Doğrulama bölümünden de silebilirsiniz.

Kullanıcının kimliğini yeniden doğrulayın

Hesap silme, birincil e-posta adresi ayarlama ve şifre değiştirme gibi güvenlik açısından hassas bazı işlemler, kullanıcının kısa süre önce oturum açmasını gerektirir. Bu işlemlerden birini yaparsanız ve kullanıcı çok uzun zaman önce oturum açtıysa işlem başarısız olur ve FirebaseAuthRecentLoginRequiredException hatası verir. Böyle bir durumda, kullanıcıdan yeni oturum açma kimlik bilgilerini alarak ve kimlik bilgilerini reauthenticate hizmetine ileterek kullanıcının kimliğini yeniden doğrulayın. Örnek:

Kotlin+KTX

val user = Firebase.auth.currentUser!!

// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
val credential = EmailAuthProvider
    .getCredential("user@example.com", "password1234")

// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
    .addOnCompleteListener { Log.d(TAG, "User re-authenticated.") }

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
AuthCredential credential = EmailAuthProvider
        .getCredential("user@example.com", "password1234");

// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                Log.d(TAG, "User re-authenticated.");
            }
        });

Kullanıcı hesaplarını içe aktarın

Firebase CLI'nın auth:import komutunu kullanarak kullanıcı hesaplarını bir dosyadan Firebase projenize aktarabilirsiniz. Örnek:

firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14