2
votes

I am using the sdk to create a user and a db entry for the user which all works perfectly. Upon creation of the database entry I call a function to sendEmailVerification() but I am guessing this is a client side function as it returns null when being called.

What is the process to send the verify email directly from the admin sdk (if even possible). Currently what I do is send some JSON back to the client to say if the verification email sent successfully or not. But calling the function does not work so it doesn't get that far. Here is my function within node.

function verifiyEmail(email, res) {

    var user = admin.auth().currentUser;
    user.sendEmailVerification().then(function() {


        // Email sent.
        var jsonResponse = {

            status: 'success',
            alertText: '1',
            email: email
        }

        res.send(jsonResponse); 

    }, function(error) {

        // An error happened.
        var jsonResponse = {

            status: 'success',
            alertText: '0',
            email: email
        }

        res.send(jsonResponse); 

    });

}

UPDATE

I am guessing this isn't possible so I generate a custom token in node and send that back to the client. I then use the token I get back to try and sign the user in by calling the below however the signInWithCustomToken() fuction doesnt get called. Heres my code am I missing something. Seems like a lot of work just to send out the verification email!

function signInUserWithToken(token) {

    firebase.auth().signInWithCustomToken(token).catch(function(error) {

      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;

      console.log(errorCode);
      console.log(errorMessage);

      verifiyEmail();

    });
}

UPDATE 2

I scraped the token idea. All i do now is use the onAuthStateChanged() function and handle the email verification there in the client implementation. Its not perfect as this method gets called several times. However adding a flag seems to do the trick. Like the below.

function authListenerContractor() {
  // Listening for auth state changes.
  $('#not-verified').css('display','none'); 
  var flag = true;
  firebase.auth().onAuthStateChanged(function(user) {

        if (user) {

            // User is verified.
            var displayName = user.displayName;
            var email = user.email;
            var emailVerified = user.emailVerified;
            var photoURL = user.photoURL;
            var isAnonymous = user.isAnonymous;
            var uid = user.uid;
            var providerData = user.providerData;
            console.log("Email Verified?: " + emailVerified);

            if(emailVerified) {

                  window.location.href = "http://www.my-redirect-url.com";

            } else {

                if (flag == true) {

                    $('#not-verified').css('display','inherit');
                    verifiyEmail();

                    flag = false;
                }
            }

        } else {

            console.log("User is signed out.");
        }
   });
 }

function verifiyEmail() {

    var user = firebase.auth().currentUser;
    user.sendEmailVerification().then(function() {

        // Email sent.
        console.log("Verification email sent");
        $('#not-verified').text('**Email verification sent. Please check your email now!**');

    }, function(error) {

        // An error happened.
        console.log("Email verification not sent. An error has occurred! >>" + error);

    });
}
1
do you want to send the user a verification after something has been created in the firebase database ?Rahul Singh
@RahulSingh yes thats correct.Alex McPherson
you are using firebase cloud functions ?Rahul Singh
@RahulSingh not sure I follow. I am using the node.js firebase admin module only.Alex McPherson
There's an open issue in the Node.js Admin SDK requesting this feature: github.com/firebase/firebase-admin-node/issues/46. It might be useful to keep an eye on that ticket.Hiranya Jayathilaka

1 Answers

1
votes

This is a classic case to use Firebase Cloud Functions

Sending Welcome Mail Example

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');

const gmailEmail = encodeURIComponent(functions.config().gmail.email);
const gmailPassword = encodeURIComponent(functions.config().gmail.password);
const mailTransport = nodemailer.createTransport(
    `smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);


const APP_NAME = 'My App';


exports.sendWelcomeEmail = functions.auth.user().onCreate(event => {

  const user = event.data; // The Firebase user.

  const email = user.email; // The email of the user.
  const displayName = user.displayName; // The display name of the user.


  return sendWelcomeEmail(email, displayName);
});

function sendWelcomeEmail(email, displayName) {
  const mailOptions = {
    from: `${APP_NAME} <[email protected]>`,
    to: email
  };

  mailOptions.subject = `Welcome to ${APP_NAME}!`;
  mailOptions.text = `Hey ${displayName || ''}! Welcome to ${APP_NAME}. I hope you will enjoy our service.`;
  return mailTransport.sendMail(mailOptions).then(() => {
    console.log('New welcome email sent to:', email);
  });
}

Check this Link for More Info , used these functions to trigger a mail in this very app

UPDATE

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');


const mailTransport = nodemailer.createTransport(
  `smtps://emailid:[email protected]`);

const APP_NAME = 'My App';

exports.sendPageCountEmail = functions.database.ref('/yournode').onWrite(event => { // here we are specifiying the node where data is created
    const data = event.data;
    return sendEmail('emailid',data);
});


// Sends a welcome email to the given user.
function sendEmail(email,body) {
  const mailOptions = {
    from:`${APP_NAME}[email protected]`,
    to: email
  };

  mailOptions.subject = `Welcome to ${APP_NAME}!`;
  mailOptions.text = `Welcome to ${APP_NAME}.\n 
  return mailTransport.sendMail(mailOptions).then(() => {
      console.log('New welcome email sent to:', email);
});
}