I'm trying to create a Firebase authentication system in my React web app. I know how to register an account and I know how to send a verification email out. Upon registration it sends the verification email which is fine, but the account gets added to the Firebase console database before the user has even verified it. I want it to be such that only verified accounts are added to the database.
Here is my code:
import React, { useState, useEffect, useRef } from 'react'
import './join.css'
import { Link, useNavigate } from 'react-router-dom'
import { auth } from '../firebase'
import { createUserWithEmailAndPassword, onAuthStateChanged, sendEmailVerification } from "firebase/auth"
export default function Join() {
const [registerEmail, setRegisterEmail] = useState('');
const [registerPassword, setRegisterPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [user, setUser] = useState({});
const verificationMessage = useRef();
useEffect(() => {
onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});
}, [])
const navigate = useNavigate();
const register = async () => {
try {
const user = await createUserWithEmailAndPassword(auth, registerEmail, registerPassword);
console.log(user);
} catch (error) {
console.log(error.message);
}
}
const handleSubmit = event => {
if (registerPassword === confirmPassword) {
sendEmailVerification(auth.currentUser);
verificationMessage.current.style.display = 'block';
register();
event.preventDefault();
}
else {
alert('Passwords do not match, please try again!');
event.preventDefault();
}
}
return (
<>
<div className="signup-div">
<h2>Sign Up</h2>
<form onSubmit={handleSubmit}>
<fieldset>
<label className='labels'>Email:</label><br />
<input placeholder='Please enter your email' type="email" value={registerEmail} onChange={e => setRegisterEmail(e.target.value)} required />
</fieldset>
<fieldset>
<label className='labels'>Set Password:</label><br />
<input placeholder='Create password' type="password" value={registerPassword} onChange={e => setRegisterPassword(e.target.value)} required />
</fieldset>
<fieldset>
<label className='labels'>Re-type password to confirm:</label><br />
<input placeholder="Confirm password" type="password" value={confirmPassword} onChange={e => setConfirmPassword(e.target.value)} required />
</fieldset>
<button type="submit">Sign Up</button>
</form>
<div>
Already have an account? <Link to="/login">Log In</Link>
</div>
</div>
<div className='verification-message' ref={verificationMessage}>Welcome aboard! Please check your inbox and click the link in our verification email to verify your account. This could take upto a few minutes to arrive.</div>
</>
)
}