Open inlined opened 7 years ago
Hey there! I couldn't figure out what this issue is about, so I've labeled it for a human to triage. Hang tight.
Hmmm this issue does not seem to follow the issue template. Make sure you provide all the required information.
The issue/new feature request is that the user.sendEmailVerification()
function is not available on the firebase admin (firebase cloud functions), but it is available in the client sdk like the one used in angular 4.
From the Documentation when you create a New user. I added the sendEmailVerification() which this function is not available. But it's a must to allow at this time for the new user to verify their email before we allow access to our apps.
admin.auth().createUser({
email: "user@example.com",
emailVerified: false,
password: "secretPassword",
displayName: "John Doe",
photoURL: "http://www.example.com/12345678/photo.png",
disabled: false
})
.then(function(userRecord) {
// See the UserRecord reference doc for the contents of userRecord.
console.log("Successfully created new user:", userRecord.uid);
// ****************************************************************
// Cannot request/call the sendEmailVerification() function, not available
// Send Email Verification
user.sendEmailVerification()
.then(function (emailSent) {
console.log('emailSent ', emailSent);
})
.catch(function (error) {
console.log('emailSent error ', error);
});
// End send email verification not available
// ****************************************************************
})
.catch(function(error) {
console.log("Error creating new user:", error);
});
Please let me know if this explains the issue. Thanks.
Yes, would like this feature in cloud functions. user.sendEmailVerification()
The docs make it seem like its possible to verify a new user's email address with the firebase email validation using a cloud function. Lack of this feature forces developers to use an external service (which requires an upgraded paid plan). Requiring a third party dependency for something Firebase already does well is clunky for developers and confusing.
Hey @coreybutler, the email verification Firebase Auth sends is not a welcome nor a goodbye email (the link you pointed it out). Nor should it be used for that.
You also have the option to send an email verification client side for free. So if you want to send an email verification, you can always do it for free.
Let's keep these issues separate (sending email verifications, vs sending other personalized emails for non-auth specific reasons). We acknowledge the value of sending an email verification, server side via the admin SDK, and we are looking into it.
@bojeil-google - thanks.
Purely for context, my "app" doesn't have a front end. In my case, I'm using a cloud function to serve as a Docker Authentication Proxy... 100% server-side. Users are added directly through the Firebase console.
If this is a separate issue (which is fine), the docs should clarify. Perhaps indicate what limitations exist. A document titled "Extend Firebase Authentication with Cloud Functions" and a subtitle of "Trigger a function on user creation" seems like it would encompass email verification.
Hey @coreybutler, to help unblock you, you can always use the client SDK to send the email verification from a Firebase Function. You'd need to require firebase module. On user creation, you do the following:
uid
of the user created from the onCreate trigger.createCustomToken
for that user.signInWithCustomToken
using that custom token.currentUser.sendEmailVerification
.+1, for now, I'm sending verification email by hitting the restful api. What a mess..
BTW, I'm trying to catch examples of sub-optimal Promise usage in the wild and wanted to point out the one in this thread, CC @Sun3 Promise code should almost never repeatedly nest. These aren't callbacks anymore:
admin.auth().createUser({
email: emailAddress,
emailVerified: false,
password: password,
displayName: '', //name,
disabled: false
}).then(function (user) {
// A error representation of the newly created user is returned
console.log("Created Firebase User successfully with id: ", user.uid);
console.log("user.emailVerified:", user.emailVerified);
// Send Email Verification
return user.sendEmailVerification();
}).then(function (emailSent) {
console.log('emailSent ', emailSent);
}).catch(function (error) {
console.log('emailSent error ', error);
});
// ... Additional code below
This code should hopefully be more readable. It also fixes two bugs:
user.sendEmailVerificaiton
wasn't being returned, so the outer promise was resolving early to undefined
catch
block was on the outer promise, there was no handler for a failure to create the new user (may have been intentional from the error message, but you should always handle rejection.@bojeil-google While that would work to unblock developers who need this urgently, its an incredibly elaborate workaround once you figure in the need for service account certs for minting custom tokens... in my case where i have multiple environments where i would need to manage certs based on environment, its just a ton of mental overhead. It would be nice if cloud functions didn't need service account certs anyway.
Any word if this feature is being worked on?
The feature is on our list and we acknowledge its importance. We just have a lot of feature requests and many are currently critical to developers and not possible client side or admin side. I would prioritize those higher.
If you are having a hard time minting custom tokens, you can just send the ID token to an HTTP endpoint you host in Firebase Functions and use the REST API to send the email verifications: https://firebase.google.com/docs/reference/rest/auth/#section-send-email-verification
@bojeil-google Thanks a ton!
@bojeil-google - sorry for the delayed response. Are you suggesting the firebase client SDK can be used from Node (i.e. within the function)? Just to reiterate, I have no front end and no browser, so all logic must be encapsulated within the Firebase function (which is what I was trying to do). Step 3 is what I'm questioning the viability of. I thought the client SDK relied on browser-specific capabilities, such as XHR, which would make this impossible. I'd love to be wrong about that ;-)
The goal of my project is for users to login to Docker via a terminal/shell, using Firebase auth. The Docker agent handles all of the handshaking, but uses HTTP requests to authenticate users. Basically, Docker attempts to login via basic auth first, so my function extracts the credentials and matches them up with a Firebase user. That was pretty simple.
I wanted my code to assure the user had a verified email address. We know and trust users, but we don't always trust someone to type in the right email... typos are rampant. So, the goal was to setup a function that would send the verification email whenever a new user was created, regardless of how they're created (which is exclusively through the web console at the moment).
I know this isn't a traditional use of Firebase, and our goal is to eventually have a more traditional UI/self-registration portal, which would make all of this moot. However; we don't have enough time for a project of that scale right now. Personally, I'd be even happier if there were an option in the Firebase console to automatically send new users a verification email so we don't have to write this functionality ourselves... but I'm also perfectly content doing it myself if it's possible.
Yes, the client SDK works in Node. We actually use the Client SDK in Node as part of firebase-tools
, so this is pretty unlikely to change any time soon.
I have the latest version of the admin sdk but I don't see this feature implemented. Do we still have to login as the user in order to send the verification? If so, I couldn't find a solution or reason for this issue to be closed. Thanks a lot.
This issue is not closed.
Oh ok, my bad. I saw the reference and mistaken it for an action in this issue. Thank you @hiranya911 So +1 for this feature 👍
Any updates on this issue? It seems like a pretty crucial feature...
I'm still waiting it this feature to be available soon
Agree this will be a great feature to add to the Admin SDK.
I understand an ID token would really not be required to perform these type of operation from the server side and assume the plan is to just use service account credentials, just like with other sever side/admin APIs.
That said, with the current situation, I gave it a shot with a combination of sign up + send email verification REST APIs:
https://firebase.google.com/docs/reference/rest/auth/#section-create-email-password (returns an ID token if successful)
https://firebase.google.com/docs/reference/rest/auth/#section-send-email-verification
And that worked well. Not an ideal flow, and possibly simpler to just use a 3rd party transactional/cloud email provider - but looks promising as an interim solution/workaround.
Did not check options available to customize the email using this approach (if related at all), neither any possible throttling issues involved, given this will be always triggered from the same (server) IP address, though....(not sure if the same rules than using the client SDK would apply for example)
In addition, the ID token will really be discarded in this case, since it's solely used for the purpose of getting the email sent. Expecting to be able to get a new one from the client, once the email is verified.
Is this feature already available ? ; this is really needed.
Formally seconding (thirding? fourthing?) this feature. Also, a bit more clarity in the docs that you cannot issue a verification email from Cloud Functions would be helpful.
Currently the Auth API for the client and Cloud Functions appear very similar (e.g. firebase.auth().currentUser...
vs functions.auth.user()...
) and it took a lot of digging and testing to figure out that I could call sendEmailVerification()
from the former but not the latter. The flow has the appearance of convenience but it really felt like a head-fake when I learned that sending an email verification in a logical create-user flow (i.e. within the onCreate
callback) could not actually be handled nearly as simply as the client-side feature seemed to imply.
Fifthing (?) this as well. Would love to have this ability be a single call vs. needing to leverage the REST API.
Okay got this working and wanted to post here so others have a reference implementation but also to really show the need for having this wrapped up in a simple function. A crazy thing I realized too was the difference between Auth customTokens and IdTokens, and that the Admin Auth SDK is only able to generate the former. This means you not only need to use the REST SDK to send an email, but also need to add in an additional call to exchange your customToken for an idToken. The Admin Auth SDK also has no method for verifying a customToken to generate an idToken (which is what it looks like the REST SDK does).
This uses the Admin SDK + REST SDK (and the request.js npm module) to send a verification email from the server when a new user signs up and all you have at that point is their UID:
auth.createCustomToken(userRecord.uid).then(function(customToken) {
var idTokenRequestOps =
{
url:'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=[APIKEY]',
json: true,
body: { "token" : customToken, "returnSecureToken" : true}
};
request.post(idTokenRequestOps, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('unable to post request to send swap custom token for id token', err);
}
else {
if(body.error) {
console.log("unable to swap custom token for idtoken with error", body.error);
}
else {
var emailVerificationOps =
{
url:'https://www.googleapis.com/identitytoolkit/v3/relyingparty/getOobConfirmationCode?key=[APIKEY]',
json: true,
body: { "requestType" : "VERIFY_EMAIL", "idToken" : body.idToken}
};
request.post(emailVerificationOps, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('unable to post request to send verification email', err);
}
else {
if(body.error) {
console.log("unable to send email verification with error",body.error);
}
else {
console.log("sent verification email! server responded with",body);
}
}
});
}
}
});
});
So I'm going to ask. Has this gotten any better. Just a simple create a user and send the email verification link.
Thank you @kkukshtel Its works like a charm! But in order to work with createCustomToken() function we have to nitialize the admin with a service account like follow. Refer: https://stackoverflow.com/questions/42717540/firebase-cloud-functions-createcustomtoken
var serviceAccount = require('./serviceAccountKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://< Project ID>.firebaseio.com"
});```
Here is my complete code:
```const cloudStorageConfig = require('./cloud-storage-config.json');
const admin = require('firebase-admin');
var serviceAccount = require('./serviceAccountKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://catalog-e8e80.firebaseio.com"
});
const request = require('request');
exports.customerSignUp = functions.https.onRequest((req, res) => {
cors(req, res, () => { });
admin.auth().createUser({
email: req.body.email,
password: req.body.password
}).then(function (userRecord) {
sendVerificationEmail(userRecord).then(()=>{
res.status(200).send({ "success": true, uid: userRecord.uid });
).catch((error)=>{
res.status(200).send({ "success": false, error: error });
})
})
});
function sendVerificationEmail(userRecord) {
return admin.auth().createCustomToken(userRecord.uid).then(function (customToken) {
var header = {
'Content-Type': 'application/json'
}
return request({
url: "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=" + cloudStorageConfig.apiKey,
method: 'POST',
json: { "token": customToken, "returnSecureToken": true },
headers: header
},
function (error, response, body) {
if (error) {
console.log('unable to post request to send swap custom token for id token', error);
return;
}
if (body.error) {
console.log('unable to swap custom token for idtoken with error', body.error);
return;
} else {
return request({
url: "https://www.googleapis.com/identitytoolkit/v3/relyingparty/getOobConfirmationCode?key=" + cloudStorageConfig.apiKey,
method: 'POST',
json: { "requestType": "VERIFY_EMAIL", "idToken": body.idToken },
headers: header
},
function (err, response, body) {
if (err) {
console.error('unable to post request to send verification email', err);
} else {
if (body.error) {
console.log("unable to send email verification with error", body.error);
} else {
console.log("sent verification email! server responded with", body);
}
}
return;
}
);
}
}
);
});
}```
Hi everyone!
How long this feature will be available?
Appreciate the attention.
Hey, any update on this?
I'm having to call a nodejs module with a rest api in order to do it unless this has been now included
Hey @coreybutler, to help unblock you, you can always use the client SDK to send the email verification from a Firebase Function. You'd need to require firebase module. On user creation, you do the following:
- get the
uid
of the user created from the onCreate trigger.- Using admin SDK, mint custom token via
createCustomToken
for that user.- Using client SDK,
signInWithCustomToken
using that custom token.- Send email verification via
currentUser.sendEmailVerification
.
@bojeil-google How would I initialize the firebase app on the cloud functions? firebase.initializeApp({config}) doesnt work, also firebase.initializeApp() doesnt work
Edit: admin.intializeApp() works without passing config, firebase.initializeApp({config}) Config is requires. Now it works Thanks
I'd also like to request this feature at some point as well. While it probably isn't the most important feature, the alternative presented, creating a custom token and then posting to googleapis, isn't as simple as it could be. I am having issues with the post request accepting my custom id token and as far as I can tell I followed all of the documentation/steps. I can think of a client side work around but it would be easier to do this all server side.
Edit: I did eventually get it to work on the server but the point stands just adding a sendEmailVerification function would be the most straightforward method.
const functions = require('firebase-functions');
const fetch = require('node-fetch');
// Send email verification through express server
exports.sendVerificationEmail = functions.auth.user().onCreate((user) => {
// Example of API ENPOINT URL 'https://mybackendapi.com/api/verifyemail/'
return fetch(<API ENDPOINT URL>, {
method: 'POST',
body: JSON.stringify({ user: user} ),
headers: {
"Content-Type": "application/json"
}
}).then(res => console.log(res))
.catch(err => console.log(err));
});
// File name 'middleware.js'
import firebase from 'firebase';
import admin from 'firebase-admin';
// Get Service account file from firebase console
// Store it locally - make sure not to commit it to GIT
const serviceAccount = require('
// Initialize firebase Client firebase.initializeApp(config);
export const verifyEmail = async (req, res, next) => { const sentUser = req.body.user; try { const customToken = await admin.auth().createCustomToken(sentUser.uid); await firebase.auth().signInWithCustomToken(customToken); const mycurrentUser = firebase.auth().currentUser; await mycurrentUser.sendEmailVerification(); res.locals.data = mycurrentUser; next(); } catch (err) { next(err); } };
#### Server code
```javascript
// Filename 'app.js'
import express from 'express';
import bodyParser from 'body-parser';
// If you don't use cors, the api will reject request if u call it from Cloud functions
import cors from 'cors';
import { verifyEmail } from './middleware'
app.use(cors());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(bodyParser.json());
const app = express();
// If you use the above example for endpoint then here will be
// '/api/verifyemail/'
app.post('<PATH TO ENDPOINT>', verifyEmail, (req, res, next) => {
res.json({
status: 'success',
data: res.locals.data
});
next()
})
This endpoint will return back the full user object and will send the verification email to user.
I hope this helps.
Apparently, there are many of us who are asking firebase developers to add this feature to Node.js firebase-admin SDK. Please!
Any update?
The admin SDK recently started supporting generation of email links for email verification, password reset and email link sign-in. This allows you to fully build and customize your own email templates. However, you will need to use your own or a third party SMTP sever to send the email.
@bojeil-google this is great! Is this considered "done" from the FB team? I'd personally love to not have to rely on a third party service for this, it should just be built into Firebase or have some setting that lets you toggle it.
Create user and send verification email. I think that these 2 features are almost inseparable. While you may consider merging under single cloud function, it was disappointed that we can not even use them separately.
The REST API allows sending an email through Firebase via this endpoint: https://firebase.google.com/docs/reference/rest/auth/#section-send-email-verification
It seems pretty easy to use: just give it an email address and it attempts to send verification to the address.
Using the REST API is more of a workaround due to the SDK still lacking this functionality. In my opinion, ideally, the admin SDK should have a function to sendEmailVerification() for the current user. It is much more reliable to trigger this functionality on the OnCreate event of the user rather than relying on the client to handle this.
Been almost 3 years.....
I do not think this will ever be implemented, they added other functionalities such as https://firebase.google.com/docs/auth/admin/email-action-links that pretty much covers 90% of this and the way I see it, that is the best solution going forward.
Yes, you would still need to use your own email service or a third-party one, but nowadays you can get it for free (SendGrid, for example).
Just came across this issue :/. Since this is already working for the client SDK, what is the suggested work-around for now without relying on a 3rd party service?
I'll just go ahead an ask.... is there actually any community interest in a 3rd party service to do this? Since my original posts, I've resolved this a number of different times. It's not rocket science from a code perspective, it's just a PITA to setup every time.
I was thinking along the lines of configuring a simple onCreate
function to send a web request off to a service when a user is created.... service does everything else and could conceivably send a webhook back to systems once the verification is complete.
I don't want to hijack this thread, so ping me separately if anyone is interested in something like this.
I found a work-around that works well enough for my use case, see below. I'm not sure if this is best practice, but I wanted to keep the emails exactly the same between the server and client requests. Would love to hear about any flaws with this implementation 💡
As suggested above, it uses a three step process to do this:
custom token
via the admin sdk's createCustomToken(uid)
idToken
via the APIsend email verification
endpoint on the APIconst functions = require('firebase-functions');
const fetch = require('node-fetch');
const admin = require('firebase-admin');
const apikey = functions.config().project.apikey;
const exchangeCustomTokenEndpoint = `https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${apikey}`;
const sendEmailVerificationEndpoint = `https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=${apikey}`;
module.exports = functions.auth.user().onCreate(async (user) => {
if (!user.emailVerified) {
try {
const customToken = await admin.auth().createCustomToken(user.uid);
const { idToken } = await fetch(exchangeCustomTokenEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: customToken,
returnSecureToken: true,
}),
}).then((res) => res.json());
const response = await fetch(sendEmailVerificationEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
requestType: 'VERIFY_EMAIL',
idToken: idToken,
}),
}).then((res) => res.json());
// eslint-disable-next-line no-console
console.log(`Sent email verification to ${response.email}`);
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
}
}
});
It's 2020.. nothing on this yet?? C'mon firebase team! I lost hours trying this because it was intuitive to make it server side and even on client side is not working.
I'm pretty stumped why the admin would have less functionality than the insecure front end
I find the lack of user verification and email/password reset from the admin sdk to be a flawed and lacking feature
+1 for this. I'm currently using a combination of calling the identity toolkit login with password + send Oob code endpoints to do this, which just feels like a big workaround.
Firebase team, can you please shed light on this issue? The Admin SDK lack of using the sendEmailVerification() link is a serious issue not being address. It should not rely on third party to actually send the email out, it's a standard Firebase auth fuction.
I first reported this issue back Jun 22, 2017.
Thank you.
[Refiling for user @sun3 from https://github.com/firebase/functions-samples/issues/181]
Feature Request:
The
user.sendEmailVerification()
needs to be supported by Firebase Cloud Functions. This is available in client side but not server side. When using Cloud Functions to create new users we also need to automatically send Email Verification before new user can use our apps. This is currently as stopping block for our apps.At this point the
user.sendEmailVerification()
gives error that function is not found.Thank you and I am open to any suggestions.