Ad-hoc dashboard Answered

Hey everyone! πŸ™‚

I'm building an ad-hoc dashboard where users will display only data relative to their own member_id.

For this implementation I do use a front-end code in JS that calls a PHP script to retrieve data. Now, for security reason I would like the PHP to retrieve the memberstack member_id before responding with the data. Do you have any recommendation on the best way to acheive that?

I thought that I could pass the member_id with the JS function that calls the PHP script, but isn't there a risk that anyone could alter their own member_id and retrieve data of other members? I would like to avoid that.

Thank you in advance for any tip or info! πŸ™‚

I think I got how to do it by asking ChatGPT, but in order to test if that's safe. Is there a way I, as a user, can print the member_id in the console? πŸ™‚

Comments

18 comments

  • Comment author
    Chukwudi Onyekwere

    Hi Luc,

    The script below prints member_id of a logged-in user in the console:

    <script> window.$memberstackDom.getCurrentMember().then((member) => { if (member.data) { console.log(member.data['id']); } }) </script>

    I took out a line of code that wasn't necessary from the code snippet, kindly use the updated code. Β Luca De Angelis

    0
  • Comment author
    Raquel Lopez

    To make sure your server only responds to the user that's actually logged in, I'd recommend you to use JWT tokens.

    You can obtain the token by using window.$memberstackDom.getMemberToken() , then you send it as a authentication header in your request to the backend. Your PHP can verify and decode the token to obtain the memberId the user send by using this REST service

    You can learn more about tokens in this simple article
    https://jujuontheweb.medium.com/simple-introduction-to-jwt-tokens-3f8d1a7ba880

    0
  • Comment author
    Luca De Angelis

    Thank you Raquel Lopez! Chukwudi Onyekwere πŸ™‚ Very helpful!

    From the docs I don't fully understand where i should pass the token string in the PHP request. Maybe I miss it πŸ™‚

    0
  • Comment author
    Raquel Lopez

    Because is a GET, try sending it as a queryParam in the url

    var axios = require('axios');

    const API_KEY = process.env.MEMBERSTACK_SECRET_KEY
    const BASE_URL = 'https://admin.memberstack.com/members'
    const headers = { "X-API-KEY": API_KEY }
    const params = {token: 'ey...'}

    await axios.get(${BASE_URL}/verify-token, { headers, params })
    0
  • Comment author
    Luca De Angelis

    Thank you! Raquel Lopez I tried to use the window.$memberstackDom.getMemberToken() in the code and in the console and it gives me the error window.$memberstackDom.getMemberToken is not a function. Could you share please how can I retrieve the token for a member?

    0
  • Comment author
    Raquel Lopez

    Ah my bad, here's the correct fn $memberstackDom.getMemberCookie()

    0
  • Comment author
    Luca De Angelis

    That works. Thank you! πŸ™‚ For the REST API I just use Member stack API credentials from the devtools sections right?

    Oh, I am afraid I misunderstood. I thought the API call would be launched from the PHP script, instead what you shared is for the front end...

    0
  • Comment author
    Raquel Lopez

    The frontend sends the token to the backend. The backend decodes the token, process the data and returns the response to the frontend with the correct information.

    So the browser would use this $memberstackDom.getMemberCookie()
    And the backend would process the token internally with the verify token service

    When Memberstack generates the token after login, the token gets stored in a cookie in the browser. So you need to send the request FROM the browser

    0
  • Comment author
    Luca De Angelis

    Thank you Raquel Lopez. I m trying to run the code in js but it gives a few errors:

    • first with regards to require(axios) it gives Uncaught ReferenceError: require is not defined
    • i tried to import axios from the cdn usingΒ <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>Β but it still gives error. When removing the statement then it gives an error with regards to API_KEY = process.env.MEMBERSTACK_SECRET_KEY; =?Uncaught ReferenceError: process is not defined

    Any idea by chance on this? πŸ™‚ Thank you so much for your support! I feel I am soooo close!

    0
  • Comment author
    Raquel Lopez

    Well, basically the errors are clear. You need to look where the require and process are being used. process and require are methods that you use in a NodeJS environment.

    I'm not sure if axios can be run in php, I gave you that example so you could translate it to your http client of your php server

    You should be doing the request as php indicates like https://reintech.io/blog/php-curl-making-http-requests-in-php

    0
  • Comment author
    Luca De Angelis

    Ahhh ok. Then the code was just an example. Actually my API request needs to be sent by my server inPHP. All clear! πŸ™‚

    0
  • Comment author
    Raquel Lopez

    And you need to use your secret API key found in the Memberstack dashboard to be able to use the admin API.

    0
  • Comment author
    Luca De Angelis

    Alright, I managed to send a POST API call with my admin private key.
    I use the following endpoint = "https://admin.memberstack.com/members/verify-token?token=member_cookie" where the member_cookie is the cookie passed from the front end. But I get an object with {"data": null} .

    Is it possible that I need to pass the token in another way other than in the url or that needs to be called differently?

    Even if I pass it has header it won't work. It seems that the problem is the token, the API doesn't find any data for the provided token. I checked and the token is exactly the result of window.$memberstackDom.getMemberCookie();

    I just checked here, but it's not very clear to me how should I pass the token in the call. But is it possible also that the cookie that I am passing is actually not the same thing as the token that is needed here?

    0
  • Comment author
    Raquel Lopez

    You need to do a GET, not a POST. The token is stored in a Cookie, (localstorage or cookie). The method that I gave you would get it to you no matter where is stored in your browser. JWT tokens start with ey as your cookie should.

    Remember that tokens expire, use a fresh token that's currently logged in in your MS app. If you log out you'll need to login again to insert a new token.

    The only variables that you need to use to verify the token are the TOKEN, sending it as a url param and the SECRET API KEY sending it as header with the prop x-api-key. Is a GET method.

    0
  • Comment author
    Luca De Angelis

    Hi Raquel Lopez I do use a fresh token (I take it directly after the log in) and encode it into the endpoint ( "https://admin.memberstack.com/members/verify-token?token=eyJhbGciOiJSUzI1NiIsInR5cCI6Ik....." => I checked and this works well). Then run a GET request with the secret api key (which works for the identifiaction) and get back still {"data": null} .

    The code is very simple, but maybe is there something wrong? It seems the problem it's that the token that I send is not matching any member in the API call:

    // Define the API endpoint $endpoint = "https://admin.memberstack.com/members/verify-token?token=" . urlencode($token) ; // Define your API key $api_key = 'sk_sb_..............'; // Initialize cURL session $curl = curl_init(); // Set cURL options curl_setopt_array($curl, array( CURLOPT_URL => $endpoint, CURLOPT_RETURNTRANSFER => true, // Return response as a string CURLOPT_HTTPHEADER => array( 'x-api-key: ' . $api_key, // Set API key as a header ), )); // Execute the request $response = curl_exec($curl); // Check for errors if (curl_errno($curl)) { $error_message = curl_error($curl); // Handle cURL error echo "cURL Error: $error_message"; } else { // Response successful // Handle the response data echo $response; } // Close cURL session curl_close($curl);
    0
  • Comment author
    Raquel Lopez

    Hi Tyler Bell Chukwudi Onyekwere could please you check the REST endpoint for /verify-token? The documentation is not very clear and is not returning the member data πŸ€”

    0
  • Comment author
    Tyler Bell

    For those that find this thread later πŸ™‚

    We improved the docs for verifying tokens here.

    0
  • Comment author
    Raquel Lopez

    Thanks for updating the docs! 🫢

    0

Please sign in to leave a comment.