Zarządzaj użytkownikami w Firebase

Tworzenie konta użytkownika

Nowego użytkownika możesz utworzyć w projekcie Firebase, wywołując metodę createUserWithEmailAndPassword lub logując użytkownika po raz pierwszy przy użyciu dostawcy tożsamości sfederowanego, takiego jak Logowanie przez Google lub Logowanie przez Facebooka.

Nowych użytkowników z uwierzytelnianiem za pomocą hasła możesz też utworzyć w sekcji Uwierzytelnianie w konsoli Firebase na stronie Użytkownicy.

Pobierz informacje o zalogowanym użytkowniku

Aby pozyskać bieżącego użytkownika, zalecamy wywołanie metody getCurrentUser. Jeśli żaden użytkownik nie jest zalogowany, getCurrentUser zwraca wartość null:

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
}

W niektórych przypadkach getCurrentUser zwraca FirebaseUser o wartości innej niż null, ale podany token jest nieprawidłowy. Może się tak zdarzyć, jeśli np. użytkownik został usunięty z innego urządzenia, a lokalny token nie został odświeżony. W takim przypadku możesz otrzymać prawidłowego użytkownika getCurrentUser, ale kolejne wywołania uwierzytelnionych zasobów zakończą się niepowodzeniem.

getCurrentUser może również zwrócić wartość null, ponieważ obiekt uwierzytelniania nie został dokończony.

Jeśli dołączysz element AuthStateListener, będziesz otrzymywać wywołanie zwrotne po każdej zmianie stanu tokena. Jest to przydatne w reagowaniu na przypadki skrajne, takie jak te wymienione powyżej.

Pobieranie profilu użytkownika

Aby uzyskać informacje o profilu użytkownika, użyj metod akcesorów instancji FirebaseUser. Przykład:

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();
}

Uzyskiwanie informacji o profilu użytkownika specyficznych dla dostawcy

Aby pobrać informacje profilowe pobrane od dostawców logowania połączonych z użytkownikiem, użyj metody getProviderData. Przykład:

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();
    }
}

Aktualizowanie profilu użytkownika

Za pomocą metody updateProfile możesz aktualizować podstawowe informacje profilowe użytkownika – wyświetlaną nazwę i adres URL zdjęcia profilowego. Przykład:

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

Ustawianie adresu e-mail użytkownika

Adres e-mail użytkownika możesz skonfigurować za pomocą metody updateEmail. Przykład:

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

Wysyłanie e-maila weryfikacyjnego do użytkownika

Aby wysłać do użytkownika e-maila na potrzeby weryfikacji adresu, użyj metody sendEmailVerification. Przykład:

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

Na stronie Szablony e-maili możesz dostosować szablon e-maila w sekcji Uwierzytelnianie w konsoli Firebase. Przeczytaj artykuł Szablony e-maili w Centrum pomocy Firebase.

Można też przekazać stan za pomocą adresu URL kontynuacji, aby przekierowywać użytkowników z powrotem do aplikacji podczas wysyłania e-maila weryfikacyjnego.

Możesz też zlokalizować e-maila weryfikacyjnego, aktualizując kod języka w instancji Auth przed wysłaniem wiadomości. Przykład:

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();

Ustawianie hasła użytkownika

Hasło użytkownika możesz ustawić za pomocą metody updatePassword. Przykład:

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

Wyślij e-maila do resetowania hasła

Za pomocą metody sendPasswordResetEmail możesz wysłać do użytkownika e-maila z prośbą o zresetowanie hasła. Przykład:

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

Na stronie Szablony e-maili możesz dostosować szablon e-maila w sekcji Uwierzytelnianie w konsoli Firebase. Przeczytaj artykuł Szablony e-maili w Centrum pomocy Firebase.

Możesz też przekazywać stan za pomocą adresu URL kontynuacji, aby przekierowywać użytkowników z powrotem do aplikacji podczas wysyłania e-maila do resetowania hasła.

Możesz też zlokalizować e-maila do resetowania hasła, aktualizując kod języka w instancji Auth przed wysłaniem wiadomości. Przykład:

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();

Możesz też wysyłać e-maile dotyczące resetowania hasła z konsoli Firebase.

Usuwanie konta użytkownika

Konto użytkownika możesz usunąć za pomocą metody delete. Przykład:

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

Użytkowników możesz też usuwać w sekcji Uwierzytelnianie w konsoli Firebase na stronie Użytkownicy.

Ponowne uwierzytelnianie użytkownika

Niektóre działania związane z bezpieczeństwem (takie jak usunięcie konta, ustawienie podstawowego adresu e-mail lub zmiana hasła) wymagają ostatniego zalogowania się. Jeśli wykonasz jedną z tych czynności, a użytkownik zalogował się zbyt dawno temu, czynność ta nie powiedzie się i wyświetli FirebaseAuthRecentLoginRequiredException. W takim przypadku ponownie uwierzytelnij użytkownika, uzyskując od niego nowe dane logowania i przekazując je do usługi reauthenticate. Przykład:

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

Importowanie kont użytkowników

Aby zaimportować konta użytkowników z pliku do projektu Firebase, użyj polecenia auth:import interfejsu wiersza poleceń Firebase. Przykład:

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