Beispiel #1
0
        private void UpdateDevices(AlertsResponse alertsResponse, IEnumerable <string> deviceIds)
        {
            Dictionary <string, Device> devices = new Dictionary <string, Device>();

            foreach (var id in deviceIds)
            {
                devices.Add(id, new Device()
                {
                    Id = id, Alerts = new ItemsDictionary <Alert>()
                });
            }

            if (alertsResponse != null && alertsResponse.IsSuccessful && alertsResponse.Body.Alerts != null)
            {
                foreach (var alert in alertsResponse.Body.Alerts.Values)
                {
                    string deviceId = alert.DeviceId;
                    if (deviceId != null && devices.ContainsKey(deviceId))
                    {
                        devices[deviceId].Alerts.Add(alert.Id, alert);
                    }
                }

                foreach (var device in devices.Values)
                {
                    DataCache.AddOrUpdate(device);
                }
            }
        }
Beispiel #2
0
 /// <summary>
 /// Given a standard AlertsResponse, loops through all alerts in it and merges them  into the appropriate
 /// cached devices.
 /// </summary>
 /// <param name="response">Standard AlertsResponse from server.</param>
 public static void HandleAlertsResponse(AlertsResponse response)
 {
     ExceptionUtility.Try(() =>
     {
         LogUtility.LogMessage("Caching alerts response in app DB");
         if (response != null && response.IsSuccessful && response.Body.Alerts != null)
         {
             DataCache.CacheAlerts(response.Body.Alerts.Values);
         }
     });
 }
        public static IEnumerable <Alert> MapAlertsResponse(AlertsResponse data)
        {
            List <Alert> alerts = new List <Alert>();

            foreach (var a in data.alertsNoRead)
            {
                alerts.Add(MapAlert(a, false));
            }
            foreach (var a in data.alertsRead)
            {
                alerts.Add(MapAlert(a, true));
            }
            return(alerts);
        }
        public async Task <ActionResult> GetAlertsByFilter([FromQuery] string key, [FromQuery] string value)
        {
            try
            {
                var token = string.Empty;

                if (Request.Headers.ContainsKey("Authorization"))
                {
                    token = Request.Headers["Authorization"].ToString()?.Split(" ")?[1];
                }

                _graphService = _graphServiceProvider.GetService(token);

                if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(value))
                {
                    return(BadRequest(new ArgumentNullException(value, "value and key can't be null")));
                }

                var viewAlertFilter = new AlertFilterViewModel {
                    Top = 50, Filters = new AlertFilterCollection()
                };
                viewAlertFilter.Filters.Add(key, (new List <string>()
                {
                    value
                }));

                var orderByOarams = new Dictionary <string, string>();

                switch (key)
                {
                case "alert:severity":
                    {
                        orderByOarams.Add("createdDateTime", "desc");
                    }
                    break;

                default:
                    {
                        orderByOarams.Add("severity", "desc");
                        orderByOarams.Add("createdDateTime", "desc");
                    }
                    break;
                }

                var filter = new AlertFilterModel(viewAlertFilter);
                var securityAlertsResult = await _graphService.GetAlertsAsync(filter, orderByOarams);

                var filterQuery = securityAlertsResult?.Item2 ?? string.Empty;

                // Generate queries
                var sdkQueryBuilder  = new StringBuilder();
                var restQueryBuilder = new StringBuilder();
                sdkQueryBuilder.Append("await graphClient.Security.Alerts.Request()");
                if (!string.IsNullOrEmpty(filterQuery))
                {
                    sdkQueryBuilder.Append($".Filter(\"{filterQuery}\")");
                }

                sdkQueryBuilder.Append($".Top({filter.Top}).GetAsync()");

                if (!string.IsNullOrEmpty(filterQuery))
                {
                    restQueryBuilder.Append(
                        $"<a href=\"https://developer.microsoft.com/en-us/graph/graph-explorer?request=security/alerts?$filter={HttpUtility.UrlEncode(filterQuery)}%26$top={filter.Top}&&method=GET&version={_graphService.GraphUrlVersion}&GraphUrl=https://graph.microsoft.com\" target=\"_blank\">https://graph.microsoft.com/{_graphService.GraphUrlVersion}/security/alerts?");

                    restQueryBuilder.Append($"$filter={HttpUtility.UrlEncode(filterQuery)}&");
                    restQueryBuilder.Append($"$top={filter.Top}</a>");
                }
                else
                {
                    restQueryBuilder.Append(
                        $"<a href=\"https://developer.microsoft.com/en-us/graph/graph-explorer?request=security/alerts?$top={filter.Top}&&method=GET&version={_graphService.GraphUrlVersion}&GraphUrl=https://graph.microsoft.com\" target=\"_blank\">https://graph.microsoft.com/{_graphService.GraphUrlVersion}/security/alerts?");
                    restQueryBuilder.Append($"$top={filter.Top}</a>");
                }

                var alerts = securityAlertsResult?.Item1?.Select(sa => new AlertResultItemModel
                {
                    Id              = sa.Id,
                    Title           = sa.Title,
                    Status          = sa.Status,
                    Provider        = sa.VendorInformation?.Provider,
                    CreatedDateTime = sa.CreatedDateTime,
                    Severity        = sa.Severity.ToString(),
                    Category        = sa.Category
                }) ?? Enumerable.Empty <AlertResultItemModel>();

                // Save queries to session
                var queries = new ResultQueriesViewModel(sdkQueryBuilder.ToString(), restQueryBuilder.ToString());

                var alertsResponse = new AlertsResponse(alerts, queries);

                return(Ok(alertsResponse));
            }
            catch (Exception exception)
            {
                return(BadRequest(exception.Message));
            }
        }
        public async Task <ActionResult> GetAlerts([FromBody] AlertFilterViewModel viewAlertFilter)
        {
            try
            {
                var startGetAlerts = DateTime.Now;
                var token          = string.Empty;

                if (Request.Headers.ContainsKey("Authorization"))
                {
                    token = Request.Headers["Authorization"].ToString()?.Split(" ")?[1];
                }

                _graphService = _graphServiceProvider.GetService(token);

                AlertFilterModel filter = new AlertFilterModel(viewAlertFilter);

                var startGetAlertsfromGraph = DateTime.Now;

                var securityAlertsResult = await _graphService.GetAlertsAsync(filter);

                var filterQuery = securityAlertsResult?.Item2 ?? string.Empty;

                Debug.WriteLine($"Get Alerts from Graph: {DateTime.Now - startGetAlertsfromGraph}");

                // Generate queries
                var sdkQueryBuilder  = new StringBuilder();
                var restQueryBuilder = new StringBuilder();
                sdkQueryBuilder.Append("await graphClient.Security.Alerts.Request()");
                if (!string.IsNullOrEmpty(filterQuery))
                {
                    sdkQueryBuilder.Append($".Filter(\"{filterQuery}\")");
                }
                sdkQueryBuilder.Append($".Top({viewAlertFilter.Top}).GetAsync()");

                if (!string.IsNullOrEmpty(filterQuery))
                {
                    restQueryBuilder.Append($"<a href=\"https://developer.microsoft.com/en-us/graph/graph-explorer?request=security/alerts?$filter={HttpUtility.UrlEncode(filterQuery)}%26$top={viewAlertFilter.Top}&&method=GET&version={_graphService.GraphUrlVersion}&GraphUrl=https://graph.microsoft.com\" target=\"_blank\">https://graph.microsoft.com/{_graphService.GraphUrlVersion}/security/alerts?");

                    restQueryBuilder.Append($"$filter={HttpUtility.UrlEncode(filterQuery)}&");
                    restQueryBuilder.Append($"$top={viewAlertFilter.Top}</a>");
                }
                else
                {
                    restQueryBuilder.Append($"<a href=\"https://developer.microsoft.com/en-us/graph/graph-explorer?request=security/alerts?$top={viewAlertFilter.Top}&&method=GET&version={_graphService.GraphUrlVersion}&GraphUrl=https://graph.microsoft.com\" target=\"_blank\">https://graph.microsoft.com/{_graphService.GraphUrlVersion}/security/alerts?");
                    restQueryBuilder.Append($"$top={viewAlertFilter.Top}</a>");
                }

                ResultQueriesViewModel resultQueriesViewModel = new ResultQueriesViewModel(sdkQueryBuilder.ToString(), restQueryBuilder.ToString());

                var alertSearchResult = securityAlertsResult?.Item1?.Select(sa => new AlertResultItemModel
                {
                    Id              = sa.Id,
                    Title           = sa.Title,
                    Status          = sa.Status,
                    Provider        = sa.VendorInformation?.Provider,
                    CreatedDateTime = sa.CreatedDateTime,
                    AssignedTo      = sa.AssignedTo,
                    Severity        = sa.Severity.ToString(),
                    Category        = sa.Category
                }) ?? Enumerable.Empty <AlertResultItemModel>();

                var alertsResponse = new AlertsResponse(alertSearchResult, resultQueriesViewModel);

                Debug.WriteLine($"Executionf time AlertController GetAlerts: {DateTime.Now - startGetAlerts}");
                return(Ok(alertsResponse));
            }
            catch (Exception exception)
            {
                return(BadRequest(exception.Message));
            }
        }