Search code examples
javascriptnode.jsbotsfacebook-messenger

How to authorise user for a web page in FB messenger, without logging in?


I am building a chat bot in FB messenger that saves user profile data, food and calorie consumption. I am using Node/Express/MongoDB for the backend and want the user to be able to open a personal dashboard page inside the chat with a link. So that URL would be something like www.myapp.com/:id where :id is a personal key.

The problem I have is how can only the user belonging to this page and data open this without having to login? Normally you would go to a website, login and be able to see the page, but this not a step I want in a chat bot. I want the user just to open the page in the chat, whether that is results in opening a browser tab or a native webview. Any advice on how I can achieve this?


Solution

  • To verify if the user on the page is the facebook user you intend the page to be for, add FB Messenger Extensions to the page.

    When clicking a webview in your bot, Messenger extensions will be able to tell who they are logged in as, and allow you to do whatever you want with that info. In your case, checking if the userid matches the one passed by your bot in the url. There are many ways to check this, like splitting query strings, but I stuck with the example route in your question.

    Use the following on your dashboard page. The below will check with FB who the logged in user is, and if it doesn't match the ID of the link they followed, deny them access with a redirect.

    <script>
        MessengerExtensions.getContext(<YOUR-APP-ID>, 
        function success(thread_context){
        // User ID was successfully obtained. 
            var psid = thread_context.psid;
            // Grab the user id from your url (assumes your url is /<USER_ID>)
            var loc = window.location.pathname.replace(/^\/|\/$/g, '');
            if (psid !=== loc) {
              window.location.replace("http://YOUR_DOMAIN.com/error")
            } 
        }, function error(err, errorMessage) {      
        // Error handling code
        });    
    </script>
    

    Docs on getting user id with Messenger Extensions