Tworzenie konta użytkownika
Nowego użytkownika możesz utworzyć na te sposoby:
W aplikacji: utwórz nowego użytkownika w projekcie w Firebase, wywołując metodę
createUserWithEmailAndPasswordlub logując użytkownika po raz pierwszy za pomocą tożsamości sfederowanej lub dostawcy tożsamości, np. Logowania przez Google lub Logowania przez Facebooka.W konsoli Firebase: utwórz nowego użytkownika uwierzytelnianego hasłem na karcie Bezpieczeństwo > Uwierzytelnianie > Użytkownicy.
Pobieranie aktualnie zalogowanego użytkownika
Zalecanym sposobem na pobranie aktualnego użytkownika jest wywołanie metody getCurrentUser.
Jeśli żaden użytkownik nie jest zalogowany, getCurrentUser zwraca wartość null:
Kotlin
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 zwróci wartość FirebaseUser inną niż null, ale podstawowy token będzie nieprawidłowy. Może się tak zdarzyć, jeśli użytkownik został usunięty na innym urządzeniu, a lokalny token nie został odświeżony. W takim przypadku możesz uzyskać prawidłowego użytkownika getCurrentUser, ale kolejne wywołania uwierzytelnionych zasobów zakończą się niepowodzeniem.
getCurrentUser może też zwrócić wartość null, ponieważ obiekt uwierzytelniania nie został jeszcze zainicjowany.
Jeśli dołączysz AuthStateListener za każdym razem, gdy zmieni się stan podstawowego tokena, otrzymasz wywołanie zwrotne. Może to być przydatne w przypadku reagowania na przypadki brzegowe, takie jak te wymienione powyżej.
Pobieranie profilu użytkownika
Aby uzyskać informacje o profilu użytkownika, użyj metod dostępu instancji FirebaseUser. Przykład:
Kotlin
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(); }
Pobieranie informacji o profilu użytkownika specyficznych dla dostawcy
Aby uzyskać informacje o profilu pobrane od dostawców logowania połączonych z użytkownikiem, użyj metody getProviderData. Przykład:
Kotlin
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
Podstawowe informacje o profilu użytkownika – nazwę wyświetlaną i adres URL zdjęcia profilowego – możesz zaktualizować za pomocą metody updateProfile. Przykład:
Kotlin
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 ustawić za pomocą metody updateEmail. Przykład:
Kotlin
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 do użytkownika e-maila weryfikacyjnego
Za pomocą metody sendEmailVerification możesz wysłać do użytkownika e-mail weryfikacyjny adresu. Przykład:
Kotlin
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."); } } });
Możesz dostosować, którego szablonu e-maila użyć, na karcie Bezpieczeństwo > Uwierzytelnianie > Szablony w konsoli Firebase. Zobacz Szablony e-maili w Centrum pomocy Firebase.
Dodatkowo możesz zlokalizować e-maila weryfikacyjnego, aktualizując kod języka w instancji Auth przed wysłaniem e-maila. Przykład:
Kotlin
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
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."); } } });
Wysyłanie 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
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."); } } });
Możesz dostosować, którego szablonu e-maila użyć, na karcie Bezpieczeństwo > Uwierzytelnianie > Szablony w konsoli Firebase. Zobacz Szablony e-maili w Centrum pomocy Firebase.
Dodatkowo możesz zlokalizować e-maila do resetowania hasła, aktualizując kod języka w instancji Auth przed wysłaniem e-maila. Przykład:
Kotlin
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();
E-maile do resetowania hasła możesz też wysyłać z konsoli Firebase.
Usuwanie konta użytkownika
Konto użytkownika możesz usunąć za pomocą metody delete. Przykład:
Kotlin
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 konsoli Firebase na karcie Bezpieczeństwo > Uwierzytelnianie > Użytkownicy.
Ponowne uwierzytelnianie użytkownika
Niektóre działania wymagające zachowania bezpieczeństwa, takie jak
usuwanie konta,
ustawianie podstawowego adresu e-mail i
zmienianie hasła, wymagają, aby użytkownik był
niedawno zalogowany. Jeśli wykonasz jedno z tych działań, a użytkownik zalogował się
zbyt dawno, działanie nie powiedzie się i zostanie zgłoszony wyjątek FirebaseAuthRecentLoginRequiredException.
W takim przypadku ponownie uwierzytelnij użytkownika, uzyskując od niego nowe dane logowania i przekazując je do reauthenticate. Przykład:
Kotlin
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
Konta użytkowników możesz importować z pliku do projektu w Firebase za pomocą polecenia auth:import w wierszu poleceń Firebase. Przykład:
firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14