React における Firebase Auth
react-firebase-hooks と firebase パッケージをインストールします:
npm install --save firebase react-firebase-hooks
注
react-firebase-hooks は Firebase によってメンテナンスされていないサードパーティ製パッケージです。このパッケージを使用しない選択もできますが、その場合は auth token を最新の状態に保つための監視(observability)を扱うコードを自分で書いてメンテナンスする必要があります。
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 token を設定する
以下のコードは、Firebase から Firebase Authentication token を取得して Squid backend に渡します。そこから auth context にアクセスして、データや API へのアクセスを管理できます。
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 でデータを保護する方法の詳細は、security rules のドキュメント を参照してください。