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

Kullanıcı oluşturma

createUserWithEmailAndPassword yöntemini çağırarak veya Google ile oturum açma ya da Facebook ile oturum açma gibi birleşik kimlik sağlayıcıları kullanarak bir kullanıcının oturumunu ilk kez açarak Firebase projenizde yeni bir kullanıcı oluşturursunuz.

Firebase konsolunun Kimlik Doğrulama bölümünden, Kullanıcılar sayfasından veya Yönetici SDK'sını kullanarak da şifreyle kimliği doğrulanmış yeni kullanıcılar oluşturabilirsiniz.

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

Geçerli kullanıcıyı almanın önerilen yolu, Auth nesnesine bir gözlemci ayarlamaktır:

Web

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/auth.user
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

Web

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/v8/firebase.User
    var uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

Bir gözlemci kullanarak, geçerli kullanıcıyı aldığınızda Auth nesnesinin başlatma gibi bir ara durumda olmadığından emin olursunuz. signInWithRedirect kullanıldığında onAuthStateChanged gözlemcisi, getRedirectResult çözülene kadar tetiklenmez.

currentUser özelliğini kullanarak da şu anda oturum açmış olan kullanıcıyı alabilirsiniz. Kullanıcı oturum açmadıysa currentUser null olur:

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

if (user) {
  // User is signed in, see docs for a list of available properties
  // https://firebase.google.com/docs/reference/js/auth.user
  // ...
} else {
  // No user is signed in.
}

Web

const user = firebase.auth().currentUser;

if (user) {
  // User is signed in, see docs for a list of available properties
  // https://firebase.google.com/docs/reference/js/v8/firebase.User
  // ...
} else {
  // No user is signed in.
}

Kullanıcı profilini alma

Bir kullanıcının profil bilgilerini almak için User örneğinin özelliklerini kullanın. Örneğin:

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;
if (user !== null) {
  // The user object has basic properties such as display name, email, etc.
  const displayName = user.displayName;
  const email = user.email;
  const photoURL = user.photoURL;
  const emailVerified = user.emailVerified;

  // 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.getToken() instead.
  const uid = user.uid;
}

Web

const user = firebase.auth().currentUser;
if (user !== null) {
  // The user object has basic properties such as display name, email, etc.
  const displayName = user.displayName;
  const email = user.email;
  const photoURL = user.photoURL;
  const emailVerified = user.emailVerified;

  // 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.getIdToken() instead.
  const uid = user.uid;
}

Kullanıcının sağlayıcıya özgü 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 mülkünü kullanın. Örneğin:

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

if (user !== null) {
  user.providerData.forEach((profile) => {
    console.log("Sign-in provider: " + profile.providerId);
    console.log("  Provider-specific UID: " + profile.uid);
    console.log("  Name: " + profile.displayName);
    console.log("  Email: " + profile.email);
    console.log("  Photo URL: " + profile.photoURL);
  });
}

Web

const user = firebase.auth().currentUser;

if (user !== null) {
  user.providerData.forEach((profile) => {
    console.log("Sign-in provider: " + profile.providerId);
    console.log("  Provider-specific UID: " + profile.uid);
    console.log("  Name: " + profile.displayName);
    console.log("  Email: " + profile.email);
    console.log("  Photo URL: " + profile.photoURL);
  });
}

Kullanıcı profilini güncelleme

