I have a Flutter mobile application and I am using Firebase authentication. I have decided to use email template for verifying user email. In the backend, I call generateEmailVerificationLink(email ,actionCode) to create an email verification link, then I pass the link to a good looking email template and send it to the user.
I would like to do the same thing for updating user email. But I am not sure which function to call in the backend to create the proper link that I need to pass to the email temple. The mode in the action code should be "verifyAndChangeEmail"
Does any one know?
I found this link https://firebase.google.com/docs/auth/admin/email-action-links
but it does not say how to generate a link for updating user email. Does that mean that I can't have a custom email for updating user email??
Please help.
You can use the same generateEmailVerificationLink() method, and, in the page opened via the link, you need to trigger, in the back-end, the updateUser() method of the Admin SDK.
More concretely:
In a Cloud Function (or a server you own), generate an email verification link for the new email (as explained in the doc you mention in your question) and build and send an email containing this link (for example by calling a microservice like Sendgrid).
The user receives the email in his mailbox. When he clicks on the link, the user is redirected to a web page you host somewhere (for example with Firebase hosting): the email is then verified, with applyActionCode(), as shown in the code found in this page in the Firebase doc (see "4. Handle email address verification by calling applyActionCode.").
Then, in the .then((resp) => {...}) block of this page, implement a call to a callable Cloud Function in which you use the updateUser() method to update the user's email. In the callable cloud function you must check that the uid (User ID) that you pass to the updateUser() method is the uid of the caller (with const uid = context.auth.uid; see the doc).
Related
I would like to customize the email template (using the Trigger Email extension templates) to send verification links to users.
I understand it is not possible to change the template from the Firebase console as it prevents spam.
I am aware of the ability to customize action email handlers (The page that the user lands on when the link in verification email is clicked), as well as the ability to update the auth user's emailVerified property manually.
Is there also a way to generate the verification link that firebase would have used? One with the following properties:
mode
oobCode
apiKey
continueUrl
lang
My ideal solution is to send a custom template to the user upon registration with the generated verification link. Direct users to a custom handler page, and use the applyActionCode() function as shown in The Docs to verify the email (I hope this implicitly updates the emailVerified property on the Auth.User record.)
I have achieved this by creating the user and generating the link on the backend with the admin SDK.
So your frontend would call a callable function or bespoke API endpoint for instance for the registration instead of using the SDK directly.
The callable would go about this:
Creating the user in Auth: auth.createUser()
Creating the user in your DB (Firestore, Mongo etc.)
Assigning custom claims if required: auth.setCustomUserClaims
Building the link for signin: auth.generateSignInWithEmailLink()
Sending the email to an email transactional API
You will need an ESP e.g Sendgrid, MailChimp, MailGun etc. for the last step. There you will have all the freedom to build your own templates.
Please note that the generateSignInWithEmailLink will take care of verifying an email address and signing-in. It could therefore be used for login and registration.
Cheers
I have implemented email verification in my app but i've noticed to email providers have bots that open the link before the user gets to see (thus verifying the email).
is there a way to prevent such behavior? or email verification by code or have action on the screen the user would need to click to verify?
Rather than providing a direct link to Firebase (the default), you can customize your email verification template to direct the user to another location, such as your application, where they must press a button to complete the verification process. Then you can use the Auth.applyActionCode() method with the oobCode that was supplied in the query parameters.
You'll have to process the verifications yourself if you wish to customize it. You can try it by generating email verification link using Admin SDK in a Cloud Function/Server
// Admin SDK API to generate the email verification link.
const useremail = 'user#example.com';
admin
.auth()
.generateEmailVerificationLink(useremail, actionCodeSettings)
.then((link) => {
// Construct email verification template, embed the link and send
// using custom SMTP server.
return sendCustomVerificationEmail(useremail, displayName, link);
})
.catch((error) => {
// Some error occurred.
});
Now that you've sent the email, you'll have to self-host a page to that opens after opening that link.
You can find detailed explanation in the documentation
That being said, you can implement reCaptcha or any verification service you want to use to make sure the user is not a bot and verify it in your custom handler.
I'm using firebase auth in my app and i'm setting up password-less email sign up.
I have managed to set the email from my own domain but how do i change the text sent in the email for magic link?
I can see the configuration for the other template emails but not this one.
The email in question is this one:
Hello,
We received a request to sign in to teamname using this email address. If you want to sign in with your youremail account, click this link: link
If you did not request this link, you can safely ignore this email.
Thanks,
There is no way to edit any of the email templates that Firebase Authentication uses. The reason for this is that this allows bad actors to use Firebase to spam people, which would put the service at risk.
To control what message gets sent, you'll have to send it yourself and handle the verification flow with a custom email action handler. See How to modify Email Confirmation message - Firebase.
You could also take full control of the verification flow, and then use the Admin SDK to set the emailVerified flag of the user's profile.
Following on from Frank's answer, you will have to create your own email action link using the Firebase Admin SDK and then put that link in your custom email which you will then send using whatever service (Sendgrid, Mailgun, etc.).
See how to create the action link here: Generating Email Action Links
the only way to customize your email body is to install firebase extension called Trigger Email but it'll put you on the Blaze plan because it makes requests to third-party APIs, and as they specified on the extension's page you'll only be charged for usage that exceeds Firebase's free tier.
There are two ways to customize the email body when using the Firebase authentication service. However, the drawback is that you will have to create a backend to send the email yourself rather than just using a function from the SDK that handles everything automatically.
Generate email action links:
This is the most efficient method, it requires that you use the Firebase Admin SDK to generate a link that will be embedded in emails sent to your users.
Here is an example code that shows how to create an API to send customized verification emails using Express as the backend:
// Creating a POST route that sends customized verification emails
app.post('/send-custom-verification-email', async (req, res) => {
const {userEmail, redirectUrl} = req.body
const actionCodeSettings = {
url: redirectUrl
}
try{
// generate action like with the Firebase Admin SDK
const actionLink = await getAuth()
.generateEmailVerificationLink(userEmail, actionCodeSettings)
// embedding action link to customized verification email template
const template = await ejs.renderFile('views/verify-email.ejs', {
actionLink
})
// send verification email using SendGrid, Nodemailer, etc.
await sendVerificationEmail(userEmail, template, actionLink)
res.status(200).json({message:'Email successfully sent'})
}catch(error){
// handle errors
}
})
You can read more about it in the article I wrote here
Take full control over the workflow:
With this, the Firebase Admin SDK won't be used to generate an action link, but rather, you will generate the link yourself and create an API that uses the Admin SDK to handle the action to be taken whenever the link is clicked.
To do this you will have to create two API routes. One is a route that sends the emails and the other is a route that uses the Firebase Admin SDK to handle the action to be taken when the link attached to the email is clicked.
When the user wants to update the email, I'm using verifyBeforeUpdateEmail to verify before updating it.
await FirebaseAuth.instance.currentUser.verifyBeforeUpdateEmail(
email,
ActionCodeSettings(
androidInstallApp: true,
androidPackageName: 'com.example',
iOSBundleId: 'com.example',
handleCodeInApp: true,
url: 'https://example.page.link/emailVerify',
));
Can I let the user know if the email has been verified and updated? I've tried dynamic_links but it does not pick up the email verification.
The verifyBeforeUpdateEmail() method sends a verification email to a new email address. So the user needs to execute an action in order to verify the email (click on the link provided in the email). So normally the user will know he/she has verified the new email.
If you want to add an extra mechanism to "let the user know if the email has been verified and updated" you could adopt one of the following approaches:
#1 Implement a custom email action handler
As explained in the doc, "by default, user management emails link to the default action handler, which is a web page hosted at a URL in your project's Firebase Hosting domain. You can instead create and host a custom email action handler to do custom processing and to integrate the email action handler with your website".
This way, you could implement any business logic in parallel of the email verification, like sending a confirmation email or updating a flag, etc..
#2 Use a Cloud Function
There is no Authentication Cloud Functions trigger in response to the verification of an email, unfortunately. We can only trigger a Cloud Function upon the creation and deletion of Firebase user accounts. But you could implement a scheduled Cloud Function which checks if the email has been verified.
I read some other posts about this topic but couldn't finally figure out how to accomplish this.
I want to send the email-verification email normally send from firebase itself from my own email-provider (like mailjet e. g.) The reason is that I want to customize the email text etc.
I also read about creating a custom email handler which I would do too. But this just handles the action that happens when the user clicks on the link in the email.
At the moment I call this from my flutter app after the users sign up:
user.sendEmailVerification();
this makes firebase send the standard verification email to the user. Instead of doing that I'd need to send the email myself. But like seen here I need to have this oobCode generated. to generate a correct link to handle. I just can't find an example on how to do that. What would be the right approach to send the email myself? Maybe I just did not find the right resource. Thanks a lot.
You need to generate and send the email via a backend, by using the Admin SDK. The easiest is to use a Cloud Function, from which you use the Mailjet NodeJS API wrapper.
So, in the Cloud Function, you need to:
Call the generateEmailVerificationLink() method of the Admin SDK, which returns a link
Generate an email containing this link
Send the email to the user (see the Mailjet NodeJS API wrapper documentation)
The first steps are detailed here in the doc.
In order to customize the URL of the verification link (e.g. you want to redirect to https://www.myrapp.com/emailVerifyScreen) you need to change the base URL as shown in the below image ("Customize action URL"). Also explained here in the doc.
Then, when the user clicks on the link in the email he/she has received, you need to do what is explained in the doc you referred to in your question: Create custom email action handlers. See the point #4 "Handle email address verification by calling applyActionCode".
Concretely, in the page of your app https://www.myrapp.com/emailVerifyScreen, you get the query string values from the URL (e.g. var actionCode = getParameterByName('oobCode');) and you use these values to call the applyActionCode(actionCode) method. When the promise returned by this method is fullfilled, you know that the email has been verified.
var actionCode = getParameterByName('oobCode');
auth.applyActionCode(actionCode).then((resp) => {
// Email address has been verified.
// TODO: Display a confirmation message to the user.
// You could also provide the user with a link back to the app.
// TODO: If a continue URL is available, display a button which on
// click redirects the user back to the app via continueUrl with
// additional state determined from that URL's parameters.
}).catch((error) => {
// Code is invalid or expired. Ask the user to verify their email address
// again.
});
One last point to note: you cannot directly get the oobCode alone. The generateEmailVerificationLink() method generates the full URL.
The answer mentioned above is absolutely correct , I am just adding to that how you can create action url in two ways for testing and then deployment way.
1> for custom email action handler you would have to create your own handlers (using HTML and js , react app , flutter anything you want) after doing that you can either test your handler by routing traffic to it (localhost) using ngrok(that will provide you with https url to route traffic on localhost, preferred method for testing) , or you can deploy it and directly use that url . now with that url go to firebase(your project) -> authentication -> templates -> use whatever handler you want( example reset password or email verification) -> edit and add custom action url to route traffic to your handler( hosted(deployed) or local(ngrok routing) .