Firebase ReactFire v4 の概要 - ログイン、ログアウト、アカウントの作成、保護されたルート
概要
これは、アプリケーションで ReactFire v4 を使用するコード例の簡単なチュートリアルです.このアプリケーションは、ログイン、ログアウト、アカウントの作成、および保護されたルートをサポートしています.また、v3 に存在していた AuthCheck コンポーネントが ReactFire の v4 には存在しないため、ルートを保護するための 2 つのアプローチについても説明します.
これは、以前にリリースされた reactfire イントロ アプリケーションと v3 で動作していた video の更新バージョンです.この新しいコードは v4 で動作します.
このビデオのソース コードと、ルートを保護するための 2 つのアプローチは、github repo で入手できます.
コードは UI に Ionic Framework を使用しますが、コードは反応するため、すべての reactjs ベースのアプリケーションで動作するはずです
ビデオ
コード
I am using Firebase Emulator in my project, if you are going to do the same, be sure you are using node v16 otherwise you will run into issues Issue In StackOverflow
ログインコード
reactFire の
getAuth
フックが必要ですconst auth = getAuth();
次に、auth オブジェクトを使用して、ユーザー資格情報でサインインするための呼び出しを行います
const doSignIn = () => {
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
console.log(user);
history.push("/home");
return true;
})
.catch(async (error) => {
const errorCode = error.code;
const errorMessage = error.message;
await alert({
header: "Error Signing In",
message: errorMessage,
buttons: ["OK"],
});
});
};
アカウントコードの作成
reactFire の
getAuth
フックが必要ですconst auth = getAuth();
次に、auth オブジェクトを使用して呼び出しを行い、ユーザー資格情報を使用してユーザー アカウントを作成します.
const doCreateAccount = () => {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
console.log(user);
history.replace("/");
return true;
})
.catch(async (error) => {
const errorCode = error.code;
const errorMessage = error.message;
await alert({
header: "Error Creating Account",
message: errorMessage,
buttons: ["OK"],
});
});
};
サインアウト コード
reactFire の
getAuth
フックが必要ですconst auth = getAuth();
次に、認証オブジェクトを使用して、ユーザーをサインアウトするための呼び出しを行います
<IonButton
onClick={async () => {
await signOut(auth);
history.replace("/login");
}}>
SIGN OUT
</IonButton>
認証ユーザーをチェックするための 2 つのアプローチ
どちらの場合も、すべてのルートを
AuthProvider
と FirestoreProvider
でラップする必要があります. return (
<IonApp>
<AuthProvider sdk={auth}>
<FirestoreProvider sdk={firestoreDatabase}>
... Routes Go Here ...
</FirestoreProvider>
</AuthProvider>
</IonApp>
);
};
PrivateRoute コンポーネント
PrivateRoute
コンポーネントを使用して、保護されたルートの Route コンポーネントの代わりに PrivateRoute コンポーネントを使用して Router
をセットアップします.Note here we need to use the Ionic specific Router
IonReactRouter
but it can be replaced withReactRouter
in a react application
<IonReactRouter>
<IonRouterOutlet>
<Route path="/" exact={true}>
<Redirect to="/home" />
</Route>
<PrivateRoute path="/home" exact={true}>
<Home />
</PrivateRoute>
<Route path="/login" exact={true}>
<Login />
</Route>
<Route path="/create-account" exact={true}>
<CreateAccount />
</Route>
</IonRouterOutlet>
</IonReactRouter>
反応ルーターのドキュメントから..
for this to work with IonicReactRouter, I had to remove the location from being passed in to the redirect as state. IonicRouter doesnt support Switch, so the thing just kept looping
// A wrapper for <Route> that redirects to the login
// screen if you're not yet authenticated.
export const PrivateRoute = ({
children,
location,
...rest
}: React.PropsWithChildren<any>) => {
const { status, data: signInCheckResult } = useSigninCheck();
console.log(signInCheckResult);
debugger;
if (status === "loading") {
return <IonLoading isOpen={status === "loading"} />;
}
return (
<Route
{...rest}
render={({ location }) =>
signInCheckResult.signedIn === true ? (
children
) : (
<Redirect
to={{
pathname: "/login",
}}
/>
)
}
/>
);
};
AuthWrapper コンポーネント
ここでは、ルーターを少し異なる方法でセットアップする必要があります.
AuthWrapper
コンポーネントを使用して v3 で行ったのと同様に、すべてのルートを AuthCheck
でラップしていることがわかります. <AuthWrapper fallback={<AuthRoute />}>
<Route path="/" exact={true}>
<Redirect to="/home" />
</Route>
<Route path="/home" exact={true}>
<Home />
</Route>
</AuthWrapper>
認証されたユーザーがいない場合は、
fallback
ルートも指定する必要があります.保護されていないすべてのルートを含む別のコンポーネントを作成しました.Note when using IonicReactRouter this code will not work properly since IonicReactRouter doesn't support
Switch
at the top level.
const AuthRoute = () => {
return (
<Switch>
<Route path="/login" exact={true}>
<Login />
</Route>
<Route path="/create-account" exact={true}>
<CreateAccount />
</Route>
<Route path="*" exact={true}>
<Redirect to="/login" />
</Route>
</Switch>
);
};
ReactFire のサンプル コードから、これが
AppAuthWrapper.tsx
にあることを確認してください. AuthWrapper コードは、AuthCheck
コンポーネントの削除を考慮して reactfire repo からのものです.export const AuthWrapper = ({
children,
fallback,
}: React.PropsWithChildren<{ fallback: JSX.Element }>): JSX.Element => {
const { status, data: signInCheckResult } = useSigninCheck();
console.log(signInCheckResult);
if (!children) {
throw new Error("Children must be provided");
}
if (status === "loading") {
return <IonLoading isOpen={status === "loading"} />;
} else if (signInCheckResult.signedIn === true) {
return children as JSX.Element;
}
return fallback;
};
コンデンサの使用
コンデンサを使用する場合は、認証を別の方法で初期化する必要があります.
バグを参照してください - https://github.com/firebase/firebase-js-sdk/issues/5552#issuecomment-929580662
const auth = initializeAuth(app, {
persistence: indexedDBLocalPersistence
});
// browser only
// const auth = getAuth(app);
アーロンクサンダース / クイック-イントロ-reactfire-v4
ReactFire v4 サンプル アプリケーションの簡単な紹介
認証ユーザーをチェックするための 2 つのアプローチ
反応ルーターのドキュメントから..
for this to work with IonicReactRouter, I had to remove the location from being passed in to the redirect as state. IonicRouter doesnt support Switch, so the thing just kept looping
//ログインにリダイレクトする
//まだ認証されていない場合は画面を表示します.
export const PrivateRoute = ({
子供、
位置、
...休み
}: React.PropsWithChildren
const { status, data: signInCheckResult } = useSigninCheck(…
View on GitHub
Reference
この問題について(Firebase ReactFire v4 の概要 - ログイン、ログアウト、アカウントの作成、保護されたルート), 我々は、より多くの情報をここで見つけました https://dev.to/aaronksaunders/intro-to-reactfire-v4-login-logout-create-account-and-protected-routes-37e5テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol