Firebase でユーザーを管理する

ユーザーを作成する

createUserWithEmailAndPassword メソッドを呼び出すか、Google ログインFacebook ログインなどのフェデレーション ID プロバイダを使用してユーザーが初めてログインすると、Firebase プロジェクトに新しいユーザーが作成されます。

Firebase コンソールの [Authentication] セクションにある [Users] ページで、または Admin SDK を使用して、パスワードで認証される新しいユーザーを作成することもできます。

現在ログインしているユーザーを取得する

現在ログインしているユーザーを取得するには、Auth オブジェクトでオブザーバーを設定することをおすすめします。

ウェブ向けのモジュラー API

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

ウェブ向けの名前空間付き API

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

オブザーバーを使うと、現在ログインしているユーザーを取得するときに Auth オブジェクトが中間状態(初期化など)ではないことを確認できます。signInWithRedirect を使用すると、onAuthStateChanged オブザーバーは getRedirectResult が解決された後にトリガーされます。

現在ログインしているユーザーを取得するには、currentUser プロパティを使用します。ユーザーがログインしていない場合、currentUser は null です。

ウェブ向けのモジュラー API

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

ウェブ向けの名前空間付き API

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

ユーザーのプロフィールを取得する

ユーザーのプロフィール情報を取得するには、User のインスタンスのプロパティを使用します。次に例を示します。

ウェブ向けのモジュラー API

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

ウェブ向けの名前空間付き API

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

ユーザーのプロバイダ別のプロフィール情報を取得する

ユーザーにリンクされているログイン プロバイダからプロフィール情報を取得する場合は、providerData プロパティを使用します。次に例を示します。

ウェブ向けのモジュラー API

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

ウェブ向けの名前空間付き API

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

ユーザーのプロフィールを更新する

updateProfile メソッドを使用して、ユーザーの基本的なプロフィール情報(ユーザーの表示名とプロフィール写真の URL)を更新できます。次に例を示します。

ウェブ向けのモジュラー API

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

ウェブ向けの名前空間付き API

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

ユーザーのメールアドレスを設定する

updateEmail メソッドを使用して、ユーザーのメールアドレスを設定できます。次に例を示します。

ウェブ向けのモジュラー API

import { getAuth, updateEmail } from "firebase/auth";
const auth = getAuth();
updateEmail(auth.currentUser, "user@example.com").then(() => {
  // Email updated!
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

ウェブ向けの名前空間付き API

const user = firebase.auth().currentUser;

user.updateEmail("user@example.com").then(() => {
  // Update successful
  // ...
}).catch((error) => {
  // An error occurred
  // ...
});

ユーザーに確認メールを送信する

sendEmailVerification メソッドを使用して、ユーザーにアドレス確認メールを送信できます。次に例を示します。

ウェブ向けのモジュラー API

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

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

ウェブ向けの名前空間付き API

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

Firebase コンソールの [Authentication] セクションにある [テンプレート] ページで使用されるメール テンプレートをカスタマイズできます。Firebase ヘルプセンターでメール テンプレートについての記事をご覧ください。

確認メールを送信するときに、続行 URL を使用して状態を渡し、アプリにリダイレクトすることもできます。

さらに、メールを送信する前に Auth インスタンスの言語コードを更新して、確認メールをローカライズすることもできます。次に例を示します。

ウェブ向けのモジュラー API

import { getAuth } from "firebase/auth";

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

ウェブ向けの名前空間付き API

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

ユーザーのパスワードを設定する

updatePassword メソッドを使用して、ユーザーのパスワードを設定できます。次に例を示します。

ウェブ向けのモジュラー API

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

ウェブ向けの名前空間付き API

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

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

パスワードの再設定メールを送信する

sendPasswordResetEmail メソッドを使用して、ユーザーにパスワードの再設定メールを送信できます。次に例を示します。

ウェブ向けのモジュラー API

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

ウェブ向けの名前空間付き API

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

Firebase コンソールの [Authentication] セクションにある [テンプレート] ページで使用されるメール テンプレートをカスタマイズできます。Firebase ヘルプセンターでメール テンプレートについての記事をご覧ください。

パスワードの再設定メールを送信するときに、続行 URL を使用して状態を渡し、アプリにリダイレクトすることもできます。

さらに、メールを送信する前に Auth インスタンスの言語コードを更新して、パスワードの再設定メールをローカライズすることもできます。次に例を示します。

ウェブ向けのモジュラー API

import { getAuth } from "firebase/auth";

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

ウェブ向けの名前空間付き API

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

Firebase コンソールからパスワードの再設定メールを送信することもできます。

ユーザーを削除する

delete メソッドを使用して、ユーザー アカウントを削除できます。次に例を示します。

ウェブ向けのモジュラー API

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

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

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

ウェブ向けの名前空間付き API

const user = firebase.auth().currentUser;

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

Firebase コンソールの [Authentication] セクションにある [Users] ページでユーザーを削除することもできます。

ユーザーを再認証する

アカウントの削除メインのメールアドレスの設定パスワードの変更といったセキュリティ上重要な操作を行うには、ユーザーが最近ログインしている必要があります。ユーザーが最近ログインしていない場合、このような操作を行うと失敗し、エラーになります。このような場合は、ユーザーから新しいログイン認証情報を取得して reauthenticateWithCredential に渡し、ユーザーを再認証します。次に例を示します。

ウェブ向けのモジュラー API

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

ウェブ向けの名前空間付き API

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

ユーザー アカウントをインポートする

ユーザー アカウントをファイルから Firebase プロジェクトにインポートするには、Firebase CLI の auth:import コマンドを使用します。次に例を示します。

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