Skip to content

Instantly share code, notes, and snippets.

@torresalmonte
Created December 17, 2018 16:59
Show Gist options
  • Save torresalmonte/203df1d544474c2cf2efff7cd8fe0f4a to your computer and use it in GitHub Desktop.
Save torresalmonte/203df1d544474c2cf2efff7cd8fe0f4a to your computer and use it in GitHub Desktop.
firebase admin sdk send verification email
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
// taken from here: https://stackoverflow.com/a/41886023/4139896
exports.testSendVerificationEmail = functions.https.onRequest(async (req, res) => {
const firebase = require('firebase');
var config = {
/* PUT YOUR PROJECT'S WEB APP CONFIG HERE */
};
const app = firebase.initializeApp(config);
var userData = {
email: "newUserEmail@example.com",
emailVerified: false,
};
try {
const user = await admin.auth().createUser(userData);
const token = await admin.auth().createCustomToken(user.uid);
const result = await firebase.auth().signInWithCustomToken(token);
await result.user.sendEmailVerification();
await firebase.auth().signOut();
res.send("OK")
} catch (err) {
console.log("ERROR:", err);
res.send("ERROR");
}
});
@roundrobin
Copy link

Can you post the solution?

@ShahoodulHassan
Copy link

Please give this a try. I can't test it right now but I believe I have incorporated all that was required. Oh and I copied the snippets from my code that is in Typescript not Javascript. So, u might have to make some corrections here and there.

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

// By default, firebase dependency is not included. I had to add it using instructions on the
// following link:
// https://stackoverflow.com/a/42846299/7983864
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithCustomToken, sendEmailVerification } from 'firebase/auth';

// taken from here: https://stackoverflow.com/a/41886023/4139896

export const testSendVerificationEmail = functions.https.onRequest(async (req, res) => {

// const firebase = require('firebase');

var config = {
    /* PUT YOUR PROJECT'S WEB APP CONFIG HERE */
};

const app = initializeApp(config);

const auth = getAuth(app);

var userData = {
    email: "newUserEmail@example.com",
    emailVerified: false,
};

try {
    const user = await admin.auth().createUser(userData);
    const token = await admin.auth().createCustomToken(user.uid);
    const result = await signInWithCustomToken(auth, token);
    await sendEmailVerification(result.user);
    await auth.signOut();

    res.send("OK")

} catch (err) {
    console.log("ERROR:", err);

    res.send("ERROR");
}

});

Hope it helps!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment