Search code examples
mongodbwebhookses6-modulesmongodb-stitch

Authentication Service Webhook (endpoint) in MongoDB Stitch


Is there a way to create a service webhook to register new user with Email and Password?

I can see the way via SDK but I am trying to do the same via service webhook function?

for e.g.

exports = function(payload) {

 const { Stitch, AnonymousCredential } = require('mongodb-stitch-server-sdk');

  var queryArg = payload.query || '';
  var body = {};

  if (payload.body) {
  body = EJSON.parse(payload.body.text());
  }

  return body.email;
};

I am not able to access mongodb-stitch-server-sdk here. Am I going in the right direction?


Solution

  • So you won't be able to use the SDK inside of a webhook. What you could do is add the user by hitting the Stitch Admin API.

    1. Make an API key in Atlas. Go to the user dropdown in the top right corner > Account > Public API Access. Click on "Generate", and save the API key that gets created.

    2. Make an HTTP service in Stitch.

    3. In your webhook, use the Admin API to authenticate and create a new user. The code will look something like:

      exports = function(payload) {
          const http = context.services.get("http");
          return http.post({
              url: "https://stitch.mongodb.com/api/admin/v3.0/auth/providers/mongodb-cloud/login",
              body: JSON.stringify({ 
                  username: "<atlas-username>",
                  apiKey: "<atlas-apiKey>"
              })
          }).then(response => EJSON.parse(response.body.text()).access_token).then(accessToken => {
              return http.post({
                  url: "https://stitch.mongodb.com/api/admin/v3.0/groups/<groupId>/apps/<appId>/users",
                  headers: {
                      Authorization: ["Bearer " + accessToken]
                  },
                  body: JSON.stringify({ 
                      email: "<email-from-payload>",
                      password: "<password-from-payload>"
                  })
              });
          });
      };
      

    After Comment:

    const http = context.services.get("http"); needs to be the configured ServiceName instead of http as const http = context.services.get("<SERVICE_NAME>");