ユーザ登録と認証


このチュートリアルではFirebase Authentication サービスのセットアップでユーザー登録と認証を行うサービス.FireBaseは、あなたが開発プロセスの他の部分に集中できるようにユーザー認証のプロセスを簡素化します.
ソースコードの完成GitHub .
を使用してアプリケーションを作成するCreate React App とFirebaseのインストールReact Router 以下のコマンドを実行することによる依存関係
npx create-react-app react-firebase-auth
cd react-firebase-auth
npm install firebase react-router-dom

セットアップfirebase


クリエイトアFirebase account と“新しいプロジェクト”を追加します.
セットアップを完了するようプロンプトに従ってください.

Webオプションを使用してアプリケーションにFireBaseを追加します.
Firebaseセットアップを完了するには、認証メソッドを指定する必要があります.利用可能なメソッドがいくつかありますが、このチュートリアルでは、メールメソッドとパスワードメソッドを使用します.“認証”-“サインインメソッド”に移動し、“電子メール/パスワード”のステータス設定を“有効”に変更します.

firebase設定


次の場所に新しいファイルを作成しますsrc/config.js .
このファイルインポートのFirebase SDKには、FireBase設定の設定があります.
import firebase from "firebase/app";
import "firebase/auth";

const firebaseConfig = firebase.initializeApp({
  apiKey: "AIzaSyBRnU-ukg1hajloAXYxmU_2wiKnwbNKDhA",
  authDomain: "react-firebase-auth-6270e.firebaseapp.com",
  databaseURL: "https://react-firebase-auth-6270e.firebaseio.com",
  projectId: "react-firebase-auth-6270e",
  storageBucket: "react-firebase-auth-6270e.appspot.com",
  messagingSenderId: "83091629514",
  appId: "1:83091629514:web:99702034755a934a5a9b33",
});

export default firebaseConfig;
FireBaseコンソールの「プロジェクト設定」>「一般」からこれらの設定をコピーしてください.

サインアップフォーム


次の場所に新しいファイルを作成しますsrc/components/SignUp.js .
このコンポーネントには、サインアップフォームが含まれています.
import React, {useState} from "react";
import { Redirect } from "react-router-dom";
import firebaseConfig from "../config";

const SignUp = () => {
  const [currentUser, setCurrentUser] = useState(null);    
  const handleSubmit = (e) => {
    e.preventDefault();    
    const { email, password } = e.target.elements;
    try {
      firebaseConfig.auth().createUserWithEmailAndPassword(email.value, password.value);      
      setCurrentUser(true);
    } catch (error) {
      alert(error);
    }
  };
  if (currentUser) {
      return <Redirect to="/dashboard" />;
  }
  return (
    <>
      <h1>Sign Up</h1>
      <form onSubmit={handleSubmit}>
        <label for="email">Email</label>
        <input type="email" name="email" placeholder="Email" />
        <label for="password">Password</label>
        <input type="password" name="password" placeholder="Password" />
        <button type="submit">Submit</button>
      </form>
    </>
  );
};

export default SignUp;
フォームの送信で我々は電子メール&パスワードを通過しているFirebase Authに入力createUserWithEmailAndPassword メソッド.成功した場合、ブラウザは、認証されたユーザーにのみ表示されるコンテンツを含むダッシュボードページにリダイレクトされます.サインアップが失敗して、エラーを記述している警告メッセージが引き起こされるならば.

認証


次の場所に新しいファイルを作成しますsrc/components/Auth.js .
このコンポーネントは、ユーザーが認証されたかどうかを判断します.
import React, { useEffect, useState } from "react";
import firebaseConfig from "../config.js";

export const AuthContext = React.createContext();

export const AuthProvider = ({ children }) => {
  const [loading, setLoading] = useState(true);
  const [currentUser, setCurrentUser] = useState(null);
  useEffect(() => {
    firebaseConfig.auth().onAuthStateChanged((user) => {
      setCurrentUser(user);
      setLoading(false);
    });
  }, []);
  if (loading) {
    return <p>Loading...</p>;
  }
  return (
    <AuthContext.Provider value={{ currentUser }}>
      {children}
    </AuthContext.Provider>
  );
};
ここで我々はAuthContext 現在のユーザーステータスを共有するためのオブジェクトです.onAuthStateChanged ユーザのサインイン状態への変更のためのオブザーバです.これはユーザーのログイン時またはサインアウト時にトリガされます.

