Reacting to Auth Events using Stitch Triggers
MongoDB Stitch
makes it easy to add authentication to your application.
Several authentication providers
are available to be configured using the Stitch Admin Console. Recently, authorization triggers were added to Stitch. Functions can now be executed based on authorization events such as user creation, deletion, and login.
During my
Stitchcraft live coding sessions
, I’ve been creating an Instagram-like application that uses
Google Authentication
. The Google authentication provider can be configured to return metadata with the authenticated user. I set up my provider to retrieve the user’s email, name, and profile picture. This works well as long as only the authenticated users need to see it. If you want other users to be able to access this data, you’re going to have to write it to a collection. Before authorization triggers, this could have been an arduous task.
Now it’s as simple as executing a function to perform an insert on the CREATE operation. Because I wanted to also ensure that the data in this collection stayed up-to-date,
I created authorization
triggers for CREATE and LOGIN and pointed them to a single upsert function as seen below.
exports = function(authEvent) {
const mongodb = context.services.get("mongodb-atlas");
const users = mongodb.db('data').collection('users');
const { user, time } = authEvent;
const newUser = {
user_id: user.id,
last_login: time,
full_name: user.data.name,
first_name: user.data.first_name,
last_name: user.data.last_name,
email: user.data.email,
picture: user.data.picture
};
return users.updateOne({user_id: user.id}, newUser, {upsert: true});
};
During the last Stitchcraft session, I set up this authorization trigger and a database trigger that watched for changes to the
full_name
field.
Check out the recording
with the GitHub repo linked in the description.
Follow me on Twitch
and be notified of future Stitchcraft live coding sessions.
-Aydrian Howard
Developer Advocate
NYC
@aydrianh
Creating your first Stitch app? Start with one of the
Stitch tutorials
.
Want to learn more about MongoDB Stitch? Read the
white paper
.
September 25, 2018