-
Notifications
You must be signed in to change notification settings - Fork 371
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature Request: Cloud Function should support user.sendEmailVerification() like client sdk #46
Comments
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 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.
Please let me know if this explains the issue. |
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.
|
+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:
|
@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: |
@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 |
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? |
This issue is not closed. |
Oh ok, my bad. I saw the reference and mistaken it for an action in this issue. |
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 https://firebase.google.com/docs/reference/rest/auth/#section-send-email-verification And that worked well. 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. |
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 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:
const 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);
}
}
}); References |
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. |
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. |
Not having this feature after so many years makes one wonder what is happening, the developer experience is really bad, of course this should have been implemented at the same time as it was possible to create users with the Admin SDK. |
@stehag I'm not sure we should say that the developer experience is "really bad" just because of a few missing features here and there. But yeah, this one is a real must for a lot of things. |
I've re-escalated this internally. Has anyone who has been waiting all this time tried just using the client SDK from the server side? I would expect that you could create a custom token in the admin SDK, pass it to the client SDK, and then call the appropriate method. I get that this is a kludge, but it's better than waiting on a complete backend API rewrite to support this edge case (sadly that's what would be required). |
I can confirm that works as it is what I did for the project I was on. It was very "hacky" and did not look good and only worked for custom auth flows not SSO. This was for a project where admins had to create users as self signup was not allowed. Once they had their custom signon, at that point they could switch to SSO. |
A few years ago I did exactly that, I guess that still works but I can confirm it used to work around 3 years ago. (Using the client SDK) |
Isn't the client sdk rate limited for client use ? |
Rate limiting shouldn't be a problem AFAICT. |
So you are saying that a public facing lib is not rate limited by IP ? |
I see a ratelimit error in their service definition, but don't know (and probably shouldn't say) what the limit is. Generally even IP ratelimts are set to "reasonable" levels because ISPs in some countries NAT massive numbers of clients to the same IPv4. Either way, the rate limit is guaranteed to be greater than 0, so this is better than waiting for an architecture rewrite. |
@inlined , in that case, this should be a better solution #46 (comment), since it shouldn't be rate limited the same way a public facing lib is. |
So, I have #46 (comment) working in local emulators when I manually specify the REST API key ( Is there a way in a production environment to get the REST API key? or will I need to manually add that to the functions config via |
The Firebase Config does not include an API key since the Firebase Config is for backend development and the API key is ostensibly to label a client. You can inject it with |
+1, we want to see this! |
I found a method on the Firebase Auth documentation where you can generate a You can also pass a redirect URL (and other info) where you can handle any callbacks once the use clicks on the link. You just need to send the email yourself. This is what I have done: let displayName = 'John Doe'
let email = 'to@mail.com'
//Generate the email verification link
let emailVerificationLink = await admin.auth().generateEmailVerificationLink(email, { url: `SOME_REDIRECT_URL?with=params` })
let mail = JSON.parse(process.env.FIREBASE_CONFIG).mail
//construct the email
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: mail.email,
pass: mail.password,
},
})
const mailOptions = {
from: `"${APP_NAME}" <${mail.email}>`,
to: email,
subject: `Email verification for ${APP_NAME}`,
text: `Hello ${displayName})}
Please follow this link to verify your email address for the ${APP_NAME}
${emailVerificationLink}
Thanks
Your ${APP_NAME} team
`,
html: `
<p>Hello ${displayName}</p>
<p>Please follow this link to verify your email address for the ${APP_NAME}</p>
<p><a href='${emailVerificationLink}'>Verify Email</a></p>
<p>Thanks</p>
<p>Your ${APP_NAME} team</p>
`
};
try {
//send the email
await mailTransport.sendMail(mailOptions);
} catch(error) {
console.error('send email error', error)
} I am using the NodeMailer package for sending the email |
7 years later and no feature still? |
Possible solution is to install the firebase client and initiate the auth with a custom token from the admin sdk and then invoke an email request on that user instance |
I really do need this, guess I'll just have to implement the workaround. Any updates on when the solution should come out? |
something like this can be done: const admin = require('firebase-admin');
const axios = require('axios');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
});
const generateCustomToken = async (uid) => {
try {
const customToken = await admin.auth().createCustomToken(uid);
console.log('Custom Token:', customToken);
return customToken;
} catch (error) {
console.error('Error creating custom token:', error);
}
};
const authenticateWithCustomToken = async (customToken) => {
const url = `https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${process.env.FIREBASE_API_KEY}`;
try {
const response = await axios.post(url, {
token: customToken,
returnSecureToken: true,
});
console.log('ID Token:', response.data.idToken);
return response.data.idToken;
} catch (error) {
console.error('Error authenticating with custom token:', error);
}
};
const sendVerificationEmail = async (idToken) => {
const url = `https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=${process.env.FIREBASE_API_KEY}`;
try {
const response = await axios.post(url, {
requestType: 'VERIFY_EMAIL',
idToken: idToken,
});
console.log('Verification email sent:', response.data);
} catch (error) {
console.error('Error sending verification email:', error);
}
};
// Replace with your user's UID
const uid = 'your-user-uid';
generateCustomToken(uid)
.then(customToken => authenticateWithCustomToken(customToken))
.then(idToken => sendVerificationEmail(idToken)); |
[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.
The text was updated successfully, but these errors were encountered: