Skip to content

Instantly share code, notes, and snippets.

@gunzip
Created December 4, 2019 09:38
Show Gist options
  • Save gunzip/b52074b206cd28da11001de8d56790ac to your computer and use it in GitHub Desktop.
Save gunzip/b52074b206cd28da11001de8d56790ac to your computer and use it in GitHub Desktop.
/**
* we need a couple of patches and some utility functions
* to the azure sdk, see
* https://github.com/teamdigitale/io-developer-portal-backend/tree/master/patches
*/
// tslint:disable:no-console
import * as dotenv from "dotenv";
dotenv.config({ path: __dirname + "/../local.env" });
import ApiManagementClient from "azure-arm-apimanagement";
import * as msGraph from "azure-graph";
import { UserCreateParameters } from "azure-graph/lib/models";
import { isNone } from "fp-ts/lib/Option";
import * as msRestAzure from "ms-rest-azure";
import * as randomstring from "randomstring";
import {
addUserToGroups,
getApimUser,
getUserSubscriptions
} from "../src/apim_operations";
import { login } from "./login";
const OLD_ARM_CLIENT_ID = "";
const OLD_ARM_CLIENT_SECRET = "";
const OLD_ARM_TENANT_ID = "";
const OLD_ARM_SUBSCRIPTION_ID = "";
const OLD_APIM_NAME = "agid-apim-prod";
const OLD_APIM_RG = "agid-rg-prod";
const NEW_ARM_CLIENT_ID = "";
const NEW_ARM_CLIENT_SECRET = "";
const NEW_ARM_TENANT_ID = "";
const NEW_ARM_SUBSCRIPTION_ID = "";
const NEW_APIM_NAME = "ioitalia-apim-prod";
const NEW_APIM_RG = "ioitalia-rg-prod";
const NEW_ADB2C_CLIENT_ID = "";
const NEW_ADB2C_CLIENT_KEY = "";
const NEW_ADB2C_TENANT_ID = "ioitalia.onmicrosoft.com";
async function init(): Promise<ReadonlyArray<void>> {
const email = (process.argv[2] || "").trim();
if (email === "") {
throw new Error("please provide an email");
}
const oldCreds = await login(
OLD_ARM_CLIENT_ID,
OLD_ARM_CLIENT_SECRET,
OLD_ARM_TENANT_ID,
OLD_ARM_SUBSCRIPTION_ID
);
const oldApiClient = new ApiManagementClient(
oldCreds.creds,
oldCreds.subscriptionId
);
const oldApimOpt = {
azurermApim: OLD_APIM_NAME,
azurermResourceGroup: OLD_APIM_RG
};
const maybeOldApimUser = await getApimUser(oldApiClient, email, oldApimOpt);
if (isNone(maybeOldApimUser)) {
throw new Error("no user found " + email);
}
const oldApimUser = maybeOldApimUser.value;
console.log(
"%s (%s)",
JSON.stringify(oldApimUser),
Array.from(oldApimUser.groupNames).join(",")
);
// login into new active directory b2c
const newTokenCreds = await msRestAzure.loginWithServicePrincipalSecret(
NEW_ADB2C_CLIENT_ID,
NEW_ADB2C_CLIENT_KEY,
NEW_ADB2C_TENANT_ID,
{ tokenAudience: "graph" }
);
const newAdb2cClient = new msGraph.GraphRbacManagementClient(
newTokenCreds,
NEW_ADB2C_TENANT_ID
);
// const oldAdUser = await adb2cClient.users.get()
// Create user into new ADB2C tenant and get the user's id
const newAdUser = await newAdb2cClient.users.create(({
accountEnabled: true,
creationType: "LocalAccount",
displayName: oldApimUser.firstName + " " + oldApimUser.lastName,
givenName: oldApimUser.firstName,
// mail: oldApimUser.email,
mailNickname: oldApimUser.email.split("@")[0],
passwordProfile: {
forceChangePasswordNextLogin: true,
password: randomstring.generate({ length: 16 }) + "!"
},
signInNames: [
// controls which identifier the user uses to sign in to the account
{
type: "emailAddress",
value: oldApimUser.email
}
],
surname: oldApimUser.lastName,
// userPrincipalName: oldApimUser.email,
userType: "Member"
// tslint:disable-next-line:no-any
} as any) as UserCreateParameters);
// login into new api management
const newCreds = await login(
NEW_ARM_CLIENT_ID,
NEW_ARM_CLIENT_SECRET,
NEW_ARM_TENANT_ID,
NEW_ARM_SUBSCRIPTION_ID
);
const newApiClient = new ApiManagementClient(
newCreds.creds,
newCreds.subscriptionId
);
const newApimOpt = {
azurermApim: NEW_APIM_NAME,
azurermResourceGroup: NEW_APIM_RG
};
// Create new user into new API management
const newApimUser = await newApiClient.user.createOrUpdate(
NEW_APIM_RG,
NEW_APIM_NAME,
oldApimUser.name,
{
email: oldApimUser.email,
firstName: oldApimUser.firstName!,
identities: [
{
id: newAdUser.objectId,
provider: "AadB2C"
}
],
lastName: oldApimUser.lastName!
}
);
// Copy all previous user's groups
// groups must exist
await addUserToGroups(
newApiClient,
newApimUser,
Array.from(oldApimUser.groupNames),
newApimOpt
);
// Copy all previous user's subscriptions
const userSubscriptions = await getUserSubscriptions(
oldApiClient,
oldApimUser.name,
oldApimOpt
);
return Promise.all(
userSubscriptions.map(async subscription => {
await newApiClient.subscription.createOrUpdate(
NEW_APIM_RG,
NEW_APIM_NAME,
subscription.name!,
{
displayName: subscription.displayName!,
primaryKey: subscription.primaryKey,
// TODO: must exists
productId: subscription.productId,
secondaryKey: subscription.secondaryKey,
state: subscription.state,
userId: newApimUser.id!
}
);
})
);
}
init().then(console.log).catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment