React + Firestore + Authenticationの基本的な操作

目的

Firestoreにアクセスする際に認証を必要としたい。

認証のためのログインプロバイダはメール/パスワード(パスワード認証)のみ。

前提

Firestoreはテストモード。

Firestoreにcollection_nameという名前のコレクションが存在する。

Authenticationのログインプロバイダはメール/パスワードのみ有効化。

下記の認証用アカウントが存在する。

  • ID:aa@aa.com
  • パスワード:password

Firestoreのルール

設定したルールは公式の例にもある下記の通り。

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
    	allow read, write: if request.auth != null;
    }
  }
}

tsxファイルの内容

※ 変数名グチャグチャだけど気にしない。

※ コメントアウトを使って試せば把握できるはず。

import React from "react";
import ReactDOM from "react-dom/client";
import {initializeApp} from 'firebase/app';
import {
    getFirestore,
    collection,
    getDocs,
    deleteDoc,
    doc,
    setDoc,
    updateDoc,
} from 'firebase/firestore';
import {
    getAuth,
    signInWithEmailAndPassword,
    signOut
} from 'firebase/auth';

const firebaseConfig = {
    // apiKey等を設定するFirebaseプロジェクト固有の情報。
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth(app);

// サインイン処理。
await signInWithEmailAndPassword(auth, 'aa@aa.com', 'password')
    .then(async (userCredential) => {
        console.log('userCredential.user.uid = ', userCredential.user.uid);
        console.log('ログイン成功');
    })
    .catch((error) => {
        console.log('ログイン失敗');
    });

// Firestoreにデータ追加。
const fb_document = doc(db, 'collection_name', 'document_name');
const data = {
    first: 'ファースト',
    last: 'ラスト',
    born: 2023
};
await setDoc(fb_document, data);

// Firestoreのデータ更新。
const fb_doc = doc(db, 'collection_name', 'document_name');
const updateData = {
    born: 3024
};
await updateDoc(fb_doc, updateData);

// Firestoreからcollection_nameコレクションのドキュメント全て読み込み。
const fb_collection = collection(db, 'collection_name');
const querySnapShot = await getDocs(fb_collection);
querySnapShot.forEach((doc) => {
    console.log('ドキュメント識別子 = ', doc.id);
    console.log('born = ', doc.data().born);
});

// 指定したドキュメントを削除。
const fb_del_doc = doc(db, 'collection_name', 'document_name');
await deleteDoc(fb_del_doc);

// サインアウト処理。
signOut(auth);

ReactDOM.createRoot(document.getElementById('root')!).render(
    <React.StrictMode>
    </React.StrictMode>
);

コメント

タイトルとURLをコピーしました