public async Task <int> InsertDevice(UserAccountDevice userAccountDevice) { var cmd = QueriesCreatingHelper.CreateQueryInsert(userAccountDevice); cmd += ";SELECT LAST_INSERT_ID();"; return((await DALHelper.ExecuteQuery <int>(cmd, dbTransaction: DbTransaction, connection: DbConnection)).First()); }
public List <AlertHistoryState> GetAlertHistoryStates(Alert alert, UserAccountDevice assignedTo, UserAccountDevice user) { try { if (alertHistoryStatesDictionary.ContainsKey(alert.Id)) { return(alertHistoryStatesDictionary[alert.Id]); } if (user == null || assignedTo == null) { return(new List <AlertHistoryState>()); } return(new List <AlertHistoryState>() { new AlertHistoryState() { AssignedTo = assignedTo, Feedback = alert.Feedback, Status = alert.Status, UpdatedDateTime = alert?.LastModifiedDateTime, User = user, Comments = alert?.Comments } }); } catch (Exception exception) { Trace.WriteLine(exception.Message); return(new List <AlertHistoryState>()); } }
public async Task <bool> Initialization(IGraphService graphService) { try { var categories = new List <string>(); var providers = new List <string>(); var alerts = await graphService.GetAlertsAsync(new AlertFilterModel(1000)); foreach (var alert in alerts?.Item1) { if (!string.IsNullOrWhiteSpace(alert.AssignedTo)) { if (GetUserAccountDevice(alert.AssignedTo) == null) { UserAccountDevice userAccountDevice = await graphService.GetUserDetailsAsync(alert.AssignedTo, true, true, true); SetUserAccountDevice(alert.AssignedTo, userAccountDevice); } } if (alert.UserStates != null) { foreach (var userState in alert.UserStates) { if (!string.IsNullOrWhiteSpace(userState.UserPrincipalName) && GetUserAccountDevice(userState.UserPrincipalName) == null) { UserAccountDevice userAccountDevice = await graphService.GetUserDetailsAsync(userState.UserPrincipalName, populatePicture : true, populateManager : true, populateDevices : true); if (!string.IsNullOrWhiteSpace(userAccountDevice.Manager.Upn)) { userAccountDevice.Manager = await graphService.GetUserDetailsAsync(userAccountDevice.Manager.Upn, populatePicture : false, populateManager : false, populateDevices : false); } if (!string.IsNullOrWhiteSpace(userState.DomainName)) { userAccountDevice.DomainName = userState.DomainName; } userAccountDevice.RiskScore = userState?.RiskScore; userAccountDevice.LogonId = userState?.LogonId; userAccountDevice.EmailRole = userState?.EmailRole.ToString(); if (userAccountDevice?.RegisteredDevices?.Count() == 0 && userAccountDevice?.OwnedDevices?.Count() == 0) { userAccountDevice.RegisteredDevices = _demoExample.GetDevices(); userAccountDevice.OwnedDevices = _demoExample.GetDevices(); } if (userAccountDevice != null) { SetUserAccountDevice(userState.UserPrincipalName, userAccountDevice); } } } } if (alert.VendorInformation != null && !string.IsNullOrWhiteSpace(alert.VendorInformation.Provider)) { providers.Add(alert.VendorInformation.Provider); } if (!string.IsNullOrWhiteSpace(alert.Category)) { categories.Add(alert.Category); } } if (categories.Count > 0) { SetFilter("Categories", categories.Distinct().ToList()); } if (providers.Count > 0) { SetFilter("Providers", providers.Distinct().ToList()); } return(true); } catch (Exception exception) { Trace.WriteLine(exception.Message); return(false); } }
public void SetUserAccountDevice(string userUpn, UserAccountDevice userAccountDevice) { _cache.Set(userUpn, userAccountDevice); }
/// <summary> /// Get additional details about the user to help in investigating the alert /// </summary> /// <param name="principalName">User principal name</param> /// <param name="populatePicture"></param> /// <param name="populateManager"></param> /// <param name="populateDevices"></param> /// <param name="populateRiskyUser"></param> /// <returns>Graph User Model</returns> public async Task <UserAccountDevice> GetUserDetailsAsync(string principalName, bool populatePicture = false, bool populateManager = false, bool populateDevices = false, bool populateRiskyUser = false) { try { List <Task> taskList = new List <Task>(); UserAccountDevice userModel = new UserAccountDevice(); Task <Stream> populatePictureTask = null; Task <IUserRegisteredDevicesCollectionWithReferencesPage> registeredDevicesTask = null; Task <IUserOwnedDevicesCollectionWithReferencesPage> ownedDevicesTask = null; Task <DirectoryObject> managerTask = null; Task <RiskyUser> riskyUserTask = null; _graphClient.BaseUrl = this.GraphBetaUrl; var userPageTask = _graphClient.Users.Request().Filter($"UserPrincipalName eq '{principalName}'").GetAsync(); taskList.Add(userPageTask); if (populatePicture) { populatePictureTask = _graphClient.Users[principalName].Photo.Content.Request().GetAsync(); taskList.Add(populatePictureTask); } if (populateManager) { managerTask = ManagerAsync(principalName, _graphClient); taskList.Add(managerTask); } if (populateDevices) { registeredDevicesTask = _graphClient.Users[principalName].RegisteredDevices.Request().GetAsync(); taskList.Add(registeredDevicesTask); ownedDevicesTask = _graphClient.Users[principalName].OwnedDevices.Request().GetAsync(); taskList.Add(ownedDevicesTask); } //if (populateRiskyUser) //{ // riskyUserTask = RiskyUserAsync(principalName); // taskList.Add(riskyUserTask); //} await Task.WhenAll(taskList); if (userPageTask.Result.Count > 0) { userModel = BuildGraphAccountDeviceModel(userPageTask.Result?[0], principalName); } if (populatePicture && populatePictureTask != null && populatePictureTask?.Result != null) { MemoryStream picture1 = (MemoryStream)populatePictureTask.Result; string pic = "data:image/png;base64," + Convert.ToBase64String(picture1.ToArray(), 0, picture1.ToArray().Length); userModel.Picture = pic; } if (populateManager && managerTask != null && managerTask.Result != null) { if (!string.IsNullOrEmpty(managerTask.Result?.Id)) { userModel.Manager = BuildGraphAccountDeviceModel(await _graphClient.Users[managerTask.Result?.Id].Request().GetAsync()); } } if (populateRiskyUser) { if (userPageTask.Result.Count > 0) { riskyUserTask = RiskyUserAsync(userPageTask.Result?[0].Id); userModel.RiskyUser = await riskyUserTask; } Debug.WriteLine(riskyUserTask.Result); } if (populateDevices && registeredDevicesTask != null && registeredDevicesTask.Result != null) { userModel.RegisteredDevices = await Task.WhenAll(registeredDevicesTask.Result.Select(dev => GetDeviceDetailsAsync(dev.Id))); } if (populateDevices && ownedDevicesTask != null && ownedDevicesTask.Result != null) { userModel.OwnedDevices = await Task.WhenAll(ownedDevicesTask.Result.Select(dev => GetDeviceDetailsAsync(dev.Id))); } _graphClient.BaseUrl = this.GraphUrl; return(userModel); } catch (Exception exception) { Trace.WriteLine(exception.Message); return(null); } }
public static AlertHistoryState ToAlertHistoryState(this AlertUpdateRequest alertUpdateRequest, UserAccountDevice assignedTo, UserAccountDevice user) { if (!Enum.TryParse <AlertStatus>(alertUpdateRequest.Status, true, out var status)) { throw new ArgumentOutOfRangeException(nameof(alertUpdateRequest.Status)); } if (!Enum.TryParse <AlertFeedback>(alertUpdateRequest.Feedback, true, out var feedback)) { throw new ArgumentOutOfRangeException(nameof(alertUpdateRequest.Feedback)); } return(new AlertHistoryState() { Status = status, Feedback = feedback, Comments = alertUpdateRequest.Comments, AssignedTo = assignedTo, User = user, }); }
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)); } }
// Microsoft.Graph.Device private async Task AddAdditionalInformationAboutAlert(Alert alert, AlertDetailsViewModel alertModel) { try { var startAdd = DateTime.Now; if (!string.IsNullOrWhiteSpace(alert.AssignedTo)) { UserAccountDevice assignedTo = _memoryCacheHelper.GetUserAccountDevice(alert.AssignedTo); if (assignedTo == null) { assignedTo = await _graphService.GetUserDetailsAsync(alert.AssignedTo, populatePicture: true, populateManager : true, populateDevices : true); alertModel.AssignedTo = assignedTo; _memoryCacheHelper.SetUserAccountDevice(alert.AssignedTo, assignedTo); } alertModel.AssignedTo = assignedTo; } List <UserAccountDevice> userAccountDevices = new List <UserAccountDevice>(); foreach (var userState in alert?.UserStates) { // Get info about user var principalName = userState.UserPrincipalName; if (!string.IsNullOrWhiteSpace(principalName)) { UserAccountDevice userAccountDevice = _memoryCacheHelper.GetUserAccountDevice(principalName); if (userAccountDevice == null) { userAccountDevice = await _graphService.GetUserDetailsAsync(principalName, populatePicture : true, populateManager : true, populateDevices : true, populateRiskyUser : true); if (!string.IsNullOrWhiteSpace(userAccountDevice.Manager.Upn)) { userAccountDevice.Manager = await _graphService.GetUserDetailsAsync(userAccountDevice.Manager.Upn, populatePicture : false, populateManager : false, populateDevices : false); } if (!string.IsNullOrWhiteSpace(userState.DomainName)) { userAccountDevice.DomainName = userState.DomainName; } userAccountDevice.RiskScore = userState?.RiskScore; userAccountDevice.LogonId = userState?.LogonId; userAccountDevice.EmailRole = userState?.EmailRole.ToString(); if (userAccountDevice?.RegisteredDevices?.Count() == 0 && userAccountDevice?.OwnedDevices?.Count() == 0) { userAccountDevice.RegisteredDevices = _demoExample.GetDevices(); userAccountDevice.OwnedDevices = _demoExample.GetDevices(); } _memoryCacheHelper.SetUserAccountDevice(principalName, userAccountDevice); } if (userAccountDevice != null) { userAccountDevices.Add(userAccountDevice); } } } alertModel.UserAccountDevices = userAccountDevices; Debug.WriteLine($"Executing time AddAdditionalInformationAboutAlert: {DateTime.Now - startAdd}"); } catch (Exception exception) { Trace.WriteLine(exception.Message); } }