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

Kullanıcı oluşturma

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

Oturum açmış olan kullanıcıyı alma

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

Dinleyici kullanarak mevcut kullanıcıyı aldığınızda Auth nesnesinin başlatma gibi bir ara durumda olmadığından emin olursunuz.

Oturum açmış olan kullanıcıyı CurrentUser yöntemini çağırarak da alabilirsiniz. Kullanıcı oturum açmamışsa CurrentUser null değerini döndürür. Kullanıcının oturumu kapalıysa kullanıcının IsValid() değeri false değerini döndürür.

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

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

Kullanıcı profili alma

Bir kullanıcının profil bilgilerini almak için Firebase.Auth.FirebaseUser örneğinin erişim 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

UpdateUserProfile yöntemini kullanarak bir kullanıcının temel profil bilgilerini (kullanıcının görünen adı ve profil fotoğrafı URL'si) 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 bir 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ılara 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 bir kullanıcının şifresini 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ı hesapları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.");
  });
}

Kullanıcıları Firebase konsolunda Güvenlik > Kimlik doğrulama > Kullanıcılar sekmesinden de 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 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ının oturum açma işlemi çok uzun süre önce yapılmışsa işlem başarısız olur.

Bu durumda, kullanıcıdan yeni oturum açma kimlik bilgilerini alıp Reauthenticate yöntemine 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 CLI'nin auth:import komutunu kullanarak bir dosyadan Firebase projenize kullanıcı hesaplarını içe aktarabilirsiniz. Örneğin:

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