/*** Generated by streamline 0.10.17 (callbacks) - DO NOT EDIT ***/ "use strict"; var __rt=require('streamline/lib/callbacks/runtime').runtime(__filename, false),__func=__rt.__func,__cb=__rt.__cb,__catch=__rt.__catch,__tryCatch=__rt.__tryCatch,__forIn=__rt.__forIn; var __ = require("underscore");

















var utils = require("../../../util/utils");
var roleUtils = require("./roleUtils");

var $ = utils.getLocaleString;


exports.processInsightsResults = function exports_processInsightsResults__1(cli, log, insightsResults, subscription, graphClient, authzClient, _) { var startEvents, endEvents, offlineEvents, i, outputData, principalDetailsCache, roleDefinitionCache, scopeForRoleDefinitions, filterParameters, result, j, se, out, endEvent, startEvent, scope, messageBody, properties, principalId, index, resourceDetails, roleId, oe, outOffline, offlineEvent; var __frame = { name: "exports_processInsightsResults__1", line: 25 }; return __func(_, this, arguments, exports_processInsightsResults__1, 6, __frame, function __$exports_processInsightsResults__1() {
    startEvents = { }; endEvents = { }; offlineEvents = { };


    for (i = 0; (i < insightsResults.length); i++) {
      if ((insightsResults[i]["httpRequest"] && utils.ignoreCaseEquals((insightsResults[i]["status"]).value, "Started"))) {
        startEvents[insightsResults[i]["operationId"]] = insightsResults[i]; } else {
        if ((insightsResults[i]["httpRequest"] && !utils.ignoreCaseEquals((insightsResults[i]["status"]).value, "Started"))) {
          endEvents[insightsResults[i]["operationId"]] = insightsResults[i]; } else {

          if (((insightsResults[i]["eventName"] && insightsResults[i]["eventName"].value) && (insightsResults[i]["eventName"].value.toLowerCase().indexOf("classicadministrators") > 0))) {
            offlineEvents[insightsResults[i]["operationId"]] = insightsResults[i]; } ; } ; } ; };



    outputData = [];

    principalDetailsCache = { };


    roleDefinitionCache = { };

    scopeForRoleDefinitions = ("/subscriptions/" + subscription.id);
    filterParameters = { atScopeAndBelow: true };

    return authzClient.roleDefinitions.list(scopeForRoleDefinitions, filterParameters, __cb(_, __frame, 25, 43, function ___(__0, __3) { result = __3;

      for (j = 0; (j < result.roleDefinitions.length); j++) {

        result.roleDefinitions[j].id = roleUtils.getRoleDefinitionName(result.roleDefinitions[j].id);

        roleDefinitionCache[result.roleDefinitions[j]["id"]] = result.roleDefinitions[j]; };





      var __1 = __forIn(startEvents); var __2 = 0; return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$exports_processInsightsResults__1() { __more = false; var __5 = (__2 < __1.length); if (__5) { se = __1[__2++];
            out = { }; return (function __$exports_processInsightsResults__1(__then) {
              if (((((endEvents[se] && endEvents[se]["operationName"]) && endEvents[se]["operationName"].value) && utils.stringStartsWith(endEvents[se]["operationName"].value, "Microsoft.Authorization/RoleAssignments", true)) && utils.ignoreCaseEquals(endEvents[se]["status"].value, "Succeeded"))) {

                endEvent = endEvents[se];
                startEvent = startEvents[se];

                out["Timestamp"] = endEvent["eventTimestamp"];
                out["Caller"] = startEvent["caller"]; return (function __$exports_processInsightsResults__1(__then) {


                  if (((startEvent["httpRequest"] && startEvent["httpRequest"]["method"]) && utils.ignoreCaseEquals(startEvent["httpRequest"]["method"], "PUT"))) {
                    out["Action"] = "Granted"; return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$exports_processInsightsResults__1() {

                          messageBody = JSON.parse(startEvent["properties"]["requestbody"]); __then(); }); })(function ___(ex, __result) { __catch(function __$exports_processInsightsResults__1() { if (ex) { __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$exports_processInsightsResults__1() {



                        scope = startEvent.authorization.scope; __then(); }); }); } else { return (function __$exports_processInsightsResults__1(__then) {
                      if (((startEvent["httpRequest"] && startEvent["httpRequest"]["method"]) && utils.ignoreCaseEquals(startEvent["httpRequest"]["method"], "DELETE"))) {
                        out["Action"] = "Revoked"; return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$exports_processInsightsResults__1() {

                              messageBody = JSON.parse(endEvent["properties"]["responseBody"]); __then(); }); })(function ___(ex, __result) { __catch(function __$exports_processInsightsResults__1() { if (ex) { __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, __then); }); } else { __then(); } ; })(__then); } ; })(function __$exports_processInsightsResults__1() { return (function __$exports_processInsightsResults__1(__then) {





                    if (messageBody) {
                      messageBody = toCamelCaseObj(messageBody);
                      properties = messageBody["properties"];
                      properties = toCamelCaseObj(properties); return (function __$exports_processInsightsResults__1(__then) {


                        if (properties) {
                          principalId = properties["principalId"];
                          out["PrincipalId"] = principalId; return (function __$exports_processInsightsResults__1(__then) {
                            if (principalId) {
                              return getPrincipalDetails(principalId, principalDetailsCache, graphClient, __cb(_, __frame, 75, 12, function __$exports_processInsightsResults__1() {
                                if ((principalDetailsCache && principalDetailsCache[principalId])) {
                                  out["PrincipalName"] = principalDetailsCache[principalId]["Name"];
                                  out["PrincipalType"] = principalDetailsCache[principalId]["Type"]; } ; __then(); }, true)); } else { __then(); } ; })(__then); } else { __then(); } ; })(function __$exports_processInsightsResults__1() {





                        if ((!scope && properties)) {
                          scope = properties["scope"]; } ;

                        if (scope) {
                          index = scope.toLowerCase().indexOf("/providers/microsoft.authorization");
                          if ((index > 0)) {
                            scope = scope.substring(0, index); } ;


                          out["Scope"] = scope;
                          resourceDetails = { };
                          resourceDetails = getResourceDetails(out["Scope"]);
                          if (resourceDetails) {
                            out["ScopeName"] = resourceDetails["Name"];
                            out["ScopeType"] = resourceDetails["Type"]; } ; } ;




                        if (properties) {
                          out["RoleDefinitionId"] = roleUtils.getRoleDefinitionName(properties["roleDefinitionId"]);
                          roleId = out["RoleDefinitionId"];
                          if (roleId) {
                            if (roleDefinitionCache[roleId]) {
                              out["RoleName"] = roleDefinitionCache[roleId].properties.roleName; }
                             else {
                              out["RoleName"] = ""; } ; } ; } ; __then(); }); } else { __then(); } ; })(function __$exports_processInsightsResults__1() {





                    outputData.push(out); __then(); }); }); } else { __then(); } ; })(function __$exports_processInsightsResults__1() { while (__more) { __loop(); }; __more = true; }); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(function __$exports_processInsightsResults__1() {





        for (oe in offlineEvents) {
          outOffline = { };
          offlineEvent = offlineEvents[oe];
          if ((((((offlineEvent["status"] && offlineEvent["status"].value) && utils.ignoreCaseEquals(offlineEvent["status"].value, "Succeeded")) && offlineEvent["operationName"]) && offlineEvent["operationName"].value) && utils.stringStartsWith(offlineEvent["operationName"].value, "Microsoft.Authorization/ClassicAdministrators", true))) {
            outOffline["Timestamp"] = offlineEvent["eventTimestamp"];
            outOffline["Caller"] = "Subscription Admin";

            if (utils.ignoreCaseEquals(offlineEvent["operationName"].value, "Microsoft.Authorization/ClassicAdministrators/write")) {
              outOffline["Action"] = "Granted"; } else {

              if (utils.ignoreCaseEquals(offlineEvent["operationName"].value, "Microsoft.Authorization/ClassicAdministrators/delete")) {
                outOffline["Action"] = "Revoked"; } ; } ;


            outOffline["RoleDefinitionId"] = null;
            outOffline["PrincipalId"] = null;
            outOffline["PrincipalType"] = "User";
            outOffline["Scope"] = ("/subscriptions/" + subscription.id);
            outOffline["ScopeType"] = "Subscription";
            outOffline["ScopeName"] = subscription.id;

            if (offlineEvent["properties"]) {
              outOffline["PrincipalName"] = offlineEvent["properties"]["adminEmail"];
              outOffline["RoleName"] = ("Classic " + offlineEvent["properties"]["adminType"]); } ;


            outputData.push(outOffline); } ; };






        cli.interaction.formatOutput(outputData, function(data) {
          if ((data.length === 0)) {
            log.info($("No records were found in the specified search interval")); }
           else {
            data.sort(function(a, b) {
              return (new Date(a["Timestamp"]) - new Date(b["Timestamp"])); });

            for (var k = 0; (k < data.length); k++) {
              displayRecord(data[k], log); }; } ; }); _(); }); }, true)); });};





