Email Confirmation Script for User Authentication via Email Address

I’m looking to move across from Firebase to MongoDB (for a number of reasons). But user authentication is a little more “involved”. Based on the Realm UI, I’m required to enter an “email confirmation URL” that should point to a page that contains an email confirmation script.

I’ve tried to look for some tutorials or guides on how to configure this as I’m new to programming. Can anyone point me in the right direction please?

3 Likes

Hi @Anthony_CJ,

The idea is you should set a link pointing to your application url endpoint where you would confirm the received token.

Now the user is sended with an email by Realm system after registration the link he clicks should point to a place where you complete your registration with your sdk language.

Here is the section for user confirmation flow for JS sdk (you should navigate to a similar docs for your sdk):

Please let me know if this helps.

Best
Pavel

Thanks. I understand the process, what I don’t know how to do is generate the email configuration script that I will locate at the email confirmation URL. I am building an iOS app so there’s so web app.

1 Like

Hi @Anthony_CJ

This is more related to language specific redirect, you can also avoid email confirmation or do a function confirmation for your app.

I would recommend looking into our IOS tutorial which shows email signup logic:
https://docs.mongodb.com/realm/tutorial/ios-swift#enable-authentication

Best
Pavel

Hi @Pavel_Duchovny. Thanks but I’ve got that bit sorted. That’s not what I’m asking about. I’m asking about the email confirmation URL and generating an email confirmation script.

1 Like

I have exactly the same question mark. It seems like you have to set up you own website with scripts to handle the confirmation link. Apparently in previous versions (Realm Cloud or Stitch) they provided this service for the clients but not anymore. I’m trying to develop a desktop app with Realm, so I don’t have a webserver, which could do that job. Thus this feature is not really useable for me.
Using custom functions to might be the answer, but because of a lack of examples I don’t see how I still can validate that users provided a valid email (for password resets) .

1 Like

Hi @Anthony_CJ,

I think its definitely possible to create a link which redirect to your ios app instead of a web page:

iphone - ios url redirect from mail to app - Stack Overflow

This is a bit out of scope for realm per say.

The code to confirm is:
https://docs.mongodb.com/realm/ios/manage-email-password-users#confirm-a-new-user-s-email-address

As I said if you don’t want to use an email you can send the user SMS via twilio or email with a code and have the confirmation function input this code from email.

Thanks
Pavel

Hello, I was in the same boat as you and here are the steps I did to add email confirmation to my application. I am going to assume you have some knowledge with the MongoDB Realm website.

Steps

Turn On Email/Password Authentication Provider

Click on the “Email/Password” provider.

Ensure it is ON.

Add Registration Code To Application

Insert this code where you make the user sign up.

Create Confirmation Script

This is the super simple code that confirms your user when clicks on the “confirm email” link that they get in their confirmation email.

<html>
<head>
<script src="https://unpkg.com/realm-web@1.2.0/dist/bundle.iife.js"></script>
<script>
const APP_ID = "< YOUR APP_ID >";
const app = new Realm.App({ id: APP_ID});
//Grab Tokens
const params = new URLSearchParams(window.location.search);
const token = params.get('token');
const tokenId = params.get('tokenId');
//Confirm client
app.emailPasswordAuth
    .confirmUser(token, tokenId)
    .then(() => displayResult('success'))
    .catch(err => displayResult('error', err))
//Display Message depending on result
function displayResult(result, err) {
    const message = document.getElementById("message");
    if (result === "success") {
        message.innerText = "Your E-mail address has been verified.\n\n You may close this page. Thank you.";
    }
   else if (result === "error") {
       message.innerText = "Unable to register this user. Please try again to register." + err;
   }
}
</script>

<title>E-mail Confirmation</title>
<style>
    h1 {text-align: center;}
    h3 {text-align: center;}
    h5 {text-align: center; background-color: whitesmoke;}
    p {text-align: center;}
    div {text-align: center;}
</style>
</head>
<body>
    <h1>My Apps Name</h1>
    <h3>Thanks for choosing our app!</h1>
    <h5 id = "message"></h5>
</body>
</html>

This line here “” allows us to use Realm as a global variable, and the rest is pretty self explanitory.
** Ensure to put your own APP_ID **

Hosting the script

Now you have to host the script, this is super simple. Go to your Realm Apps home page and on the left hand side you should see a tab called “Hosting”, click on it.

Then put the code from the previous step into a file and upload that file by clicking “Upload Files”, and selecting that file.

