Skip to content

Instantly share code, notes, and snippets.

@thevrus
Last active March 29, 2022 21:35
Show Gist options
  • Select an option

  • Save thevrus/1639c2f1265cca81526f0c5034ca3d87 to your computer and use it in GitHub Desktop.

Select an option

Save thevrus/1639c2f1265cca81526f0c5034ca3d87 to your computer and use it in GitHub Desktop.
function (user, context, callback) {
if (
context.clientMetadata &&
context.clientMetadata.shopify_domain &&
context.clientMetadata.shopify_multipass_secret
) {
const RULE_NAME = "shopify-multipasstoken";
const CLIENTNAME = context.clientName;
const BLOCK_SIZE = 16;
const secret = context.clientMetadata.shopify_multipass_secret;
const hash = crypto.createHash("sha256").update(secret).digest();
const encryptionKey = hash.slice(0, 16);
const signingKey = hash.slice(16, 32);
const generateUrl = (obj, domain) => {
if (!domain) return;
return "https://" + domain + "/account/login/multipass/" + encode(obj);
};
const sign = (data) => {
return crypto.createHmac("SHA256", signingKey).update(data).digest();
};
const encrypt = (plaintext) => {
// Use a random IV
const iv = crypto.randomBytes(BLOCK_SIZE);
const cipher = crypto.createCipheriv("aes-128-cbc", encryptionKey, iv);
// Use IV as first block of ciphertext
const encrypted = Buffer.concat([
iv,
cipher.update(plaintext, "utf8"),
cipher.final(),
]);
return encrypted;
};
const encode = (obj) => {
if (!obj) return;
// Store the current time in ISO8601 format.
// The token will only be valid for a small timeframe around this timestamp.
obj.created_at = new Date().toISOString();
// Serialize the customer data to JSON and encrypt it
const cipherText = encrypt(JSON.stringify(obj));
// Create a signature (message authentication code) of the ciphertext
// and encode everything using URL-safe Base64 (RFC 4648)
let token = Buffer.concat([cipherText, sign(cipherText)]).toString(
"base64"
);
token = token
.replace(/\+/g, "-") // Replace + with -
.replace(/\//g, "_"); // Replace / with _
return token;
};
let shopifyToken = {
email: user.email,
created_at: (new Date()).toISOString(),
// identifier: user.user_id,
// remote_ip: context.request.ip
};
if (
context.request &&
context.request.query &&
context.request.query.return_to
) {
shopifyToken.return_to = context.request.query.return_to;
}
if (context.user_metadata) {
shopifyToken.first_name = user.user_metadata.given_name;
shopifyToken.last_name = user.user_metadata.family_name;
}
const url = generateUrl(
shopifyToken,
context.clientMetadata.shopify_domain
);
context.redirect = {
url,
};
}
return callback(null, user, context);
}
@thevrus
Copy link
Copy Markdown
Author

thevrus commented Mar 14, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment