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

Kullanıcı oluşturma

createUserWithEmailAndPassword yöntemini çağırarak veya Google ile oturum açma ya da Facebook ile oturum açma gibi birleşik kimlik sağlayıcıları kullanarak bir kullanıcının oturumunu ilk kez açarak Firebase projenizde yeni bir kullanıcı oluşturursunuz.

Şifre ile kimlik doğrulaması yapılan yeni kullanıcıları, Firebase konsolunun Kullanıcılar sayfasındaki Kimlik Doğrulama bölümünden de oluşturabilirsiniz.

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

Mevcut kullanıcıyı almanın önerilen yolu getCurrentUser yöntemini çağırmaktır. Hiçbir kullanıcı oturum açmadıysa getCurrentUser null değerini döndürür:

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

getCurrentUser işlevinin null olmayan bir FirebaseUser döndürdüğü ancak temel jetonun geçerli olmadığı bazı durumlar vardır. Örneğin, kullanıcı başka bir cihazda silindiyse ve yerel jeton yenilenmediyse bu durum oluşabilir. Bu durumda, geçerli bir kullanıcı getCurrentUser elde edebilirsiniz ancak kimliği doğrulanmış kaynaklara yapılan sonraki çağrılar başarısız olur.

Kimlik doğrulama nesnesi başlatılmamış olduğu için getCurrentUser, null değerini de döndürebilir.

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

Kullanıcının profilini alma

Kullanıcının profil bilgilerini almak için FirebaseUser örneğinin erişim yöntemlerini kullanın. Örneğin:

KotlinJava
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
}
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 özgü profil bilgilerini alma

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

KotlinJava
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
    }
}
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

Kullanıcının temel profil bilgilerini (kullanıcı adı ve profil fotoğrafı URL'si) updateProfile yöntemiyle güncelleyebilirsiniz. Örneğin:

KotlinJava
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.")
        }
    }
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 ayarlama

updateEmail yöntemini kullanarak kullanıcının e-posta adresini ayarlayabilirsiniz. Örneğin:

KotlinJava
val user = Firebase.auth.currentUser

user!!.updateEmail("user@example.com")
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Log.d(TAG, "User email address updated.")
        }
    }
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öntemini kullanarak bir kullanıcıya adres doğrulama e-postası gönderebilirsiniz. Örneğin:

KotlinJava
val user = Firebase.auth.currentUser

user!!.sendEmailVerification()
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Log.d(TAG, "Email sent.")
        }
    }
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ı başlıklı makaleyi inceleyin.

Doğrulama e-postası gönderirken uygulamaya geri yönlendirmek için durumu bir devam URL'si aracılığıyla da iletebilirsiniz.

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

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

Kullanıcı şifresi belirleme

Kullanıcının şifresini updatePassword yöntemiyle ayarlayabilirsiniz. Örneğin:

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

user!!.updatePassword(newPassword)
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Log.d(TAG, "User password updated.")
        }
    }
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önderme

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

KotlinJava
val emailAddress = "user@example.com"

Firebase.auth.sendPasswordResetEmail(emailAddress)
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Log.d(TAG, "Email sent.")
        }
    }
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ı başlıklı makaleyi inceleyin.

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

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

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

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

Kullanıcı silme

delete yöntemini kullanarak kullanıcı hesaplarını silebilirsiniz. Örneğin:

KotlinJava
val user = Firebase.auth.currentUser!!

user.delete()
    .addOnCompleteListener { task ->
        if (task.isSuccessful) {
            Log.d(TAG, "User account deleted.")
        }
    }
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ı, Firebase konsolunun Kimlik Doğrulama bölümündeki Kullanıcılar sayfasından da silebilirsiniz.

Kullanıcının kimliğini tekrar doğrulama

Hesap silme, birincil e-posta adresi ayarlama ve şifre değiştirme gibi güvenlik açısından hassas bazı işlemler için kullanıcının yakın zamanda oturum açmış olması gerekir. Bu işlemlerden birini gerçekleştirirseniz ve kullanıcı çok uzun zaman önce oturum açtıysa işlem başarısız olur ve FirebaseAuthRecentLoginRequiredException hatası oluşur. Bu durumda, kullanıcıdan yeni oturum açma kimlik bilgilerini alarak ve kimlik bilgilerini reauthenticate'e ileterek kullanıcının kimliğini yeniden doğrulayın. Örneğin:

KotlinJava
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.") }
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 aktarma

Firebase CLI'nin auth:import komutunu kullanarak kullanıcı hesaplarını bir dosyadan Firebase projenize aktarabilirsiniz. Örneğin:

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