Test

Created Diff never expires
5 removals
157 lines
71 additions
224 lines
var thisO = Get('ivanti_AzureADint#', "$(RecId)");
var thisO = Get('ivanti_AzureADint#', "$(RecId)");
var serverURL="$(SecureServerURL())";
var serverURL="$(SecureServerURL())";


console.log("<br>Get vars");
console.log("<br>Get vars");
var client_tenant_id = thisO.Fields['ClientTenantID'];
var client_tenant_id = thisO.Fields['ClientTenantID'];
var client_secret = thisO.Fields['ClientSecret'];
var client_secret = thisO.Fields['ClientSecret'];
var client_id = thisO.Fields['ClientID'];
var client_id = thisO.Fields['ClientID'];
var bTestMode = thisO.Fields['TestMode'] == 1;
var bTestMode = thisO.Fields['TestMode'] == 1;
var client_api = thisO.Fields['API_Key'];
var client_api = thisO.Fields['API_Key'];
//What will be used as primary key
//What will be used as primary key
//NOTE: This will overwrite other values not designated as primary key
//NOTE: This will overwrite other values not designated as primary key
var useEmail = thisO.Fields['useEmail'] == 1;
var useEmail = thisO.Fields['useEmail'] == 1;
var useUPN = thisO.Fields['useLogin'] == 1;
var useUPN = thisO.Fields['useLogin'] == 1;
var useAzureID = thisO.Fields['useGUID'] == 1;
var useAzureID = thisO.Fields['useGUID'] == 1;


//Build my filter
//Build my filter
var sMasterToken = {};
var sMasterToken = {};
//Filter?
//Filter?
var sFltr = thisO.Fields['ADFilter'];
var sFltr = thisO.Fields['ADFilter'];


var sEndpoint = 'https://login.microsoftonline.com/' + client_tenant_id + '/oauth2/v2.0/token';
var sEndpoint = 'https://login.microsoftonline.com/' + client_tenant_id + '/oauth2/v2.0/token';
console.log("<br>Setting tokens " + sEndpoint);
console.log("<br>Setting tokens " + sEndpoint);


function byteLength(str) {
function byteLength(str) {
// returns the byte length of an utf8 string
// returns the byte length of an utf8 string
var s = str.length;
var s = str.length;
for (var i=str.length-1; i>=0; i--) {
for (var i=str.length-1; i>=0; i--) {
var code = str.charCodeAt(i);
var code = str.charCodeAt(i);
if (code > 0x7f && code <= 0x7ff) s++;
if (code > 0x7f && code <= 0x7ff) s++;
else if (code > 0x7ff && code <= 0xffff) s+=2;
else if (code > 0x7ff && code <= 0xffff) s+=2;
if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
}
}
return s;
return s;
}
}


var sBodyToPass = 'client_id='+ client_id + '&Client_secret='+ client_secret + '&grant_type=client_credentials&scope=https://graph.microsoft.com/.default';
var sBodyToPass = 'client_id='+ client_id + '&Client_secret='+ client_secret + '&grant_type=client_credentials&scope=https://graph.microsoft.com/.default';
var byteL = byteLength(sBodyToPass);
var byteL = byteLength(sBodyToPass);


const Params = {
const Params = {
Headers: {
Headers: {
'Content-Type': "application/x-www-form-urlencoded",
'Content-Type': "application/x-www-form-urlencoded",
'Accept': '*/*',
'Accept': '*/*',
'Content-Length' : byteL,
'Content-Length' : byteL,
'Accept-Encoding' : 'gzip, deflate, br'
'Accept-Encoding' : 'gzip, deflate, br'
}
}
};
};
// End of WWW encode
// End of WWW encode
var resp = ExecuteWebRequest("POST", sEndpoint, sBodyToPass, Params);
var resp = ExecuteWebRequest("POST", sEndpoint, sBodyToPass, Params);
if ((resp != null) && (resp.StatusCode == 200)) {
if ((resp != null) && (resp.StatusCode == 200)) {
console.log("<br>Status code " + resp.StatusCode + "<br>" + JSON.stringify(JSON.parse(resp.Data)) + "<br><br>");
console.log("<br>Status code " + resp.StatusCode + "<br>" + JSON.stringify(JSON.parse(resp.Data)) + "<br><br>");
//Let us extract the access token
//Let us extract the access token
var accessToken = JSON.parse(resp.Data).access_token;
var accessToken = JSON.parse(resp.Data).access_token;
var tokenType = JSON.parse(resp.Data).token_type;
var tokenType = JSON.parse(resp.Data).token_type;
sMasterToken = accessToken;
sMasterToken = accessToken;
console.log("Access token is " + accessToken + " and type is " + tokenType);
console.log("Access token is " + accessToken + " and type is " + tokenType);
runMe(accessToken, sEndpoint);
runMe(accessToken, sEndpoint);
} else {
} else {
console.log("<br>Status code is not successfull " + resp.StatusCode + "<br>");
console.log("<br>Status code is not successfull " + resp.StatusCode + "<br>");
console.log(JSON.stringify(resp.Data) + "<br>")
console.log(JSON.stringify(resp.Data) + "<br>")
}
}