ログインフォーム


次の場所に新しいファイルを作成しますsrc/components/LogIn.js .
このコンポーネントには、ユーザーがアカウントに署名できるようにログが含まれています.
import React, { useContext } from "react";
import { Redirect } from "react-router-dom";
import { AuthContext } from "./Auth";
import firebaseConfig from "../config.js";

const LogIn = () => {
  const handleSubmit = (e) => {
    e.preventDefault();
    const { email, password } = e.target.elements;
    try {
      firebaseConfig.auth().signInWithEmailAndPassword(email.value, password.value);
    } catch (error) {
      alert(error);
    }
  };
  const { currentUser } = useContext(AuthContext);
  if (currentUser) {
    return <Redirect to="/dashboard" />;
  }
  return (
    <>
      <h1>Log In</h1>
      <form onSubmit={handleSubmit}>
        <label for="email">Email</label>
        <input type="email" name="email" placeholder="Email" />
        <label for="password">Password</label>
        <input type="password" name="password" placeholder="Password" />
        <button type="submit">Submit</button>
      </form>
    </>
  );
};

export default LogIn;
現在のユーザが既にログインしていれば、ダッシュボードにリダイレクトされます.それ以外の場合は、送信時にフォームの入力をキャプチャし、詳細をFireBase Authに送信しますsignInWithEmailAndPassword メソッド.

ダッシュボード


次の場所に新しいファイルを作成しますsrc/components/Dashboard.js .
このコンポーネントには、認証されたユーザーのみが閲覧できるコンテンツが含まれます.
import React, { useContext } from "react";
import { Redirect } from "react-router-dom";
import { AuthContext } from "./Auth";
import firebaseConfig from "../config.js";

const Dashboard = () => {
  const { currentUser } = useContext(AuthContext);
  if (!currentUser) {
    return <Redirect to="/login" />;
  }
  return (
    <div>
      <h1>Welcome</h1>
      <p>This is the dashboard, if you can see this you're logged in.</p>
      <button onClick={() => firebaseConfig.auth().signOut()}>Sign out</button>
    </div>
  );
};

export default Dashboard;
このページが非認証されたユーザーによってアクセスされるならば、ブラウザーはログインページに直結します.ユーザーが認証されている場合は、プライベートコンテンツを表示します.また、ユーザーが自分のアカウントから署名できるようにボタンが含まれている.

のホームページ


次の場所に新しいファイルを作成しますsrc/components/Home.js .
このコンポーネントは認証ステータスに基づいて関連ページへのリンクを含みます.
import React, { useContext } from "react";
import { Link } from "react-router-dom";
import { AuthContext } from "./Auth";

const Home = () => {
  const { currentUser } = useContext(AuthContext);
  return (
    <>
      <h1>Home</h1>
      {currentUser ? (
        <p>
          You are logged - <Link to="/dashboard">View Dashboard</Link>
        </p>
      ) : (
        <p>
          <Link to="/login">Log In</Link> or <Link to="/signup">Sign Up</Link> 
        </p>
      )}
    </>
  );
};

export default Home;
アプリケーション内の任意の場所で我々のステータスをチェックすることができますcurrentUser と、このステータスに基づいて別のコンテンツを表示します.ここでは、認証されたユーザーのための個人的なダッシュボードへのリンクを提供して、非認証されたユーザーのためにログイン/サインアップリンクを記録しました.

アプリで一緒にすべてを引く。js


変更するApp.js 以下を含むファイル
import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Home from "./components/Home";
import Dashboard from "./components/Dashboard";
import LogIn from "./components/LogIn";
import SignUp from "./components/SignUp";
import { AuthProvider } from "./components/Auth";

const App = () => {
  return (
    <AuthProvider>
      <Router>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route exact path="/dashboard" component={Dashboard} />
          <Route exact path="/login" component={LogIn} />
          <Route exact path="/signup" component={SignUp} />
        </Switch>
      </Router>
    </AuthProvider>
  );
};

export default App;
これで実行できますnpm start アプリケーションを起動し、登録および認証プロセスをテストします.一旦登録フォームが提出されるならば、あなたは登録を確認するためにFirebaseコンソールの「認証」-「ユーザー」を閲覧することができて、成功して、ユーザーアカウントを管理することができます.

これで、FireBaseを使用して反応アプリケーションでユーザーを認証する方法を知っています.FireBase認証についてもっと知りたいなら、チェックアウトしてくださいofficial guide .