Home > front end >  Can't verify email and password from Firebase
Can't verify email and password from Firebase

Time:10-16

I'm creating a signup form and trying to get the email and password to work. When I used input and set the state with the appropriate values, it works just fine, but once I wrap the Input around my custom component its unable to get data from the component into the state and gives me an error that a user cannot be found (even if their info is in the Firebase Auth) I need help.

Auth.js

import style from "./auth.module.css";
import { useEffect, useRef, useState } from "react";
import { useAuthState } from 'react-firebase-hooks/auth';
import { auth, signInWithEmailAndPassword, signInWithGoogle } from "../../firebase";
import { CSSTransition } from "react-transition-group";


export default function Auth() {
  const [activeMenu, setActiveMenu] = useState("main");
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [user, loading, error] = useAuthState(auth);

  let domNode = useClickOutside(() => {
    setActiveMenu(false);
  });

  return (
    <div className={style.container}>
      <Login />
      <Signup />
    </div>
  );

  function AuthType(props) {
    return (
      <a
        href={props.link}
        className={style.menuItem}
        onClick={() => props.goToMenu && setActiveMenu(props.goToMenu)}
      >
        {props.children}
      </a>
    );
  }

/* I believe you've switched up the login and sign-up? */
  function Login() {

    return (
      <CSSTransition in={activeMenu === "main"} unmountOnExit timeout={500}>
        <div ref={domNode}>
          <div className={style.login}>
            <h1 className={style.title}>Clip It</h1>
            {/* Email and Password */}
            <Emailform 
              label="Email" 
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              />

            <Passform 
              label="Password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              />

            <div className={style.button}>
              <input 
                type="submit" 
                value="Login"
                onClick={() => signInWithEmailAndPassword(email, password)} />
              <input 
                type="submit" 
                value="Login with Google"
                onClick={signInWithGoogle} />
            </div>
            <div className={style.text}>
              <p className={style.plink}>Forgot Password</p>
              <div>
                Need an account?&nbsp;
                <AuthType goToMenu="Signup">click here</AuthType>
              </div>
            </div>
          </div>
        </div>
      </CSSTransition>
    );
  }


  function Signup() {
    return (
      <CSSTransition in={activeMenu === "Signup"} unmountOnExit timeout={500}>
        <div ref={domNode}>
          <div className={style.signUp}>
            <div className={style.title}> Clip It</div>
            <Form label="First Name" type="text" />
            <Form label="Last Name" type="Text" />
            <Form label="Email" type="email" />
            <Form label="Date of Birth" type="date" />
            <Form label="Password" type="password" />
            <Form label="Confirm Password" type="password" />
            <div className={style.button}>
              <input type="submit" value="Sign Up" />
            </div>
            <div className={style.text}>
              have an&nbsp;
              <AuthType goToMenu="main"> account</AuthType>
            </div>
          </div>
        </div>
      </CSSTransition>
    );
  }
}
let useClickOutside = (handler) => {
  let domNode = useRef();

  useEffect(() => {
    let clickListener = (event) => {
      if (domNode.current && !domNode.current.contains(event.target)) {
        handler();
      }
    };

    document.addEventListener("mousedown", clickListener);

    return () => {
      document.removeEventListener("mousedown", clickListener);
    };
  });
  return domNode;
};

function Form(props) {
  return (
    <div className={style.formBox}>
      <label className={style.label}>{props.label}:</label>

      <form className={style.input}>
        <input 
          type={props.input} 
          name={props.input} 
          required="true" />
      </form>
    </div>
  );
}

function Emailform(props) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  return (
    <div className={style.formBox}>
      <label className={style.label}>{props.label}:</label>

      <form className={style.input}>
        <input 
          type="email" 
          name={props.input} 
          required="true"
          value={email} 
          onChange={(e) => setEmail(e.target.value)} />
      </form>
    </div>
  );
}

function Passform(props) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  return (
    <div className={style.formBox}>
      <label className={style.label}>{props.label}:</label>

      <form className={style.input}>
        <input 
          type="text" 
          name={props.input} 
          required="true"
          value={password} 
          onChange={(e) => setPassword(e.target.value)} />
      </form>
    </div>
  );
}

Firebase.js

