Tworzenie konta użytkownika
Nowego użytkownika możesz utworzyć na te sposoby:
Z aplikacji: utwórz nowego użytkownika w projekcie w Firebase, wywołując metodę
CreateUserWithEmailAndPasswordlub logując użytkownika po raz pierwszy za pomocą dostawcy tożsamości sfederowanej, takiego jak Logowanie przez Google lub Zaloguj się przez Facebooka.W konsoli Firebase: utwórz nowego użytkownika uwierzytelnianego hasłem na karcie Zabezpieczenia > Uwierzytelnianie > Użytkownicy.
Pobieranie informacji o obecnie zalogowanym użytkowniku
Zalecanym sposobem na uzyskanie bieżącego użytkownika jest ustawienie detektora na obiekcie Auth:
Firebase.Auth.FirebaseAuth auth; Firebase.Auth.FirebaseUser user; // Handle initialization of the necessary firebase modules: void InitializeFirebase() { Debug.Log("Setting up Firebase Auth"); auth = Firebase.Auth.FirebaseAuth.DefaultInstance; auth.StateChanged += AuthStateChanged; AuthStateChanged(this, null); } // Track state changes of the auth object. void AuthStateChanged(object sender, System.EventArgs eventArgs) { if (auth.CurrentUser != user) { bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null; if (!signedIn && user != null) { Debug.Log("Signed out " + user.UserId); } user = auth.CurrentUser; if (signedIn) { Debug.Log("Signed in " + user.UserId); } } } // Handle removing subscription and reference to the Auth instance. // Automatically called by a Monobehaviour after Destroy is called on it. void OnDestroy() { auth.StateChanged -= AuthStateChanged; auth = null; }
Dzięki temu obiekt Auth nie będzie w stanie pośrednim (np. inicjowania), gdy pobierzesz bieżącego użytkownika.
Możesz też pobrać dane obecnie zalogowanego użytkownika, wywołując funkcję CurrentUser. Jeśli użytkownik nie jest zalogowany, CurrentUser zwróci wartość null. Jeśli użytkownik jest wylogowany, jego IsValid() zwróci wartość false.
Zachowywanie danych logowania użytkownika
Dane logowania użytkownika zostaną zapisane w lokalnym magazynie kluczy po zalogowaniu się użytkownika. Lokalną pamięć podręczną danych logowania użytkownika można usunąć, wylogowując go. Magazyn kluczy zależy od platformy:
- Platformy Apple: Keychain Services.
- Android: Magazyn kluczy Androida.
- Windows: Credential Management API.
- OS X: Keychain Services.
- Linux: libsecret, który użytkownik musi mieć zainstalowany.
Pobieranie profilu użytkownika
Aby uzyskać informacje o profilu użytkownika, użyj akcesorów instancji Firebase.Auth.FirebaseUser. Na przykład:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; if (user != null) { string name = user.DisplayName; string email = user.Email; System.Uri photo_url = user.PhotoUrl; // 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 User.TokenAsync() instead. string uid = user.UserId; }
Pobieranie informacji o profilu użytkownika u konkretnego dostawcy
Aby uzyskać informacje o profilu pobrane od dostawców logowania powiązanych z użytkownikiem, użyj metody ProviderData. Na przykład:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; if (user != null) { foreach (var profile in user.ProviderData) { // Id of the provider (ex: google.com) string providerId = profile.ProviderId; // UID specific to the provider string uid = profile.UserId; // Name, email address, and profile photo Url string name = profile.DisplayName; string email = profile.Email; System.Uri photoUrl = profile.PhotoUrl; } }
Aktualizowanie profilu użytkownika
Podstawowe informacje o profilu użytkownika, takie jak wyświetlana nazwa i adres URL zdjęcia profilowego, możesz zaktualizować za pomocą metody UpdateUserProfile. Na przykład:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; if (user != null) { Firebase.Auth.UserProfile profile = new Firebase.Auth.UserProfile { DisplayName = "Jane Q. User", PhotoUrl = new System.Uri("https://example.com/jane-q-user/profile.jpg"), }; user.UpdateUserProfileAsync(profile).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("UpdateUserProfileAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("UpdateUserProfileAsync encountered an error: " + task.Exception); return; } Debug.Log("User profile updated successfully."); }); }
Ustawianie adresu e-mail użytkownika
Adres e-mail użytkownika możesz ustawić za pomocą metody UpdateEmail. Na przykład:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; if (user != null) { user.UpdateEmailAsync("user@example.com").ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("UpdateEmailAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("UpdateEmailAsync encountered an error: " + task.Exception); return; } Debug.Log("User email updated successfully."); }); }
Wysyłanie e-maila weryfikacyjnego do użytkownika
Możesz wysłać e-maila weryfikacyjnego do użytkownika za pomocą metody SendEmailVerification. Na przykład:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; if (user != null) { user.SendEmailVerificationAsync().ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("SendEmailVerificationAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("SendEmailVerificationAsync encountered an error: " + task.Exception); return; } Debug.Log("Email sent successfully."); }); }
Możesz dostosować szablon e-maila na karcie Bezpieczeństwo > Uwierzytelnianie > Szablony w konsoli Firebase. Więcej informacji znajdziesz w artykule Szablony e-maili w Centrum pomocy Firebase.
Ustawianie hasła użytkownika
Hasło użytkownika możesz ustawić za pomocą metody UpdatePassword. Na przykład:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; string newPassword = "SOME-SECURE-PASSWORD"; if (user != null) { user.UpdatePasswordAsync(newPassword).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("UpdatePasswordAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("UpdatePasswordAsync encountered an error: " + task.Exception); return; } Debug.Log("Password updated successfully."); }); }
Wysyłanie e-maila z prośbą o zresetowanie hasła
Możesz wysłać użytkownikowi e-maila z prośbą o zresetowanie hasła, korzystając z metody SendPasswordResetEmail. Na przykład:
string emailAddress = "user@example.com"; if (user != null) { auth.SendPasswordResetEmailAsync(emailAddress).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("SendPasswordResetEmailAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("SendPasswordResetEmailAsync encountered an error: " + task.Exception); return; } Debug.Log("Password reset email sent successfully."); }); }
Możesz dostosować szablon e-maila na karcie Bezpieczeństwo > Uwierzytelnianie > Szablony w konsoli Firebase. Więcej informacji znajdziesz w artykule Szablony e-maili w Centrum pomocy Firebase.
E-maile z linkiem do resetowania hasła możesz też wysyłać z konsoli Firebase.
Usuwanie użytkownika
Konto użytkownika możesz usunąć za pomocą metody Delete. Na przykład:
Firebase.Auth.FirebaseUser user = auth.CurrentUser; if (user != null) { user.DeleteAsync().ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("DeleteAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("DeleteAsync encountered an error: " + task.Exception); return; } Debug.Log("User deleted successfully."); }); }
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 związane z bezpieczeństwem, takie jak usunięcie konta, ustawienie podstawowego adresu e-mail i zmiana hasła, wymagają, aby użytkownik niedawno się zalogował. Jeśli wykonasz jedną z tych czynności, a użytkownik zalogował się zbyt dawno temu, działanie się nie powiedzie.
W takim przypadku ponownie uwierzytelnij użytkownika, uzyskując od niego nowe dane logowania i przekazując je do Reauthenticate. Na przykład:
Firebase.Auth.FirebaseUser user = 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. Firebase.Auth.Credential credential = Firebase.Auth.EmailAuthProvider.GetCredential("user@example.com", "password1234"); if (user != null) { user.ReauthenticateAsync(credential).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("ReauthenticateAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("ReauthenticateAsync encountered an error: " + task.Exception); return; } Debug.Log("User reauthenticated successfully."); }); }
Importowanie kont użytkowników
Konta użytkowników możesz importować z pliku do projektu Firebase za pomocą polecenia auth:import wiersza poleceń Firebase. Na przykład:
firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14