{"size": 1376, "ext": "js", "max_stars_repo_path": "src/scripts/index.js", "max_stars_repo_name": "travishorn/netlifyidentity", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/scripts/index.js", "max_issues_repo_name": "travishorn/netlifyidentity", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scripts/index.js", "max_forks_repo_name": "travishorn/netlifyidentity", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.0181818182, "max_line_length": 69, "alphanum_fraction": 0.6453488372}
import netlifyIdentity from "netlify-identity-widget";

const checkIdentityBtn = document.getElementById("checkIdentityBtn");
const identityOutput = document.getElementById("identityOutput");
const callFunctionBtn = document.getElementById("callFunctionBtn");
const functionOutput = document.getElementById("functionOutput");

netlifyIdentity.init();

const checkIdentity = () => {
  identityOutput.innerText = JSON.stringify(
    netlifyIdentity.currentUser(),
    null,
    2
  );
};

const generateHeaders = () => {
  const headers = { "Content-Type": "application/json" };

  if (netlifyIdentity.currentUser()) {
    return netlifyIdentity
      .currentUser()
      .jwt()
      .then(token => {
        return {
          ...headers,
          Authorization: `Bearer ${token}`
        };
      });
  }

  return Promise.resolve(headers);
};

const callFunction = () => {
  generateHeaders().then(headers => {
    fetch("/.netlify/functions/protected", {
      method: "POST",
      headers,
      body: JSON.stringify({ message: "Hello World" })
    })
      .then(res => res.json())
      .then(data => {
        functionOutput.innerText = JSON.stringify(data);
      })
      .catch(err => {
        functionOutput.innerText = err;
      });
  });
};

checkIdentityBtn.addEventListener("click", checkIdentity);
callFunctionBtn.addEventListener("click", callFunction);