import firebase from 'firebase/app';
//import * as firebase from "firebase/app";
import "firebase/auth"
import "firebase/firestore"

// For Firebase JS SDK v7.20.0 and later, measurementId is optional 
const firebaseConfig = {
  apiKey: "AIzaSyCq8BAlTWJXG7rFU95QkUTU8U0kXruPA9o",
  authDomain: "clip-it-70ff5.firebaseapp.com",
  databaseURL: "https://clip-it-70ff5-default-rtdb.firebaseio.com",
  projectId: "clip-it-70ff5",
  storageBucket: "clip-it-70ff5.appspot.com",
  messagingSenderId: "637963668511",
  appId: "1:637963668511:web:9cbd1deae03b819153d92a",
  measurementId: "G-8S1G78ZH49"
};

const app = !firebase.apps.length ? firebase.initializeApp(firebaseConfig) : firebase.app();

const auth = app.auth();
const db = app.firestore();

/* Using Google Authentication */
const googleProvider = new firebase.auth.GoogleAuthProvider();
//
  const signInWithGoogle = async () => {
    try {
      const res = await auth.signInWithPopup(googleProvider);
      const user = res.user;
      const query = await db
        .collection("users")
        .where("uid", "==", user.uid)
        .get();
      if (query.docs.length === 0) {
        await db.collection("users").add({
          uid: user.uid,
          name: user.displayName,
          authProvider: "google",
          email: user.email,
        });
        alert("You're logged in");
      }
    } catch (err) {
      console.error(err);
      alert(err.message);
    }
  };


  /* Using Email and Password */
  // Sign/Logging In
  const signInWithEmailAndPassword = async (email, password) => {
    try {
      await auth.signInWithEmailAndPassword(email.trim(), password);
      alert("You've logged in successfuly");
    } catch (err) {
      console.error(err);
      alert("The email or password is incorrect, please try again");
    }
  };

  //SigningUp
  const registerWithEmailAndPassword = async (name, email, password) => {
    try {
      const res = await auth.createUserWithEmailAndPassword(email.trim(), password);
      const user = res.user;
      await db.collection("users").add({
        uid: user.uid,
        name,
        authProvider: "local",
        email,
      });
    } catch (err) {
      console.error(err);
      alert(err.message);
    }
  };

  //Sending Password reset link
  const sendPasswordResetEmail = async (email) => {
    try {
      await auth.sendPasswordResetEmail(email);
      alert("Password reset link sent!");
    } catch (err) {
      console.error(err);
      alert(err.message);
    }
  };

  const logout = () => {
    auth.signOut();
  }; // Log out

  export {
    signInWithGoogle,
    signInWithEmailAndPassword,
    registerWithEmailAndPassword,
    sendPasswordResetEmail,
    logout,
    auth,
    db,
  };

  

CodePudding user response:

Your code has a list of issues.

  1. You have email/password states in both EmailForm/PassForm, as well as the parent (Auth) component.
  2. You're setting values and trying to handle onChange on the EmailForm/PassForm components, but you never actually call these props, and you never actually set some of the props you're trying to access (ex: name={props.input}).
  3. The inputs inside those two components are setting the email/password states to themselves, yet your Auth component is feeding Firebase its own states for email/password, which you never actually set.

You should also never use an input of type="text" for password fields.

If you insist on keeping the structure you currently have, move the EmailForm and PassForm functions inside to your Auth component, remove the props you're setting onto them, remove their states, and just use the Auth component's state.

// Inside the Auth component
const EmailForm = () => {
  return (
    <div className={style.formBox}>
      <label className={style.label}>{props.label}:</label>

      <form className={style.input}>
        <input 
          type="email" 
          name="email"
          required="true"
          value={email} 
          onChange={(e) => setEmail(e.target.value)} />
      </form>
    </div>
  );
}

const PassForm = () => {
  return (
    <div className={style.formBox}>
      <label className={style.label}>{props.label}:</label>

      <form className={style.input}>
        <input 
          type="password"
          name="password"
          required="true"
          value={password} 
          onChange={(e) => setPassword(e.target.value)} />
      </form>
    </div>
  );
}

Then call them with a simple

<EmailForm />
<PassForm />
  • Related