メインコンテンツまでスキップ

React における Firebase Auth

react-firebase-hooks および firebase パッケージをインストールします:

npm install --save firebase react-firebase-hooks
注意

react-firebase-hooks は Firebase によって保守されていないサードパーティ製のパッケージです。このパッケージを使わない選択もできますが、その場合、auth token を最新の状態に保つための observability を扱う独自のコードを記述・保守する必要があります。

Initialize Firebase

src ディレクトリに firebase.ts という名前の Firebase 設定ファイルを作成し、以下の情報を提供してください:

Client code
// Import the functions you need from the SDKs you need
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';

// TODO: Add SDKs for other Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration

const firebaseConfig = {
apiKey: 'YOUR_FIREBASE_API-KEY',
authDomain: 'YOUR_FIREBASE_PROJECT_ID.firebaseapp.com',
projectId: 'YOUR_FIREBASE_PROJECT_ID',
appId: 'YOUR_FIREBASE_APP_ID',
};

// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
export const auth = getAuth(firebaseApp);
export default firebaseApp;

ユーザーの auth ID トークンを設定する

以下のコードは、Firebase から Firebase Authentication token を取得し、それを Squid backend に渡します。そこから、データや API へのアクセスを管理するための auth context にアクセスできます。

Client code
import { useState, useEffect } from 'react';
import { useSquid } from '@squidcloud/react';
import { useIdToken } from 'react-firebase-hooks/auth';
import { auth } from './firebase.ts';
import './App.css';


function App() {
// Get Firebase Authentication state
const [user, loading, error] = useIdToken(auth);
const { setAuthProvider } = useSquid();

useEffect(() => {
// Pass the auth token to the Squid backend
setAuthProvider({
integrationId: 'YOUR_FIREBASE_AUTH_INTEGRATION_ID',
getToken: async () => {
if (!user) return undefined;
return await user.getIdToken();
},
});
if (loading) return;
if (!user) {
// Change the view as needed for when a user is logged out.
} else {
// Change the view as needed for when a user is logged in.
}
}, [user, loading, setAuthProvider]);

以下は、backend で認証情報にアクセスする方法の例です:

Backend code
@secureCollection('users', 'read')
secureUsersRead(context: QueryContext<User>): boolean {
const userAuth = this.getUserAuth();
... // Take action with auth information
}

Squid backend におけるデータ保護の詳細については、documentation on security rules をご覧ください。