public AlertFilterModel(AlertFilterViewModel viewModel) { this.Top = viewModel.Top.HasValue ? viewModel.Top.Value : 1; this.filters = new Dictionary <string, List <AlertFilterProperty> >(); if (viewModel.Filters != null && viewModel.Filters.Count > 0) { foreach (KeyValuePair <string, string> property in viewModel.Filters) { if (!string.IsNullOrWhiteSpace(property.Value)) { var isDropDownProperty = dropDownFitlerProperties.Exists(prop => prop.Equals(property.Key, StringComparison.InvariantCultureIgnoreCase)); if (!isDropDownProperty || (isDropDownProperty && !property.Value.Equals("All", StringComparison.InvariantCultureIgnoreCase))) { if (!propertyDescriptions.ContainsKey(property.Key.ToLower())) { throw new Exception($"PropertyDescriptions don't contain specified '{property.Key.ToLower()}' key."); } var propertyDescription = propertyDescriptions[property.Key.ToLower()]; if (!this.filters.ContainsKey(propertyDescription.PropertyName)) { this.filters.Add(propertyDescription.PropertyName, new List <AlertFilterProperty>()); } this.filters[propertyDescription.PropertyName].Add(new AlertFilterProperty(propertyDescription, property.Value)); } } } } }
public async Task <ActionResult> Subscribe(AlertFilterViewModel actViewAlertFilter) { try { var startDateTime = DateTime.Now; var token = string.Empty; if (Request.Headers.ContainsKey("Authorization")) { token = Request.Headers["Authorization"].ToString()?.Split(" ")?[1]; } _graphService = _graphServiceProvider.GetService(token); if (actViewAlertFilter != null && actViewAlertFilter.Filters.GetFilterValue("alert:category").Equals("Any") && actViewAlertFilter.Filters.GetFilterValue("vendor:provider").Equals("Any") && actViewAlertFilter.Filters.GetFilterValue("alert:severity").Equals("Any")) { return(BadRequest("Please select at least one property/criterion for subscribing to alert notifications")); } else { var filter = new AlertFilterModel(actViewAlertFilter); var createSubscriptionResult = await _graphService.SubscribeAsync(filter); var subscription = createSubscriptionResult.Item1; Debug.WriteLine($"SubscriptionController Subscribe execution time: {DateTime.Now - startDateTime}"); return(Ok(subscription)); } } catch (Exception exception) { return(BadRequest(exception.Message)); } }
public AlertFilterModel(AlertFilterViewModel viewModel) { if (viewModel != null) { this.Top = viewModel.Top ?? 1; this.filters = new Dictionary <string, List <AlertFilterProperty> >(); if (viewModel.Filters != null && viewModel.Filters.Count > 0) { foreach (KeyValuePair <string, IEnumerable <string> > property in viewModel.Filters) { var isDropDownProperty = dropDownFitlerProperties.Exists(prop => prop.Equals(property.Key, StringComparison.InvariantCultureIgnoreCase)); if (!isDropDownProperty) { if (!propertyDescriptions.ContainsKey(property.Key.ToLower())) { throw new Exception($"PropertyDescriptions don't contain specified '{property.Key.ToLower()}' key."); } var propertyDescription = propertyDescriptions[property.Key.ToLower()]; if (!this.filters.ContainsKey(propertyDescription.PropertyName)) { this.filters.Add(propertyDescription.PropertyName, new List <AlertFilterProperty>()); } this.filters[propertyDescription.PropertyName].Add(new AlertFilterProperty(propertyDescription, property.Value.FirstOrDefault())); } else { if (!propertyDescriptions.ContainsKey(property.Key.ToLower())) { throw new Exception($"PropertyDescriptions don't contain specified '{property.Key.ToLower()}' key."); } var propertyDescription = propertyDescriptions[property.Key.ToLower()]; if (!this.filters.ContainsKey(propertyDescription.PropertyName)) { this.filters.Add(propertyDescription.PropertyName, new List <AlertFilterProperty>()); } foreach (var val in property.Value) { this.filters[propertyDescription.PropertyName].Add(new AlertFilterProperty(propertyDescription, val)); } } } } } }
public Task BindModelAsync(ModelBindingContext bindingContext) { try { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } MemoryStream ms = new MemoryStream(); bindingContext.HttpContext.Request.Body.CopyTo(ms); ms.Position = 0; var streamReader = new StreamReader(ms); var json = streamReader.ReadToEnd(); JObject jsonObj = JObject.Parse(json); AlertFilterViewModel alertFilterViewModel = new AlertFilterViewModel(); foreach (var obj in jsonObj) { if (obj.Key.Equals("Top")) { alertFilterViewModel.Top = obj.Value.Value <int>(); } if (obj.Key.Equals("Filters")) { //var d = obj.Value.ToObject<Dictionary<string, IEnumerable<string>>>(); alertFilterViewModel.Filters = new AlertFilterCollection(obj.Value.ToObject <Dictionary <string, IEnumerable <string> > >()); } } bindingContext.Result = ModelBindingResult.Success(alertFilterViewModel); return(Task.CompletedTask); } catch { bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); } }
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)); } }