emadalam / atvjs

Blazing fast Apple TV application development using pure JavaScript
https://emadalam.github.io/atvjs
MIT License
311 stars 49 forks source link

Secure image fetch #45

Closed ruudboon closed 4 years ago

ruudboon commented 5 years ago

Would it possible to add a header when fetching images? My app requires authorisation for downloading user images, this can be done by adding a Authorization header with the bearer token to the request.

emadalam commented 5 years ago

@ruudboon Can you try using the fetch api to fetch the actual image with whatever headers and other details you prefer. You can then convert it to base64 format which can be used as your image source. It's a bit lengthy solution, but should work, give it a try and let me know.

For your reference, you can do something like below (I haven't tested the code but it should work)

function arrayBufferToBase64(buffer) {
  const bytes = [].slice.call(new Uint8Array(buffer));
  const binary = bytes.reduce((binary, byte) =>
    `${binary}${String.fromCharCode(byte)}`, '');

  return window.btoa(binary);
};

const DEFAULT_OPTS = {
  method: 'GET',
  mode: 'cors',
  cache: 'default'
};

function getSecureImage(src, token, opts = {}) {
  const headers = new Headers({ 'Authorization': `Bearer ${token}'` });
  const options = { ...DEFAULT_OPTS, headers, ...opts };
  const request = new Request(src);

  let resolve; let reject;
  const promise = new Promise((...args) => [resolve, reject] = args);

  fetch(request, options).then((response) => {
    response.arrayBuffer().then((buffer) => {
      const base64Flag = 'data:image/jpeg;base64,'; // set your image format here
      const imageStr = arrayBufferToBase64(buffer);
      const imageSrc = `${base64Flag}${imageStr}`;
      resolve(imageSrc);
    });
  });

  return promise;
}