Kullanıcının temel profil bilgilerini (kullanıcı adı ve profil fotoğrafı URL'si) updateProfile yöntemiyle güncelleyebilirsiniz. Örneğin:

Web

import { getAuth, updateProfile } from "firebase/auth";
const auth = getAuth();
updateProfile(auth.currentUser, {
  displayName: "Jane Q. User", photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(() => {
  // Profile updated!
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

Web

const user = firebase.auth().currentUser;

user.updateProfile({
  displayName: "Jane Q. User",
  photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(() => {
  // Update successful
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});  

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

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

Web

import { getAuth, updateEmail } from "firebase/auth";
const auth = getAuth();
updateEmail(auth.currentUser, "[email protected]").then(() => {
  // Email updated!
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

Web

const user = firebase.auth().currentUser;

user.updateEmail("[email protected]").then(() => {
  // Update successful
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

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:

Web

import { getAuth, sendEmailVerification } from "firebase/auth";

const auth = getAuth();
sendEmailVerification(auth.currentUser)
  .then(() => {
    // Email verification sent!
    // ...
  });

Web

firebase.auth().currentUser.sendEmailVerification()
  .then(() => {
    // Email verification sent!
    // ...
  });

Firebase konsolunun Kimlik Doğrulama bölümünde kullanılan e-posta şablonunu E-posta Şablonları sayfasından özelleştirebilirsiniz. Firebase Yardım Merkezi'ndeki E-posta Şablonları başlıklı makaleyi inceleyin.

Doğrulama e-postası gönderirken uygulamaya geri yönlendirmek için durumu bir devam URL'si aracılığıyla da iletebilirsiniz.

Ayrıca, e-postayı göndermeden önce Auth örneğindeki dil kodunu güncelleyerek doğrulama e-postasını yerelleştirebilirsiniz. Örneğin:

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
auth.languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// auth.useDeviceLanguage();

Web

firebase.auth().languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// firebase.auth().useDeviceLanguage();

Kullanıcı şifresi belirleme

Kullanıcının şifresini updatePassword yöntemiyle ayarlayabilirsiniz. Örneğin:

Web

import { getAuth, updatePassword } from "firebase/auth";

const auth = getAuth();

const user = auth.currentUser;
const newPassword = getASecureRandomPassword();

updatePassword(user, newPassword).then(() => {
  // Update successful.
}).catch((error) => {
  // An error ocurred
  // ...
});

Web

const user = firebase.auth().currentUser;
const newPassword = getASecureRandomPassword();

user.updatePassword(newPassword).then(() => {
  // Update successful.
}).catch((error) => {
  // An error ocurred
  // ...
});

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

Web

import { getAuth, sendPasswordResetEmail } from "firebase/auth";

const auth = getAuth();
sendPasswordResetEmail(auth, email)
  .then(() => {
    // Password reset email sent!
    // ..
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    // ..
  });

Web

firebase.auth().sendPasswordResetEmail(email)
  .then(() => {
    // Password reset email sent!
    // ..
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    // ..
  });

Firebase konsolunun Kimlik Doğrulama bölümünde kullanılan e-posta şablonunu E-posta Şablonları sayfasından özelleştirebilirsiniz. Firebase Yardım Merkezi'ndeki E-posta Şablonları başlıklı makaleyi inceleyin.

Şifre sıfırlama e-postası gönderirken kullanıcıyı uygulamaya geri yönlendirmek için durumu bir devam URL'si aracılığıyla da iletebilirsiniz.

Ayrıca, e-postayı göndermeden önce Auth örneğindeki dil kodunu güncelleyerek şifre sıfırlama e-postasını yerelleştirebilirsiniz. Örneğin:

Web

import { getAuth } from "firebase/auth";

const auth = getAuth();
auth.languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// auth.useDeviceLanguage();

Web

firebase.auth().languageCode = 'it';
// To apply the default browser preference instead of explicitly setting it.
// firebase.auth().useDeviceLanguage();

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

Web

import { getAuth, deleteUser } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

deleteUser(user).then(() => {
  // User deleted.
}).catch((error) => {
  // An error ocurred
  // ...
});

Web

const user = firebase.auth().currentUser;

user.delete().then(() => {
  // User deleted.
}).catch((error) => {
  // An error ocurred
  // ...
});

Kullanıcıları, Firebase konsolunun Kimlik Doğrulama bölümündeki Kullanıcılar sayfasından da silebilirsiniz.

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

Hesap silme, birincil e-posta adresi ayarlama ve şifre değiştirme gibi güvenlik açısından hassas bazı 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 bir hatayla başarısız olur. Bu durumda, kullanıcıdan yeni oturum açma kimlik bilgilerini alarak ve kimlik bilgilerini reauthenticateWithCredential'e ileterek kullanıcının kimliğini yeniden doğrulayın. Örneğin:

Web

import { getAuth, reauthenticateWithCredential } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

// TODO(you): prompt the user to re-provide their sign-in credentials
const credential = promptForCredentials();

reauthenticateWithCredential(user, credential).then(() => {
  // User re-authenticated.
}).catch((error) => {
  // An error ocurred
  // ...
});

Web

const user = firebase.auth().currentUser;

// TODO(you): prompt the user to re-provide their sign-in credentials
const credential = promptForCredentials();

user.reauthenticateWithCredential(credential).then(() => {
  // User re-authenticated.
}).catch((error) => {
  // An error occurred
  // ...
});

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

Firebase CLI'nin 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