public async Task <ActionResult> GetAlertById(string id) { try { var start = DateTime.Now; var token = string.Empty; if (Request.Headers.ContainsKey("Authorization")) { token = Request.Headers["Authorization"].ToString()?.Split(" ")?[1]; } _graphService = _graphServiceProvider.GetService(token); var startAll = DateTime.Now; var alert = await _graphService.GetAlertDetailsAsync(id); Debug.WriteLine($"Executing time GetAlertDetailsFromGraph: {DateTime.Now - startAll}"); if (alert == null) { return(NotFound()); } var sdkQueryBuilder = new StringBuilder(); var restQueryBuilder = new StringBuilder(); sdkQueryBuilder.Append($"await graphClient.Security.Alerts[\"{id}\"].Request().GetAsync()"); restQueryBuilder.Append($"<a href=\"https://developer.microsoft.com/en-us/graph/graph-explorer?request=security/alerts/{id}&method=GET&version={_graphService.GraphUrlVersion}&GraphUrl=https://graph.microsoft.com\" target=\"_blank\">https://graph.microsoft.com/{_graphService.GraphUrlVersion}/security/alerts/{id}/</a>"); var alertModel = alert.ToAlertDetailsViewModel(); await AddAdditionalInformationAboutAlert(alert, alertModel); //Only for demo if (alertModel.HistoryStates == null || alertModel.HistoryStates?.Count() == 0) { alertModel.HistoryStates = _demoExample.GetAlertHistoryStates(alert, alertModel.AssignedTo, alertModel?.UserAccountDevices?.FirstOrDefault()); } ResultQueriesViewModel resultQueriesViewModel = new ResultQueriesViewModel(sdkQueryBuilder.ToString(), restQueryBuilder.ToString()); AlertDetailsResponse response = new AlertDetailsResponse(alertModel, resultQueriesViewModel); Debug.WriteLine($"Executing time AlertController GetAlertsById: {DateTime.Now - start}"); return(Ok(response)); } catch (Exception exception) { return(BadRequest(exception.Message)); } }
public async Task <ActionResult> GetSubscriptions() { 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); IGraphServiceSubscriptionsCollectionPage subscriptions = await _graphService.GetListSubscriptionsAsync(); var sdkQueryBuilder = new StringBuilder(); var restQueryBuilder = new StringBuilder(); sdkQueryBuilder.Append("graphClient.Subscriptions.Request().GetAsync()"); restQueryBuilder.Append($"<a href=\"https://developer.microsoft.com/en-us/graph/graph-explorer?request=subscriptions&&method=GET&version={_graphService.GraphUrlVersion}&GraphUrl=https://graph.microsoft.com\" target=\"_blank\">https://graph.microsoft.com/{_graphService.GraphUrlVersion}/subscriptions</a>"); var subscriptionResultModels = subscriptions?.ToList()?.Select(sa => new SubscriptionResultModel { Id = sa.Id, Resource = sa.Resource, ExpirationDateTime = sa.ExpirationDateTime, ClientState = sa.ClientState, NotificationUrl = sa.NotificationUrl }) ?? Enumerable.Empty <SubscriptionResultModel>(); // Save queries to session var resultQueries = new ResultQueriesViewModel(sdkQueryBuilder.ToString(), restQueryBuilder.ToString()); SubscriptionResponse subscriptionResponse = new SubscriptionResponse(subscriptionResultModels, resultQueries); Debug.WriteLine($"SubscriptionController GetSubscriptions execution time: {DateTime.Now - startDateTime}"); return(Ok(subscriptionResponse)); } catch (Exception exception) { return(BadRequest(exception.Message)); } }
public AlertsResponse(IEnumerable <AlertResultItemModel> alerts, ResultQueriesViewModel queries) { Alerts = alerts; Queries = queries; }
public AlertDetailsResponse(AlertDetailsViewModel alertDetails, ResultQueriesViewModel queries) { AlertDetails = alertDetails; Queries = queries; }
public async Task <ActionResult> UpdateAlert([FromBody] AlertUpdateRequest updateAlertModel, string id) { try { var start = DateTime.Now; var token = string.Empty; if (Request.Headers.ContainsKey("Authorization")) { token = Request.Headers["Authorization"].ToString()?.Split(" ")?[1]; } _graphService = _graphServiceProvider.GetService(token); var sdkQueryBuilder = new StringBuilder(); var restQueryBuilder = new StringBuilder(); sdkQueryBuilder.Append($"await graphClient.Security.Alerts[\"{id}\"].Request().UpdateAsync(updatedAlert)"); restQueryBuilder.Append($"PATCH <a>https://graph.microsoft.com/{_graphService.GraphUrlVersion}/security/alerts/{id}</a>"); var email = $"\"{await _graphService.GetMyEmailAddressAsync()}\""; if (!string.IsNullOrEmpty(updateAlertModel.AssignedTo)) { email = $" \"assignedTo\" = \"{updateAlertModel.AssignedTo}\" "; } if (!Enum.TryParse <AlertStatus>(updateAlertModel.Status, true, out var status)) { throw new ArgumentOutOfRangeException(nameof(updateAlertModel.Status)); } if (!Enum.TryParse <AlertFeedback>(updateAlertModel.Feedback, true, out var feedback)) { throw new ArgumentOutOfRangeException(nameof(updateAlertModel.Feedback)); } UserAccountDevice userUpn = _memoryCacheHelper.GetUserAccountDevice(updateAlertModel.UserUpn); if (userUpn == null) { userUpn = await _graphService.GetUserDetailsAsync(updateAlertModel.UserUpn, populatePicture : true, populateManager : true, populateDevices : true); _memoryCacheHelper.SetUserAccountDevice(updateAlertModel.UserUpn, userUpn); } UserAccountDevice assignedTo = _memoryCacheHelper.GetUserAccountDevice(updateAlertModel.AssignedTo); if (assignedTo == null) { assignedTo = await _graphService.GetUserDetailsAsync(updateAlertModel.AssignedTo, populatePicture : true, populateManager : true, populateDevices : true); _memoryCacheHelper.SetUserAccountDevice(updateAlertModel.AssignedTo, assignedTo); } _demoExample.AddAlertHistoryState(id, new AlertHistoryState() { Status = status, Feedback = feedback, Comments = new List <string>() { updateAlertModel.Comments.Last() }, AssignedTo = assignedTo, UpdatedDateTime = DateTimeOffset.UtcNow, User = userUpn }); restQueryBuilder.Append($" Request Body: {{ \"status\" = \"{updateAlertModel?.Status}\", {email} alert.Feedback = {updateAlertModel?.Feedback}; alert.Comments = {updateAlertModel?.Comments} "); var resultQueriesViewModel = new ResultQueriesViewModel(sdkQueryBuilder.ToString(), restQueryBuilder.ToString()); var alert = await _graphService.GetAlertDetailsAsync(id); if (alert == null) { return(NotFound()); } await _graphService.UpdateAlertAsync(alert, updateAlertModel); alert = await _graphService.GetAlertDetailsAsync(id); var alertModel = alert.ToAlertDetailsViewModel(); await AddAdditionalInformationAboutAlert(alert, alertModel); //Only for demo if (alertModel.HistoryStates == null || alertModel.HistoryStates?.Count() == 0) { alertModel.HistoryStates = _demoExample.GetAlertHistoryStates(alert, alertModel.AssignedTo, alertModel?.UserAccountDevices?.FirstOrDefault()); } AlertDetailsResponse response = new AlertDetailsResponse(alertModel, resultQueriesViewModel); Debug.WriteLine($"Executing time AlertController UpdateAlert: {DateTime.Now - start}"); return(Ok(response)); } catch (Exception exception) { return(BadRequest(exception.Message)); } }
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)); } }
public SecureScoreDetailsResponse(SecureScoreDetailsViewModel secureScoreDetails, ResultQueriesViewModel queries) { SecureScoreDetails = secureScoreDetails; Queries = queries; }
public SubscriptionResponse(IEnumerable <SubscriptionResultModel> subscriptions, ResultQueriesViewModel queries) { Subscriptions = subscriptions; Queries = queries; }
public AlertUpdatedResponse(AlertDetailsViewModel alert, ResultQueriesViewModel queries) { Alert = alert; Queries = queries; }
public async Task <ActionResult> GetSecureDetails() { var startDateTime = DateTime.Now; try { var token = string.Empty; if (Request.Headers.ContainsKey("Authorization")) { token = Request.Headers["Authorization"].ToString()?.Split(" ")?[1]; } _graphService = _graphServiceProvider.GetService(token); var secureScores = _memoryCacheHelper.GetSecureScores("?$top=200"); if (secureScores == null || secureScores?.ToList().Count() == 0) { //// Get top secure score secureScores = await _graphService.GetSecureScoresAsync("?$top=200"); _memoryCacheHelper.SetSecureScores("?$top=200", secureScores); } if (secureScores == null || secureScores?.ToList().Count == 0) { return(NotFound()); } var topSecureScore = secureScores.FirstOrDefault(); var controlProfiles = _memoryCacheHelper.GetSecureScoreControlProfiles(); if (controlProfiles == null || controlProfiles?.ToList().Count() == 0) { //// Get top secure score controlProfiles = await _graphService.GetSecureScoreControlProfilesAsync(); _memoryCacheHelper.SetSecureScoreControlProfiles(controlProfiles); } var restQueryBuilder = new StringBuilder(); restQueryBuilder.Append($"<a href=\"https://developer.microsoft.com/en-us/graph/graph-explorer?request=security/securescores?$top=1&&method=GET&version=beta&GraphUrl=https://graph.microsoft.com\" target=\"_blank\">https://graph.microsoft.com/beta/security/securescores?$top=1</a>"); var secureScoreDetails = new SecureScoreDetailsViewModel { TopSecureScore = new SecureScoreModel { CreatedDateTime = topSecureScore.CreatedDateTime, CurrentScore = topSecureScore.CurrentScore, MaxScore = topSecureScore.MaxScore, EnabledServices = topSecureScore.EnabledServices.Select(service => service.StartsWith("Has", StringComparison.CurrentCultureIgnoreCase) ? service.Substring(3) : service), LicensedUserCount = topSecureScore.LicensedUserCount ?? 0, ActiveUserCount = topSecureScore.ActiveUserCount ?? 0, Id = topSecureScore.Id, ControlScores = (topSecureScore.ControlScores?.Select(controlScore => new ControlScoreModel { ControlCategory = controlScore.ControlCategory, Score = controlScore.Score ?? 0, Name = controlScore.ControlName, Description = controlScore.Description, Count = controlScore.AdditionalData.ContainsKey("count") ? controlScore.AdditionalData["count"].ToString() : controlScore.AdditionalData.ContainsKey("on") ? controlScore.AdditionalData["on"].ToString() : "0", Total = controlScore.AdditionalData.ContainsKey("total") ? controlScore.AdditionalData["total"].ToString() : controlScore.AdditionalData.ContainsKey("IntuneOn") ? controlScore.AdditionalData["IntuneOn"].ToString() : "0", }) ?? Enumerable.Empty <ControlScoreModel>()) .GroupBy(controlScoreModel => controlScoreModel.ControlCategory) .Select(groupControlScore => new ControlScoreModel { ControlCategory = groupControlScore.Key.ToString(), Score = groupControlScore.Sum(x => x.Score), Description = groupControlScore.FirstOrDefault().Description, Name = groupControlScore.FirstOrDefault().Name, Count = groupControlScore.Count().ToString(), // it was in version 2 // Total = groupControlScore.Sum(x => x.Total.AsEnumerable().Any(ch => char.IsLetter(ch)) ? 0 : Convert.ToInt32(x.Total)).ToString(), // it was in version 2 // Count = groupControlScore.Sum(x=> x.Count.AsEnumerable().Any(ch => char.IsLetter(ch)) ? 0 : Convert.ToInt32(x.Count)).ToString(), }).ToList(), AverageComparativeScores = topSecureScore.AverageComparativeScores?.Select(score => { string Value = string.Empty; switch (score.Basis) { case "Industry": { if (score.AdditionalData.ContainsKey("industryName")) { Value = score.AdditionalData["industryName"].ToString(); } } break; case "SeatCategory": { if (score.AdditionalData.ContainsKey("SeatLowerLimit") && score.AdditionalData.ContainsKey("SeatUpperLimit")) { Value = $"{score.AdditionalData["SeatLowerLimit"]} - {score.AdditionalData["SeatUpperLimit"]}"; } } break; default: { Value = string.Join(", ", score.AdditionalData.Select(item => item.Value)); } break; } return(new AverageComparativeScoreModel { ComparedBy = score.Basis, // if null or negative AverageScore set 0.0 AverageScore = score.AverageScore.HasValue ? score.AverageScore.Value > 0 ? score.AverageScore.Value : 0.0 : 0.0, Value = Value }); }) ?? Enumerable.Empty <AverageComparativeScoreModel>() }, SecureScoreControlProfiles = controlProfiles?.Select(profile => profile) ?? Enumerable.Empty <SecureScoreControlProfileModel>() }; // Save queries to session var resultQueries = new ResultQueriesViewModel(null, restQueryBuilder.ToString()); var response = new SecureScoreDetailsResponse(secureScoreDetails, resultQueries); var responseString = JsonConvert.SerializeObject( response, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); Debug.WriteLine($"Secure Score Controller GetSecureDetails execution time: {DateTime.Now - startDateTime}"); return(new JsonStringResult(responseString)); } catch (Exception exception) { return(BadRequest(exception.Message)); } }