Enter Script URL into Email/Password Authentication Provider

This is the last step to this process, and the easiest, simple copy the link of the script,


and add it to the email.

Done!

Thats all you need to do to have email confirmation with your iOS application using MongoDB Realm and Swift. The process for password reseting is very identical as well.

12 Likes

I would like to add here that copying the link and pasting it into the Email Confirmaion URL did not work for me because there was extra information included in the copied link. What did work was just adding the file name as a path to the web address like below:

https://myappname.mongodbstitch.com/emailconfirmation.html

I also wanted to note here that if you’re using a React application you don’t need to use vanilla javascript to create an email confirmation page. For example if you had an emailconfirmation route that made use of an emailconfirmation component you could simply paste the address of that route in your Email Confirmation URL like:

https://myappname.mongodbstitch.com/emailconfirmation

Lastly I would like to mention that if the route uses capital letters it won’t load the page in the browser. I also used the single page application option in the settings to run my app.

4 Likes

@Sebastian_Gadzinski @thecyrusj13_N_A @Anthony_CJ

Can anyone please help me figure out how I can adapt Sebastian_Gadzinski’s code for password reset?

Would be very happy. Too bad that the documentation is so very lacking.

1 Like

@Nilom_N_A

Hi there, I got the solution:

step 1: put a password-type text field on the website
step 2: add a confirm button for the user to click after he inputted the new password
step 3: when user clicks the confirm button call

app.emailPasswordAuth
    .resetPassword(token, tokenId, passwordTextField.value)
    .then(() => displayResult('success'))
    .catch(err => displayResult('error', err))

thats it. Show result like “Change was successful. You may close this page now.”

1 Like

Thank you for the reply.

But I mean if the user forgot the password. Then a password confirmation mail has to be sent to his email adress. And the link inside the mail will lead to the site with the change password field.

That will most likely need a script like the registration mail example above.

@Nilom_N_A Yeah of cource, you use exactly the same script (HTML file) as posted above and then apply the 3 changes to it as I wrote. And remove the email confirmation content:

app.emailPasswordAuth
    .confirmUser(token, tokenId)
    .then(() => displayResult('success'))
    .catch(err => displayResult('error', err))

from the script, obviously

1 Like

thanks this really helped!

I only had to change the link, like someone else said:

"What did work was just adding the file name as a path to the web address like below:

https://myappname.mongodbstitch.com/emailconfirmation.html"

you saved me a lot of time :slight_smile:

Greetings Harriët

1 Like

I updated the script above to work with the newest Realm Web SDK.

<html>
<head>
<script src="https://unpkg.com/realm-web/dist/bundle.iife.js"></script>
<script>
const APP_ID = "< YOUR APP_ID >";
const app = new Realm.App({ id: APP_ID});
//Grab Tokens
const params = new URLSearchParams(window.location.search);
const token = params.get('token');
const tokenId = params.get('tokenId');
//Confirm client
if (token && tokenId) {
    app.emailPasswordAuth
        .confirmUser({token, tokenId})
        .then(() => displayResult('success'))
        .catch(err => displayResult('error', err))
} else {
    displayResult('error', 'Missing token or tokenId in URL parameters')
}
//Display Message depending on result
function displayResult(result, err) {
    const message = document.getElementById("message");
    if (result === "success") {
        message.innerText = "Your E-mail address has been verified.\n\n You may close this page. Thank you.";
    }
   else if (result === "error") {
       message.innerText = "Unable to register this user. Please try again to register. " + err;
   }
}
</script>

<title>E-mail Confirmation</title>
<style>
    h1 {text-align: center;}
    h3 {text-align: center;}
    h5 {text-align: center; background-color: whitesmoke;}
    p {text-align: center;}
    div {text-align: center;}
</style>
</head>
<body>
    <h1>My Apps Name</h1>
    <h3>Thanks for choosing our app!</h1>
    <h5 id = "message"></h5>
</body>
</html>

1 Like

Thanks for the tutorial! :slight_smile:
Do I have to pay for Dedicated Clusters for hosting to be enabled and host the confirmation page?

Hey Ciprian, no you do not have to pay for dedicated clusters for hosting to be enabled, I was using a shared cluster. You do have to have a Realm application as the hosting options are on the AppService tab.

There you can create a Realm Application and connect it to your cluster. Once you complete that process you should see the hosting option on the sidebar tab:

its says that I have to upgrade it

1 Like

When I use this with the most up to date realm web SDK version, I get an invalid JSON error. Does this still work for you?

1 Like