MongoDB Stitch Authentication Triggers

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):

MongoDB Stitch Authentication Trigger

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

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.





Leave a Reply