Custom Function authentication and POST method

Hi @Andrea,

Ok so the idea is once you get the authentication object from the query you can use it in a webhook payload to authticate the webhook via script function method. For example my webhook of storing post comments:


Script

exports = function(payload) {
  const authInput = JSON.parse(payload.body.text());
  
  if (authInput.user_id)
  {
    return authInput.user_id;
  }
};

The trick is only the required user will be returned from payload so anyone who calls the webhook can execute it via a specific user only if it knows it Realm id (consider the user id to operate as sort of apiKey here)

** Webhook body and parsing **

// This function is the webhook's request handler.
exports = function(payload, response) {
    // Data can be extracted from the request as follows:

    // Query params, e.g. '?arg1=hello&arg2=world' => {arg1: "hello", arg2: "world"}
    const {arg1, arg2} = payload.query;

    // Headers, e.g. {"Content-Type": ["application/json"]}
    const contentTypes = payload.headers["Content-Type"];

    // Raw request body (if the client sent one).
    // This is a binary object that can be accessed as a string using .text()
    const body = JSON.parse(payload.body.text());


    // Querying a mongodb service:
     const comments = context.services.get("mongodb-atlas").db("feed").collection("comments");



    return doc.updateOne({comment_id : body.comment_id, post_id :body.post_id, user_id : body.user_id },body,{ "upsert" : true});
    
};

Now the field provided in my webhook call will save it with user under the user_id field:

curl \
-H "Content-Type: application/json" \
-d '{"user_id":"5fa7105a871d206bd6739a4", "comment_id" : 1, "post_id" : 1, comment : "great post!" }' \
https://webhooks.mongodb-realm.com/api/client/v2.0/app/app-abcd/service/myTest/incoming_webhook/storeComment

My rules for comments are write only permitted to user owned objects and read is for everyone. Therefore if webhook tries to access a comment that is not written by the user it will not allow it to edit that comment.

As you can see Realm will use the user_id in my comment collection to filter and get the correct permissions. And my webhook require this field to authenticate. This field must be the same value as my custom function. Hope now it all make sense.

Please let me know if you have any additional questions.

Best regards,
Pavel

2 Likes