var url = Npm.require("url");

// There is one connect handler used by all auth redirects.  Keep track of all
// handlers which are currently being processed by shopify so that the connect
// handler knows where to "return".
//
// uuid => { authenticatorConfig, callback }
var handlers = { };

// Install the connect handler the first time it's needed.
var installWebAppHandler = _.once(function() {
    WebApp.connectHandlers.use("/__shopify-auth", function ShopifyAuthRedirect(req, res) {
        var uri = url.parse(req.url, true);

        var code = uri.query.code;
        var signature = uri.query.signature;
        var timestamp = uri.query.timestamp;

        var pathname = uri.pathname;
        var uuid = pathname.replace("/__shopify-auth?id=", "");

        // For some reason, there's an extra slash at the start.
        uuid = uuid.replace(/^\//, "");

        var handler = handlers[uuid];
        if (!handler) {
            console.error("No handler");
            res.writeHeader(500, { });
            res.end("<html><head><title>Error</title></head><body>Shopify Auth failed because no handler</body></html>");
            return;
        }

        var authenticatorConfig = handler.authenticatorConfig;
        var callback = handler.callback;
        delete handlers[uuid];

        if (authenticatorConfig.post_auth_uri === "close") {
            res.writeHead(200, { });
            res.end("<html><head><script>window.close()</script></head><body></body></html>");
        } else if (authenticatorConfig.embedded_app_sdk) {
            res.writeHead(200, { });
            res.end("<script type='text/javascript'>window.top.location.href = '" + authenticatorConfig.post_auth_uri + "';</script>");
        } else {
            res.writeHead(302, {
                "Location": authenticatorConfig.post_auth_uri
            });
            res.end();
        }

        Shopify._getPermanentAccessToken(authenticatorConfig, code, callback);
    });
});

Shopify._getPermanentAccessToken = function(authenticatorConfig, code, callback) {
    var accessTokenUrl = [
        "https://",
        authenticatorConfig.shop,
        ".myshopify.com/admin/oauth/access_token"
    ].join("");

    var keyset = Shopify._keysets[authenticatorConfig.keyset];
    var secret = keyset.secret;

    var res = HTTP.post(accessTokenUrl, {
        data: {
            client_id: authenticatorConfig.api_key,
            client_secret: secret,
            code: code
        }
    });

    if (res.statusCode === 200) {
        callback(null, res.data.access_token);
    } else {
        callback("Shopify access_token request failed with status " + res.statusCode);
    }
};

var asyncHandleAuthRedirect = function(authenticatorConfig, callback) {
    var redirect_uri = authenticatorConfig.redirect_uri;

    var uri = url.parse(redirect_uri, true);
    var pathname = uri.pathname;
    var uuid = pathname.replace("/__shopify-auth/", "");

    handlers[uuid] = {
        authenticatorConfig: authenticatorConfig,
        callback: callback
    };
};

var handleAuthRedirect = Meteor.wrapAsync(asyncHandleAuthRedirect);

Meteor.methods({
    "froatsnook:shopify/HandleAuthRedirect": function(authenticatorConfig) {
        // Install the web app handler in case it hasn't already been installed
        installWebAppHandler();

        var access_token = handleAuthRedirect(authenticatorConfig);
        return access_token;
    }
});


@@ -525,24 +525,61 @@
 rl, true);%0A%0A
+        var pathname = uri.pathname;%0A
         var 
@@ -691,17 +691,16 @@
 estamp;%0A
-%0A
         
@@ -707,233 +707,129 @@
 var 
-pathname = uri.pathname;%0A        var uuid = pathname.replace(%22/__shopify-auth?id=%22, %22%22);%0A%0A        // For some reason, there's an extra slash at the start.%0A        uuid = uuid.replace(/%5E%5C//, %22%22);%0A%0A        var handler =
+uuid = uri.query.id;%0A%0A        var handler = handlers%5Buuid%5D;%0A        if (!handler) %7B%0A            console.error(%22No
  handler
 s%5Buu
@@ -828,40 +828,27 @@
 dler
-s%5B
+ (
 uuid
-%5D;%0A        if (!handler) %7B
+=%25s)%22, uuid);
 %0A   
@@ -875,19 +875,44 @@
 or(%22
-No 
+Handlers are%22, Object.keys(
 handler
-%22
+s)
 );%0A 
@@ -2801,36 +2801,32 @@
 e);%0A    var path
-name
  = uri.pathname;
@@ -2816,28 +2816,24 @@
 h = uri.path
-name
 ;%0A    var uu
@@ -2841,20 +2841,16 @@
 d = path
-name
 .replace
@@ -2866,17 +2866,20 @@
 ify-auth
-/
+?id=
 %22, %22%22);%0A

Fix auth.