Firebase authentication web: how to verify email address

試著忘記壹切 提交于 2021-01-04 02:38:58

问题


I'm new to Firebase Authentication for the web. I managed to get a signup form working but I am running into problems with sending the email to verify the users email address. The user is created as normal and appears in my console but no verification email is sent and I get the following error in Chrome:

Uncaught TypeError: Cannot read property 'sendEmailVerification' of null

Here is the code I have so far:

"use strict";

(function () {

    // initialize firebase
    var config = {
        apiKey: "//api key",
        authDomain: "// etc",
        databaseURL: "// etc",
        projectId: "// etc",
        storageBucket: "// etc",
        messagingSenderId: "// etc"
    };
    firebase.initializeApp(config);

    // get the login form elements from HTML
    var txtEmail = document.getElementById('txtEmail');
    var txtPassword = document.getElementById('txtPassword');
    var btnLogin = document.getElementById('btnLogin');
    var btnSignUp = document.getElementById('btnSignUp');
    var btnLogout = document.getElementById('btnLogout');

    // add login event
    btnLogin.addEventListener('click', function (e) {
        // get email and pass
        var email = txtEmail.value;
        var pass = txtPassword.value;
        var auth = firebase.auth();
        // sign in 
        var promise = auth.signInWithEmailAndPassword(email, pass);
        promise.catch(function (e) {
            return console.log(e.message);
        });
    });

    // add signup event. the signup button sends user email and pass to firebase
    btnSignUp.addEventListener('click', function (e) {
        // get email and pass
        // TODO: validate email - check it is real
        var email = txtEmail.value;
        var pass = txtPassword.value;
        var auth = firebase.auth();
        var user = firebase.auth().currentUser;

        // sign in 
        var promise = auth.createUserWithEmailAndPassword(email, pass);
        promise.catch(function (e) {
            return console.log(e.message);
        }).then(function(){user.sendEmailVerification().then(function() {
          // Email sent.
        }, function(error) {
          // An error happened.
        })
                          }); // end verification
    }); // end sign up button event listener

    // show logout button when user is logged in
    // TODO: make sure the login form clears the credentials on logout
    btnLogout.addEventListener('click', function (e) {
        firebase.auth().signOut();
    });

    // realtime authentication listener
    firebase.auth().onAuthStateChanged(function (firebaseUser) {
        if (firebaseUser) {
            console.log(firebaseUser);
            btnLogout.classList.remove('hide');
            btnSignUp.classList.add('hide');
            btnLogin.classList.add('hide');
        } else {
            console.log('not logged in');
            btnLogout.classList.add('hide');
            btnSignUp.classList.remove('hide');
            btnLogin.classList.remove('hide');
        } // end if statement
    }); // end function
})();

I haven't found a straightforward example on how to do this and the docs just provide the code but no info on where put it. I appreciate your help. Thank you.

RESOLVED: Thank you for your help. It's working now. Here's the full working code:

"use strict";

(function () {

// initialize firebase 
 var config = {
 apiKey: "",
 authDomain: "",
 databaseURL: "",
 projectId: "",
 storageBucket: "",
 messagingSenderId: ""
 };
 firebase.initializeApp(config);

// get the login form elements from HTML
 var txtEmail = document.getElementById('txtEmail');
 var txtPassword = document.getElementById('txtPassword');
 var btnLogin = document.getElementById('btnLogin');
 var btnSignUp = document.getElementById('btnSignUp');
 var btnLogout = document.getElementById('btnLogout');

// login event
 btnLogin.addEventListener('click', function (e) {
 // get email and pass
 var email = txtEmail.value;
 var pass = txtPassword.value;
 var auth = firebase.auth();
 // sign in
 var promise = auth.signInWithEmailAndPassword(email, pass);
 promise.catch(function (e) {
 return console.log(e.message);
 });
 });

// add signup event. the signup button sends user email and pass to firebase
 btnSignUp.addEventListener('click', function (e) {
 // get email and pass
 // TODO: validate email - check it is real
 var email = txtEmail.value;
 var pass = txtPassword.value;
 var auth = firebase.auth();
 var user = firebase.auth().currentUser;

// create user and sign in
 var promise = auth.createUserWithEmailAndPassword(email, pass);
 promise.then(function(user) {
 user.sendEmailVerification().then(function() {
 // Email sent.
 }, function(error) {
 // An error happened.
 });
 }); 
 }); // end sign up button event listener

// show logout button when user is logged in
 btnLogout.addEventListener('click', function (e) {
 firebase.auth().signOut();
 });

// realtime authentication listener
 firebase.auth().onAuthStateChanged(function (firebaseUser) {
 if (firebaseUser) {
 console.log(firebaseUser);
 btnLogout.classList.remove('hide');
 btnSignUp.classList.add('hide');
 btnLogin.classList.add('hide');
 } else {
 console.log('not logged in');
 btnLogout.classList.add('hide');
 btnSignUp.classList.remove('hide');
 btnLogin.classList.remove('hide');
 } // end else statement
 }); // end function
 })();

回答1:


@Nagaraj N's solution is correct, you can also modify your code as follows:

    // sign in 
    var promise = auth.createUserWithEmailAndPassword(email, pass);
    promise.then(function(user) {// You are forgetting this reference.
      user.sendEmailVerification();
      // You can also call this.
      firebase.auth().currentUser.sendEmailVerification();
      // Email sent.
    }, function(error) {
      // An error happened.
    })`



回答2:


firebase.auth().currentUser will be null/undefined untill you are authenticated. Please try to send email as mentioned below.

firebase.auth().onAuthStateChanged(function (firebaseUser) {
        if (firebaseUser) {
          firebaseUser.sendEmailVerification().then(function() {
            // Email sent.
          }, function(error) {
            // An error happened.
          })
            ....

        } else {
            ....
        }
    });



回答3:


// sign in 
var promise = auth.createUserWithEmailAndPassword(email, pass);
promise.then(function(authData) {// You are forgetting this reference.
    authData.user.sendEmailVerification();
}, function(error) {
    // An error happened.
})

createUserWithEmailAndPassword returns authData so you need authData,user to send the email verification.



来源:https://stackoverflow.com/questions/44024634/firebase-authentication-web-how-to-verify-email-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!