FireBase Authentication - wds

akshdesai1

AKSH DESAI

Posted on January 19, 2023

FireBase Authentication - wds

Folder Structure

Output Image

App.js Code

import Dashboard from "./Components/Dashboard";
import Login from "./Components/Login";
import PrivateRoute from "./Components/PrivateRoute";
import Signup from "./Components/Signup";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";


function App() {

  return (
    < >
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<PrivateRoute>  <Dashboard name='aksh' /> </PrivateRoute>} />
          <Route path="/signup" element={<Signup />} />
          <Route path="/login" element={<Login />} />
          <Route path="*" element={<h1> Error: 404 Not Found </h1>} />
        </Routes>
      </BrowserRouter>

    </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Dashboard.js Code

import React from 'react'
import { useAuth } from '../Context/AuthContext';
import { Link, useNavigate } from 'react-router-dom';


const Dashboard = (props) => {
  const { currentUser, signout } = useAuth();
  const navigate = useNavigate();

  console.log('props', props);

  async function handleClick() {
    try {
      await signout();
      // navigate('/login')
    } catch (error) {
      console.log('error', error)
    }
  }

  return (
    <>

      <h3> DashBoard  </h3>
      <p>
        Name - {currentUser && currentUser.email}
      </p>

      <Link className='btn btn-primary w-100' to='update-profile'>Update Profile</Link>
      <button className="btn-primary" onClick={handleClick}>Logout</button>
    </>
  )
}

export default Dashboard

Enter fullscreen mode Exit fullscreen mode

Login.js Code

import { useState, useRef } from 'react'
import { useAuth } from '../Context/AuthContext';
import { NavLink, useNavigate } from 'react-router-dom';

const Login = () => {
    const emailRef = useRef();
    const passwordRef = useRef();

    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);

    const { login, currentUser } = useAuth();
    const navigate = useNavigate();

    async function handleSubmit(e) {
        e.preventDefault();

        try {
            setLoading(true);
            setError('');
            await login(emailRef.current.value, passwordRef.current.value);
            navigate('/');
        } catch (e) {
            setError(`${e.message}`)
        }

        setLoading(false);
    }
    return (
        <div className="row d-flex justify-content-center vh-100 align-items-center">
            <div className="col-md-6  mx-auto bg-dark text-light">
                {currentUser && currentUser.email}
                {error === '' ? null : <h6 className="alert alert-danger"> {error}  </h6>}

                <form onSubmit={handleSubmit}>
                    <h1 className="text-center"> Sign Up </h1>
                    <div className="mb-3">
                        <label htmlFor="email" className="form-label">Email address</label>
                        <input type="email" className="form-control" id="email" ref={emailRef} aria-describedby="emailHelp" />

                    </div>
                    <div className="mb-3">
                        <label htmlFor="password" className="form-label">Password</label>
                        <input type="password" className="form-control" ref={passwordRef} id="password" />
                    </div>

                    <button type="submit" disabled={loading} className="btn btn-primary"> {loading ? "Loading" : "Login"} </button>

                    <br />
                    <NavLink to='/signup' className="text-white">Don't have an account? Signup Here </NavLink>
                </form>
            </div>

        </div>
    )
}

export default Login;

Enter fullscreen mode Exit fullscreen mode

PrivateRoute.js

import React from 'react'
import { Navigate, Route } from 'react-router-dom'
import { useAuth } from '../Context/AuthContext';


export default function PrivateRoute({ children }) {
    const { currentUser } = useAuth();
    console.log('rest', children);
    return (
        currentUser ? children : <Navigate to='/login' />
    )
}

Enter fullscreen mode Exit fullscreen mode

Signup.js Code

import { useState, useRef } from 'react'
import { useAuth } from '../Context/AuthContext';
import { NavLink, useNavigate, useLoaderData} from 'react-router-dom';


const Signup = () => {
  const emailRef = useRef();
  const passwordRef = useRef();
  const passwordConfirmRef = useRef();

  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const { signup, currentUser } = useAuth();

  const navigate = useNavigate();

  async function handleSubmit(e) {
    e.preventDefault();

    if (passwordRef.current.value !== passwordConfirmRef.current.value) {
      return setError('Password do not Match.');
    }

    try {
      setLoading(true);
      setError('');
      await signup(emailRef.current.value, passwordRef.current.value);
      navigate('/');
    } catch (e) {
      setError(`${e.message}`)
    }

    setLoading(false);
  }
  return (

    <div className="row d-flex justify-content-center vh-100 align-items-center">
      <div className="col-md-6  mx-auto bg-dark text-light">
        {currentUser && currentUser.email}
        {error === '' ? null : <h6 className="alert alert-danger"> {error}  </h6>}

        <form onSubmit={handleSubmit}>
          <h1 className="text-center"> Sign Up </h1>
          <div className="mb-3">
            <label htmlFor="email" className="form-label">Email address</label>
            <input type="email" className="form-control" id="email" ref={emailRef} aria-describedby="emailHelp" />
            <div id="emailHelp" className="form-text text-white">We'll never share your email with anyone else.</div>
          </div>
          <div className="mb-3">
            <label htmlFor="password" className="form-label">Password</label>
            <input type="password" className="form-control" ref={passwordRef} id="password" />
          </div>
          <div className="mb-3">
            <label htmlFor="confirm-password" className="form-label">Password Confirm</label>
            <input type="password" className="form-control" ref={passwordConfirmRef} id="confirm-password" />
          </div>

          <button type="submit" disabled={loading} className="btn btn-primary"> {loading ? "Loading" : "Submit"} </button>

          <br />
          <NavLink to='/login' className="text-white">Already have an account? Login Here </NavLink>
        </form>
      </div>

    </div>
  )
}

export default Signup;

Enter fullscreen mode Exit fullscreen mode

firebase-config.js Code


import { getFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth";
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// TODO: Add SDKs for 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: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const db = getFirestore(app);
const auth = getAuth(app);

export default db;
export { auth };
Enter fullscreen mode Exit fullscreen mode

AuthContext.js Code

import React, { useContext, useState, useEffect } from 'react'
import { createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut} from "firebase/auth";
import { auth } from '../config/firebase-config';


const AuthContext = React.createContext();

const useAuth = () => {
    return useContext(AuthContext);
};

const AuthProvider = ({ children }) => {
    const [currentUser, setCurrentUser] = useState();
    const [loading, setLoading] = useState(true);

    function signup(email, password) {
        return createUserWithEmailAndPassword(auth, email, password)
    }

    function login(email, password) {
        return signInWithEmailAndPassword(auth, email, password)
    }

    function signout() {
        return signOut(auth)
    }

    useEffect(() => {
        const unSubscribe = auth.onAuthStateChanged((user) => {
            setCurrentUser(user);
            setLoading(false);
        });

        return unSubscribe;
    }, [])

    const value = {
        currentUser,
        signup,
        login,
        signout
    };
    return (
        <AuthContext.Provider value={value}>
            {!loading && children}
        </AuthContext.Provider>
    )
};

export default AuthContext;

export { useAuth, AuthProvider }; 
Enter fullscreen mode Exit fullscreen mode

Output 1

Output 2

Thank You.
You can follow us on:
Instagram for full stack web Development

💖 💪 🙅 🚩
akshdesai1
AKSH DESAI

Posted on January 19, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related