Learn, develop, and innovate from anywhere. Join us for our MongoDB .Live series.
HomeLearnHow-to

MongoDB Stitch Authentication Triggers

Updated: Apr 17, 2019 |

Published: Sep 25, 2018

  • Realm
  • Atlas
  • JavaScript
  • ...

By Andrew Morgan

Share

Please note: This article discusses Stitch. Stitch is now MongoDB Realm. All the same features and functionality, now with a new name. Learn more here. We will be updating this article in due course.

MongoDB Stitch makes it a breeze to use third-party services such as Google or Facebook to authenticate your app's users. This is great for your users as it means they don't need to go through the tedious process of having to provide all of their details to yet another application/service - it also means one less password to remember.

While delegating the authentication process makes your app secure and straightforward to use, you may still want to customize the process for your users. For example, if someone is registering for the first time, then you probably want to send them a welcome email. When a user deregisters, there may be regulations (such as GDPR) that mandate you delete all of their data.

This is where Stitch Authentication Triggers come to the fore. The model is very simple; you register a Stitch Function with any authentication event (register (create), login, deregister (delete)), then add JavaScript code to that function to perform the required actions.

Simply create the trigger through the Stitch UI (in this case, to send the user an email every time they log in):

Triggering a MongoDB Stitch function when user logs in

and implement the function (emailLoginNotification) that receives the authentication event and sends the email using the AWS SES service:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
exports = function(event){ var aws = context.services.get('AWS'); var input = { Destination: { ToAddresses: [event.user.data.email] }, Message: { Body: { Html: { Charset:"UTF-8", Data: "This is a message to confirm that " + event.user.data.name + " (" + event.user.data.email + ") has just logged into TrackMe" } }, Subject: { Charset:"UTF-8", Data: "TrackMe Login" } }, Source: context.values.get('fromEmail') }; try { aws.ses().SendEmail(input).then(function (result){ console.log(JSON.stringify(result)); }); } catch(error) { console.log(JSON.stringify(error)); } };

Creating your first Stitch app? Start with one of the Stitch tutorials.

Want to learn more about MongoDB Stitch? Read the white paper.

Get started with MongoDB Atlas today!

MongoDB Icon
  • Developer Hub
  • Documentation
  • University
  • Community Forums

© MongoDB, Inc.