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

Kullanıcı oluşturma

Yeni kullanıcı oluşturmak için aşağıdaki seçeneklerden yararlanabilirsiniz:

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

Geçerli kullanıcıyı almanın önerilen yolu, Auth nesnesinde bir dinleyici ayarlamaktır:

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

Bir dinleyici kullanarak, mevcut kullanıcıyı aldığınızda Auth nesnesinin ara durumda (ör. başlatma) olmamasını sağlarsınız.

Ayrıca CurrentUser işlevini çağırarak şu anda oturum açmış kullanıcıyı da alabilirsiniz. Kullanıcı oturum açmamışsa CurrentUser null değerini döndürür. Bir kullanıcının oturumu kapatılırsa kullanıcının IsValid() değeri false (yanlış) olur.

Kullanıcı kimlik bilgilerini kalıcı hale getirme

Kullanıcının kimlik bilgileri, kullanıcı oturum açtıktan sonra yerel anahtar deposunda saklanır. Kullanıcı kimlik bilgilerinin yerel önbelleği, kullanıcının oturumu kapatılarak silinebilir. Anahtar deposu platforma özgüdür:

Kullanıcı profili alma

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

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

Kullanıcının sağlayıcıya özel profil bilgilerini alma

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

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

Kullanıcı profilini güncelleme

Kullanıcının görünen adı ve profil fotoğrafı URL'si gibi temel profil bilgilerini UpdateUserProfile yöntemiyle güncelleyebilirsiniz. Örneğin:

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

Kullanıcının e-posta adresini ayarlama

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

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

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:

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

Firebase konsolunun Güvenlik > Kimlik doğrulama > Şablonlar sekmesinde hangi e-posta şablonunun kullanılacağını özelleştirebilirsiniz. Firebase Yardım Merkezi'ndeki E-posta Şablonları başlıklı makaleyi inceleyin.

Kullanıcı şifresi belirleme

UpdatePassword yöntemini kullanarak kullanıcı şifresi ayarlayabilirsiniz. Örneğin:

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

Ş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:

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

Firebase konsolunun Güvenlik > Kimlik doğrulama > Şablonlar sekmesinde hangi e-posta şablonunun kullanılacağını özelleştirebilirsiniz. Firebase Yardım Merkezi'ndeki E-posta Şablonları başlıklı makaleyi inceleyin.

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

Kullanıcı silme

Delete yöntemini kullanarak kullanıcı hesabını silebilirsiniz. Örneğin:

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

Ayrıca, Firebase konsolunda Güvenlik > Kimlik doğrulama > Kullanıcılar sekmesinden de kullanıcıları silebilirsiniz.

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

Hesap silme, birincil e-posta adresi ayarlama ve şifre değiştirme gibi güvenlikle ilgili bazı hassas 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.

Bu durumda, kullanıcıdan yeni oturum açma kimlik bilgileri alıp bu kimlik bilgilerini Reauthenticate'ya ileterek kullanıcının kimliğini yeniden doğrulayın. Örneğin:

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

Kullanıcı hesaplarını içe aktarma

Firebase KSA'nın 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