Skip to content

Instantly share code, notes, and snippets.

@ezekg
Last active September 21, 2017 14:06
Show Gist options
  • Save ezekg/1be534edc1f5f47855f39f1849a61865 to your computer and use it in GitHub Desktop.
Save ezekg/1be534edc1f5f47855f39f1849a61865 to your computer and use it in GitHub Desktop.
Import licenses from an existing system into Keygen (https://keygen.sh)
# Install the 'node-fetch' library
npm install node-fetch
# Run the script by providing the required environment vars
KEYGEN_PRODUCT_TOKEN='' KEYGEN_ACCOUNT_ID='' KEYGEN_POLICY_ID='' ./import.js
#!/usr/bin/env node
"use strict"
const fetch = require("node-fetch")
const {
KEYGEN_PRODUCT_TOKEN, // A product token that belongs to your account (see: https://app.keygen.sh/tokens)
KEYGEN_ACCOUNT_ID, // Your account's UUID (see: https://app.keygen.sh/settings)
KEYGEN_POLICY_ID // The ID of the policy that you want licenses to implement (see: https://app.keygen.sh/policies)
} = process.env
if (KEYGEN_PRODUCT_TOKEN == null) {
console.error('Environment variable KEYGEN_PRODUCT_TOKEN is required')
process.exit(1)
}
if (KEYGEN_ACCOUNT_ID == null) {
console.error('Environment variable KEYGEN_ACCOUNT_ID is required')
process.exit(1)
}
if (KEYGEN_POLICY_ID == null) {
console.error('Environment variable KEYGEN_POLICY_ID is required')
process.exit(1)
}
const licenseCodes = [/* get an array of existing license codes e.g. by parsing a CSV file, etc. */]
for (let licenseCode of licenseCodes) {
fetch(`https://api.keygen.sh/v1/accounts/${KEYGEN_ACCOUNT_ID}/licenses`, {
method: "POST",
headers: {
"Content-Type": "application/vnd.api+json",
"Accept": "application/vnd.api+json",
"Authorization": `Bearer ${YOUR_PRODUCT_TOKEN}`
},
body: JSON.stringify({
data: {
type: "licenses",
attributes: {
key: licenseCode
},
relationships: {
policy: {
data: { type: "policies", id: KEYGEN_POLICY_ID }
}
}
}
})
})
.then(response => response.json())
.then(json => {
const { data, errors } = json
if (errors) {
console.error(`Failed to import license code '${licenseCode}': ${errors.map(e => e.detail))}`)
} else {
console.log(`Successfully to imported license code '${licenseCode}: ${data.id}`)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment