var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.isDocument = exports.isWindow = exports.hasStorageAccess = exports.processAuth = exports.refreshAuth = exports.removeCookies = exports.getCookieUID = exports.getCookieToken = exports.setCookieShopify = exports.setCookieHmac = exports.isAuthenticated = exports.getShop = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _universalCookie = _interopRequireDefault(require("universal-cookie"));

var _axios = _interopRequireDefault(require("axios"));

const getShop = () => {
  const url = getUrl();
  return url ? url.get("shop") ? url.get("shop") : isDocument && document.location.ancestorOrigins && document.location.ancestorOrigins[0] ? document.location.ancestorOrigins[0].replace("https://", "") : "" : "";
};

exports.getShop = getShop;

const isAuthenticated = onNavigate => {
  var url;
  return _regenerator.default.async(function _callee$(_context) {
    while (1) switch (_context.prev = _context.next) {
      case 0:
        url = getUrl();

        if (!isAuthValid({
          token: url.get("token"),
          uid: url.get("uid")
        })) {
          _context.next = 5;
          break;
        }

        return _context.abrupt("return", true);

      case 5:
        if (getShop()) {
          _context.next = 8;
          break;
        }

        onNavigate("/install");
        return _context.abrupt("return", false);

      case 8:
        _context.next = 10;
        return _regenerator.default.awrap(refreshAuth());

      case 10:
        return _context.abrupt("return", _context.sent);

      case 11:
      case "end":
        return _context.stop();
    }
  }, null, null, null, Promise);
};

exports.isAuthenticated = isAuthenticated;

const setCookieHmac = query => {
  const expDate = new Date();
  expDate.setTime(expDate.getTime() + 5 * 60 * 1000); // 5 minutes

  setCookie(getKeys().hmac, query, expDate);
};

exports.setCookieHmac = setCookieHmac;

const setCookieShopify = apiKey => {
  setCookie(getKeys().shopify, true);
  if (isWindow) window.location.href = `https://${getShop()}/admin/apps/${apiKey}`;
};

exports.setCookieShopify = setCookieShopify;

const getCookieToken = () => cookies.get(getKeys().token);

exports.getCookieToken = getCookieToken;

const getCookieUID = () => cookies.get(getKeys().uid);

exports.getCookieUID = getCookieUID;

const removeCookies = () => Object.keys(getKeys()).map(key => cookies.remove(getKeys()[key]));

exports.removeCookies = removeCookies;

const refreshAuth = () => {
  if (!getShop() || !hasCookieAccess()) return false;
  return _axios.default.post("/auth", {
    shop: getShop()
  }).then(res => processAuth(res)).catch(err => {
    console.warn(err);
    return false;
  });
};

exports.refreshAuth = refreshAuth;

const processAuth = res => {
  if (res.data && res.data.body) {
    remoteRedirect(res.data.body);
  } else {
    throw new Error("Invalid /auth API response");
  }
};

exports.processAuth = processAuth;

const hasStorageAccess = () => {
  if (navigator.cookieEnabled && !navigator.userAgent.match(/Version\/12\.0\.?\d? Safari/)) {
    return true;
  } else {
    setCookieTest();
    return cookies.get(getKeys().test);
  }
};

exports.hasStorageAccess = hasStorageAccess;
const cookies = new _universalCookie.default();

const getKeys = () => ({
  shopify: `shopify.cookies_persist`,
  test: `reactify:test`,
  hmac: `reactify:hmac:${getShopName()}`,
  token: `reactify:token:${getShopName()}`,
  uid: `reactify:uid:${getShopName()}`
});

const getUrl = () => isWindow ? new URLSearchParams(window.location.search) : {
  get: () => "",
  set: () => ""
}; // || cookies.get(`reactify:hmac:${shopName}`)


const getShopName = () => getShop().replace(".myshopify.com", "");

const setCookie = (key, value, expiry = null) => cookies.set(key, value, {
  path: "/",
  expires: expiry,
  secure: true,
  sameSite: "none"
});

const setCookieAuth = (token, uid) => {
  const expDate = new Date();
  expDate.setTime(expDate.getTime() + 24 * 60 * 60 * 1000);
  setCookie(getKeys().uid, uid, expDate);
  setCookie(getKeys().token, token, expDate);
  cookies.remove(getKeys().hmac);
};

const setCookieTest = () => {
  const expDate = new Date();
  expDate.setTime(expDate.getTime() + 1 * 60 * 1000);
  setCookie(getKeys().test, true, expDate);
};

const hasCookieAccess = () => {
  if (shouldRequestStorage() && isWindow) {
    remoteRedirect(`${window.location.origin}/errorerror/cookies?shop=https://${getShop()}`);
    return false;
  }

  return true;
};

const shouldRequestStorage = () => {
  if (cookies.get(getKeys().shopify)) return false;
  if (isWindow && window.top === window.self) return false;
  if (!navigator.userAgent.match(/Safari/)) return false;
  if (navigator.userAgent.match(/Chrome/)) return false;
  if (navigator.userAgent.indexOf("com.jadedpixel.pos") !== -1) return false;
  if (navigator.userAgent.indexOf("Shopify Mobile/iOS") !== -1) return false;
  return !cookies.get(getKeys().shopify);
};

const isAuthValid = ({
  token,
  uid
}) => {
  if (getCookieToken() && getCookieUID()) {
    return true;
  } else if (token && uid) {
    setCookieAuth(token, uid);
    return {
      shop: getShop()
    };
  }

  return false;
};

const remoteRedirect = url => {
  if (isWindow && isDocument) {
    if (window.top === window.self) {
      window.top.location.href = url;
    } else {
      let link = document.createElement("a");
      link.href = url;
      const message = JSON.stringify({
        message: "Shopify.API.remoteRedirect",
        data: {
          location: link.href
        }
      });
      window.parent.postMessage(message, `https://${getShop()}`);
    }
  }
};

const isWindow = typeof window !== "undefined";
exports.isWindow = isWindow;
const isDocument = typeof document !== "undefined";
exports.isDocument = isDocument;
//# sourceMappingURL=auth.js.map