function toCamelCaseObj(obj) {
  var key, destKey, value;
  var camelCasedObj = { };
  if ((obj && (typeof obj === "object"))) {
    for (key in obj) {
      if (obj.hasOwnProperty(key)) {
        destKey = ((key.charAt(0).toLowerCase() + key.substring(1))).toString();
        value = obj[key];
        camelCasedObj[destKey] = value; } ; } };



  return camelCasedObj;};


function displayRecord(record, log) {
  log.data($("Timestamp         :"), record["Timestamp"]);
  log.data($("Caller            :"), record["Caller"]);
  log.data($("Action            :"), record["Action"]);
  log.data($("PrincipalId       :"), record["PrincipalId"]);
  log.data($("PrincipalName     :"), record["PrincipalName"]);
  log.data($("PrincipalType     :"), record["PrincipalType"]);
  log.data($("Scope             :"), record["Scope"]);
  log.data($("ScopeType         :"), record["ScopeType"]);
  log.data($("ScopeName         :"), record["ScopeName"]);
  log.data($("RoleDefinitionId  :"), record["RoleDefinitionId"]);
  log.data($("RoleName          :"), record["RoleName"]);
  log.data("");};



function getPrincipalDetails(principalId, principalDetailsCache, graphClient, _) { var principalDetails, user, group, sp; var __frame = { name: "getPrincipalDetails", line: 225 }; return __func(_, this, arguments, getPrincipalDetails, 3, __frame, function __$getPrincipalDetails() {
    if ((principalId in principalDetailsCache)) {
      return _(null, principalDetailsCache[principalId.toString()]); } ;


    principalDetails = { }; return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getPrincipalDetails() {



          return graphClient.users.get(principalId, __cb(_, __frame, 9, 29, function ___(__0, __1) { user = __1; __then(); }, true)); }); })(function ___(ex, __result) { __catch(function __$getPrincipalDetails() { if (ex) {

            if ((ex.statusCode !== 404)) {
              return _(ex); } ; __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$getPrincipalDetails() { return (function __$getPrincipalDetails(__then) {



          if (user) {
            principalDetails["Name"] = user.displayName;
            principalDetails["Type"] = "User";
            principalDetailsCache[principalId] = principalDetails; __then(); } else { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getPrincipalDetails() {



                  return graphClient.groups.get(principalId, __cb(_, __frame, 23, 33, function ___(__0, __2) { group = __2; __then(); }, true)); }); })(function ___(ex, __result) { __catch(function __$getPrincipalDetails() { if (ex) {

                    if ((ex.statusCode !== 404)) {
                      return _(ex); } ; __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$getPrincipalDetails() { return (function __$getPrincipalDetails(__then) {


                  if (group) {
                    principalDetails["Name"] = group.displayName;
                    principalDetails["Type"] = "Group";
                    principalDetailsCache[principalId] = principalDetails; __then(); } else { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getPrincipalDetails() {




                          return graphClient.servicePrincipals.get(principalId, __cb(_, __frame, 37, 43, function ___(__0, __3) { sp = __3; __then(); }, true)); }); })(function ___(ex, __result) { __catch(function __$getPrincipalDetails() { if (ex) {

                            if ((ex.statusCode !== 404)) {
                              return _(ex); } ; __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$getPrincipalDetails() {



                        if (sp) {
                          principalDetails["Name"] = sp.displayName;
                          principalDetails["Type"] = "Service Principal";
                          principalDetailsCache[principalId] = principalDetails; } ; __then(); }); }); } ; })(__then); }); }); } ; })(_); }); }); });};






function getResourceDetails(scope) {
  var resourceDetails = { };

  var scopeParts = scope.split("/").filter(function(r) {
    return !__.isEmpty(r); });


  var len = scopeParts.length;

  if ((((len > 0) && (len <= 2)) && (scope.toLowerCase().indexOf("subscriptions") > 0))) {
    resourceDetails["Type"] = "Subscription";
    resourceDetails["Name"] = scopeParts[1]; }
   else if ((((len > 0) && (len <= 4)) && (scope.toLowerCase().indexOf("resourcegroups") > 0))) {
    resourceDetails["Type"] = "Resource Group";
    resourceDetails["Name"] = scopeParts[3]; }
   else if (((len >= 6) && (scope.toLowerCase().indexOf("providers") > 0))) {
    resourceDetails["Type"] = "Resource";
    resourceDetails["Name"] = scopeParts[(len - 1)]; }   ;


  return resourceDetails;};
