React で Firebase Auth を使用する
react-firebase-hooks と firebase package を install します。
npm install --save firebase react-firebase-hooks
注記
react-firebase-hooks は Firebase により maintain されていない third-party package です。この package を使用しないこともできますが、auth token を最新に保つための observability を処理する独自 code を記述・maintain する必要があります。
Firebase を初期化する
src directory に firebase.ts という Firebase configuration file を作成します。次の情報を指定します。
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;
User の auth ID token を設定する
次の code は Firebase から Firebase Authentication token を取得し、Squid backend に渡します。そこから auth context に access し、data と API への access を管理できます。
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 で authentication information に access する方法の例です。
Backend code
@secureCollection('users', 'read')
secureUsersRead(context: QueryContext<User>): boolean {
const userAuth = this.getUserAuth();
... // Take action with auth information
}
Squid backend で data を保護する詳細については、security rules documentationを参照してください。