Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

Organization

【Firebase】Google認証情報 Firestore 保存

目標

Firebase AuthenticationでGoogle認証後、認証情報をFirestoreに保存したい

前提

  • React環境
  • Firebase Authentication、Firestore組込み済み
  • FirebaseUIを利用した認証

処理

  1. Firebase Authenticationで認証
  2. FirebaseUIのcallbackを利用してFirestoreへ認証情報を保存

実装

signin.jsx

import 'firebase/auth';
import '@firebase/firestore';
import firebase from 'firebase/app';
import MyApp from '../components/MyApp';
import React from 'react';
import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth';


export default function SignIn() {
  const db = firebase.firestore();

  const uiConfig = {
    signInFlow: 'popup',
    signInSuccessUrl: '/mypage',
    signInOptions: [
      firebase.auth.GoogleAuthProvider.PROVIDER_ID,
    ],
    callbacks: {
      signInSuccessWithAuthResult: (authResult) => {
        const user = authResult.user;
        const isNewUser = authResult.additionalUserInfo.isNewUser;

        // 初回Google認証時のみDB保存
        if (isNewUser) {
          writeNameToDB(user);
        }

        return true;
      },
    },
  };

  // usersコレクションにuidをドキュメントIDとして、
  // displayName(Googleアカウント名)をnameフィールドに保存
  const writeNameToDB = async (user) => {
    db.collection('users').doc(user.uid).set({
      name: user.displayName,
    });

    // 3秒程待たないとDBに保存できない...
    await new Promise((resolve) => setTimeout(resolve, 3000));
  };

  return (
    <MyApp>
      {/* firebaseui-web-reactを使用(便利ラッパーありがてぇ〜) */}
      <StyledFirebaseAuth
        uiConfig={uiConfig}
        firebaseAuth={firebase.auth()}
      />
    </MyApp>
  );
}

まとめ

  • FirebaseUIのcallbackを利用すると簡単に認証情報をDB保存できる
  • DB保存後、3秒程待機すると上手くDB保存ができた(ここ、もっと良い実装あるはず。。。

参考文献

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?