やりたいこと
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'),
});
});
}
流れ
- Firebase Authenticationでログイン(今回はGoogle Auth)
- [1]でログインしたユーザーに自動的に固有のIDが付与される
- Firestore に 'users' collection を作る
- [3]に[2]のユーザーIDと同じIDのdocumentを作る
詳細
Googleアカウントでログイン
const googleAuth = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(googleAuth);
ここまででログインはできます。
ログインしたユーザーの情報を得る
firebase.auth().signInWithPopup(googleAuth).then((cred) => {
...
})
signInWithRedirect
という方法もあるけど、それだとユーザー情報を返してくれません。
signInWithPopup
だとcredential
をreturn
してくれるのでそれを使います。
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で管理して都度突合したりしなくていい!やったー!