ReactにおけるFirebase認証
以下のコマンドで react-firebase-hooks と firebase パッケージをインストールします:
npm install --save firebase react-firebase-hooks
Note
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;
ユーザーの認証IDトークンの設定
以下のコードは、Firebase から Firebase Authentication トークンを取得し、それを 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 code
@secureCollection('users', 'read')
secureUsersRead(context: QueryContext<User>): boolean {
const userAuth = this.getUserAuth();
... // Take action with auth information
}
Squid backend におけるデータのセキュリティ設定の詳細については、documentation on security rules をご覧ください。