LoginSignup
4
4

More than 5 years have passed since last update.

Firebase Authenticationで作成されたユーザーをFirestoreに放り込んでいろいろしたい

Last updated at Posted at 2019-04-17

やりたいこと

Firebase Authenticationでログインしたユーザーに、より多くの情報を持たせたい。
ので Firestore で 'users' collection を作ってFirebase Authenticationのユーザーをそこに放り込んでいろいろしたい。

とりあえずコード

function googleLogin() {
  const googleAuth = new firebase.auth.GoogleAuthProvider();
  firebase.auth().signInWithPopup(googleAuth).then((cred) => {
    const db = firebase.firestore();
    const users = db.collection('users');
    users.doc(cred.user.uid).set({
      datetime: moment().format('YYYY/MM/DD HH:mm'),
    });
  });
}

流れ

  1. Firebase Authenticationでログイン(今回はGoogle Auth)
  2. [1]でログインしたユーザーに自動的に固有のIDが付与される
  3. Firestore に 'users' collection を作る
  4. [3]に[2]のユーザーIDと同じIDのdocumentを作る

詳細

Googleアカウントでログイン

const googleAuth = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(googleAuth);

ここまででログインはできます。

ログインしたユーザーの情報を得る

firebase.auth().signInWithPopup(googleAuth).then((cred) => {
  ...
})

signInWithRedirect という方法もあるけど、それだとユーザー情報を返してくれません。
signInWithPopupだとcredentialreturnしてくれるのでそれを使います。

users collectionを作成する

const db = firebase.firestore();
const users = db.collection('users');

users collectionの中にdocumentを作成する

users.doc(cred.user.uid).set({
  datetime: moment().format('YYYY/MM/DD HH:mm'),
})

documentがひとつも入ってないとcollectionを作ってくれません。
なのでとりあえず作成日時でも入れておきます。
(ここではmoment.jsを使用しています)

おしまい

これでuser IDをdocumentで管理して都度突合したりしなくていい!やったー!

参考

Firebase Auth Tutorial #15- Firestore Users Collection

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4