//REST INSERT
//REST INSERT
function HTTPinsertEmp(struct) {
function HTTPinsertEmp(struct) {
console.log("<br>Insert HTTP</br>");
console.log("<br>Insert HTTP</br>");
let myHeader = {
let myHeader = {
Headers: {
Headers: {
"SkipServerCertificateValidation": true,
"SkipServerCertificateValidation": true,
"AllowAutoRedirect": false,
"AllowAutoRedirect": false,
"Authorization": "rest_api_key=" + client_api,
"Authorization": "rest_api_key=" + client_api,
"Content-Type": "application/json"
"Content-Type": "application/json"
}
}
};
};
let sEndP = serverURL + "api/odata/businessobject/employees";
let sEndP = serverURL + "api/odata/businessobject/employees";
console.log("<br>Tenant URL s " + sEndP + "<br>");
console.log("<br>Tenant URL s " + sEndP + "<br>");
let rIns = ExecuteWebRequest("POST", sEndP, JSON.stringify(struct), myHeader);
let rIns = ExecuteWebRequest("POST", sEndP, JSON.stringify(struct), myHeader);
if ((rIns != null) && (rIns.StatusCode == 200)) {
if ((rIns != null) && (rIns.StatusCode == 200)) {


} else {
} else {
console.log("<br>Insert Failed! " + rIns.StatusCode + "<br>");
console.log("<br>Insert Failed! " + rIns.StatusCode + "<br>");
console.log(JSON.stringify(rIns.Data) + "<br>")
console.log(JSON.stringify(rIns.Data) + "<br>")
}
}
};
};




