Tworzenie konta użytkownika
Nowego użytkownika w projekcie Firebase możesz utworzyć, wywołując metodę createUserWithEmailAndPassword
lub logując użytkownika po raz pierwszy za pomocą dostawcy tożsamości federacyjnej, takiego jak logowanie w Google czy logowanie w Facebooku.
Nowe użytkowników uwierzytelnionych za pomocą hasła możesz też tworzyć w sekcji uwierzytelniania w konsoli Firebase na stronie Użytkownicy.
Pobieranie informacji o obecnie zalogowanym użytkowniku
Zalecaną metodą uzyskania bieżącego użytkownika jest wywołanie metody getCurrentUser
.
Jeśli żaden użytkownik nie jest zalogowany, funkcja getCurrentUser
zwraca wartość null:
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 }
W niektórych przypadkach funkcja getCurrentUser
zwraca wartość niezerową FirebaseUser
, ale podrzędny token jest 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 otrzymać prawidłowy identyfikator użytkownika getCurrentUser
, ale kolejne wywołania zasobów uwierzytelnionych zakończą się niepowodzeniem.
Funkcja getCurrentUser
może też zwrócić wartość null
, ponieważ obiekt autoryzacji nie został jeszcze w pełni zainicjowany.
Jeśli dołączysz obiekt AuthStateListener, otrzymasz wywołanie zwrotne za każdym razem, gdy zmieni się stan tokena. Może to być przydatne w przypadku sytuacji szczególnych, takich 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:
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(); }
Pobieranie informacji profilowych użytkownika dotyczących konkretnego dostawcy
Aby uzyskać informacje profilowe pobrane od dostawców usług logowania powiązanych z użytkownikiem, użyj metody getProviderData
. Przykład:
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(); } }
Aktualizowanie profilu użytkownika
Za pomocą metody updateProfile
możesz zaktualizować podstawowe informacje w profilu użytkownika, czyli jego nazwę wyświetlaną i URL zdjęcia profilowego. Przykład:
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."); } } });
Ustawianie adresu e-mail użytkownika
Adres e-mail użytkownika możesz ustawić za pomocą metody updateEmail
. Przykład:
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."); } } });
Wysyłanie użytkownikowi e-maila weryfikacyjnego
Możesz wysłać użytkownikowi e-maila z weryfikacją adresu za pomocą metody sendEmailVerification
. Przykład:
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."); } } });
Szablon e-maila używany w sekcji uwierzytelniania w konsoli Firebase możesz dostosować na stronie Szablony e-maila. Więcej informacji znajdziesz w sekcji Szablony e-maili w Centrum pomocy Firebase.
Stan można też przekazać za pomocą adresu URL kontynuacji, aby przekierować użytkownika z powrotem do aplikacji po wysłaniu e-maila weryfikacyjnego.
Dodatkowo możesz zlokalizować e-maila weryfikacyjnego, aktualizując kod języka w instancji Auth przed wysłaniem e-maila. Przykład:
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();
Ustawianie hasła użytkownika
Hasło użytkownika możesz ustawić za pomocą metody updatePassword
. Przykład:
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."); } } });
Wysyłanie e-maila do resetowania hasła
Możesz wysłać użytkownikowi e-maila z możliwością zresetowania hasła, korzystając z metody sendPasswordResetEmail
. Przykład:
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."); } } });
Szablon e-maila używany w sekcji uwierzytelniania w konsoli Firebase możesz dostosować na stronie Szablony e-maila. Więcej informacji znajdziesz w sekcji Szablony e-maili w Centrum pomocy Firebase.
Stan można też przekazać za pomocą adresu URL do kontynuowania, aby przekierować użytkownika z powrotem do aplikacji podczas wysyłania e-maila do resetowania hasła.
Dodatkowo możesz zlokalizować e-maila z prośbą o zresetowanie hasła, aktualizując kod języka w instancji Auth przed wysłaniem e-maila. Przykład:
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();
Możesz też wysyłać e-maile do zresetowania hasła z konsoli Firebase.
Usuwanie użytkownika
Konto użytkownika możesz usunąć za pomocą metody delete
. Przykład:
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."); } } });
Użytkowników możesz też usunąć w sekcji uwierzytelniania w konsoli Firebase na stronie Użytkownicy.
Ponowne uwierzytelnianie użytkownika
Niektóre działania związane z bezpieczeństwem, takie jak usuwanie konta, ustawienie podstawowego adresu e-mail i zmiana hasła, wymagają, aby użytkownik zalogował się niedawno. Jeśli wykonasz jedno z tych działań, a użytkownik zalogował się zbyt dawno, działanie się nie powiedzie i zostanie zwrócony błąd FirebaseAuthRecentLoginRequiredException
.
W takim przypadku ponownie uwierzytelnij użytkownika, uzyskując od niego nowe dane logowania i przekazując je do reauthenticate
. Przykład:
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."); } });
Importowanie kont użytkowników
Konta użytkowników możesz importować z pliku do projektu Firebase, używając polecenia auth:import
w wierszu poleceń Firebase. Przykład:
firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14