firebasefirebase-authentication

Prevent unverified email to login using firebase Authentication


I am able to send a verification email after the user has registered, but the user is automatically logged in. How can I prevent a user from being logged in until they verify their email?

async registerUser(customer: Customer, password: string) {
        try {
            const newUserCredential = await this.firebaseAuth.createUser(
                customer.email,
                password
            );
            // store user details in firestore
            this.firebaseStore.storeUserDetails(newUserCredential, customer);
                await newUserCredential.user.sendEmailVerification();
                return newUserCredential;
        } catch (error) {
            console.error(error);
            throw new Error(error.message);
        }
    }

Solution

  • You cannot prevent users from logging in to your application. However you can check if their email is verified to authorize access to any of your project resources.

    In your web app you can check the emailVerified property which is true is the email is verified. Just check if the email is verified, if not then force log them out (also log them out after sending the verification email). But this is just client side validation so you must make sure you have proper security rules or validations on your server.

    If you are using security rules for realtime database, you can verify if the email is verified there as well.

    ".read": "auth != null && auth.token.email_verified"
    

    Same goes for Firestore's security rules:

    allow read: if request.auth.token.email_verified;