//Insert Queue
//Insert Queue
function HTTPinsertQueue(struct) {
function HTTPinsertQueue(struct) {
console.log("<br>Insert HTTP QUEUE</br>");
console.log("<br>Insert HTTP QUEUE</br>");
let myHeader = {
let myHeader = {
Headers: {
Headers: {
"SkipServerCertificateValidation": true,
"SkipServerCertificateValidation": true,
"AllowAutoRedirect": false,
"AllowAutoRedirect": false,
"Authorization": "rest_api_key=" + client_api,
"Authorization": "rest_api_key=" + client_api,
"Content-Type": "application/json"
"Content-Type": "application/json"
}
}
};
};
let sEndP = serverURL + "api/odata/businessobject/AzureADQueues";
let sEndP = serverURL + "api/odata/businessobject/AzureADQueues";
console.log("<br>Tenant URL s " + sEndP + "<br>");
console.log("<br>Tenant URL s " + sEndP + "<br>");
let oJ = {
let oJ = {
ParentRECID: "$(RecId)",
ParentRECID: "$(RecId)",
JSONVal: JSON.stringify(struct)
JSONVal: JSON.stringify(struct)
}
}
let rIns = ExecuteWebRequest("POST", sEndP, JSON.stringify(oJ), myHeader);
let rIns = ExecuteWebRequest("POST", sEndP, JSON.stringify(oJ), myHeader);
if ((rIns != null) && (rIns.StatusCode == 200)) {
if ((rIns != null) && (rIns.StatusCode == 200)) {


} else {
} else {
console.log("<br>Department Insert Failed! " + rIns.StatusCode + "<br>");
console.log("<br>Department Insert Failed! " + rIns.StatusCode + "<br>");
console.log(JSON.stringify(rIns.Data) + "<br>")
console.log(JSON.stringify(rIns.Data) + "<br>")
}
}
};
};
// Function to convert the "ExtensionAttribute" collection to one "ExtensionAttribute": "String"
function ConvertExtensionAttributesToString(jsonString) {

console.error("Entering extension attribute " + jsonString);

var isDone = false;
var convertedString = "";
var start = jsonString.indexOf('onPremisesExtensionAttributes\":{');
if (start == -1)
{
isDone = true;
convertedString = jsonString;
return [isDone, convertedString];
}
var extensionAttributesStringFirst = jsonString.substring(0,start);
var extensionAttributesStringSecond = jsonString.substring(start,jsonString.length);
var replacementString = '\}"';

extensionAttributesStringSecond = extensionAttributesStringSecond.replace('onPremisesExtensionAttributes\":{', 'onPremisesExtensionAttributes\":\"\{');
extensionAttributesStringSecond = extensionAttributesStringSecond.replace('}', replacementString);

var bracketEnd = extensionAttributesStringSecond.indexOf('}');
var bracketStart = extensionAttributesStringSecond.indexOf('{');

var extentionAttributeModifiedString = extensionAttributesStringSecond.substring(bracketStart, bracketEnd+1).replace(/"/g, '\\\"');
console.error("Printing extentionAtrributeModified " + extentionAttributeModifiedString);

extensionAttributesStringSecond = extensionAttributesStringSecond.substring(0, bracketStart) + extentionAttributeModifiedString + extensionAttributesStringSecond.substring(bracketEnd + 1, extensionAttributesStringSecond.length);
isDone = false;
convertedString = extensionAttributesStringFirst+extensionAttributesStringSecond;

console.error("after extension attribute " + convertedString);
return [isDone, convertedString];
}

// Function to update all extensionAttributes in the startingJsonString
function RunConversionUntilComplete(startingJsonString){


console.error("Checking startingJsonString"+ startingJsonString );
var currentJsonString = startingJsonString;
// Replace every \" with "
currentJsonString = currentJsonString.replace(/\\\"/g, '\"');
// Remove first and last quote to avoid case where we have extra \" at start and end
currentJsonString = currentJsonString.substring(1, currentJsonString.length-1);
// TODO: Address this end condition, should it be X iterations or run for Y seconds? Should we get # of entries within JSON struct?
var recordCount = (startingJsonString.match(/givenName/g) || []).length;
for(var i = 0; i < recordCount; ++i)
{
const result = ConvertExtensionAttributesToString(currentJsonString);


if (result[0])
{
break;
}
currentJsonString = result[1];
}
// Put back our JSON brackets removed above
currentJsonString = '{' + currentJsonString + '}';
return currentJsonString;
}


// Main loop
// Main loop
function runMe(token, url) {
function runMe(token, url) {
//Get User list
//Get User list
const userParams = {
const userParams = {
Headers: {
Headers: {
'Authorization': 'Bearer ' + token,
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
'Content-Type': 'application/json',
'ConsistencyLevel':'eventual'
},
},
SkipServerCertificateValidation: true,
SkipServerCertificateValidation: true,
AllowAutoRedirect: false
AllowAutoRedirect: false
};
};
var sUsers = 'https://graph.microsoft.com/v1.0/users?$top=200';
var sUsers = 'https://graph.microsoft.com/v1.0/users?$count=true&$select=companyName,businessPhones,displayName,givenName,id,jobTitle,mail,mobilePhone,officeLocation,surname,userPrincipalName,accountEnabled,city,department,state,streetAddress,postalCode,country,lastPasswordChangeDateTime,onPremisesExtensionAttributes';
console.log("<br>FILTER " + sFltr);
console.log("<br>FILTER " + sFltr);
if (sFltr !== null && sFltr != '' && sFltr !== undefined) sUsers = sUsers + "&$filter=" + sFltr;
if (sFltr !== null && sFltr != '' && sFltr !== undefined) sUsers = sUsers + "&$filter=" + sFltr;
//sUsers = "https://graph.microsoft.com/v1.0/users?$filter=givenName eq 'user'";
//sUsers = "https://graph.microsoft.com/v1.0/users?$filter=givenName eq 'user'";
var usersList = ExecuteWebRequest("GET", sUsers, null, userParams);
var usersList = ExecuteWebRequest("GET", sUsers, null, userParams);
if ((usersList != null) && (usersList.StatusCode == 200 || usersList.StatusCode == 201)) {
if ((usersList != null) && (usersList.StatusCode == 200 || usersList.StatusCode == 201)) {
//console.log('<br>' + JSON.stringify(usersList.Data) );
//console.log('<br>' + JSON.stringify(usersList.Data) );
let JS = JSON.parse(usersList.Data);
let JS = JSON.parse(RunConversionUntilComplete(JSON.stringify(JSON.parse(usersList.Data))));
if (JS) HTTPinsertQueue(JS);
if (JS) HTTPinsertQueue(JS);
let skipURL = JS['@odata.nextLink'];
let skipURL = JS['@odata.nextLink'];
thisO.Update({DebugText : JSON.stringify(usersList.Data)});
thisO.Update({DebugText : JSON.stringify(usersList.Data)});
if (!bTestMode)
if (!bTestMode)
{
{
while (skipURL){
while (skipURL){
console.log('<br>skipURL is ' + skipURL);
console.log('<br>skipURL is ' + skipURL);
let usersList1 = ExecuteWebRequest("GET", skipURL, null, userParams);
let usersList1 = ExecuteWebRequest("GET", skipURL, null, userParams);
if ((usersList1 != null) && (usersList1.StatusCode == 200 || usersList1.StatusCode == 201)) {
if ((usersList1 != null) && (usersList1.StatusCode == 200 || usersList1.StatusCode == 201)) {
//thisO.Update({DebugText : JSON.stringify(usersList1.Data)});
//thisO.Update({DebugText : JSON.stringify(usersList1.Data)});
let JS = JSON.parse(usersList1.Data);
let JS = JSON.parse(RunConversionUntilComplete(JSON.stringify(JSON.parse(usersList1.Data))));
let skipURL = JS['@odata.nextLink'];
let skipURL = JS['@odata.nextLink'];
if (JS) HTTPinsertQueue(JS);
if (JS) HTTPinsertQueue(JS);
}
}
}
}
}
}
} else
} else
{
{
console.log("<br>Status code is not successfull " + usersList.StatusCode + "<br>");
console.log("<br>Status code is not successfull " + usersList.StatusCode + "<br>");
console.log(JSON.stringify(usersList.Data) + "<br>")
console.log(JSON.stringify(usersList.Data) + "<br>")
}
}
}
}