public async Task <IActionResult> GetUser(string id) { Models.User objUser = new Models.User(); try { if (string.IsNullOrEmpty(id) || string.IsNullOrWhiteSpace(id)) { return(BadRequest()); } // Initialize the GraphServiceClient. GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient(); // Load user profile. var user = await client.Users[id].Request().GetAsync(); // Copy Microsoft-Graph User to DTO User objUser = CopyHandler.UserProperty(user); return(Ok(objUser)); } catch (ServiceException ex) { if (ex.StatusCode == HttpStatusCode.BadRequest) { return(BadRequest()); } else { return(NotFound()); } } }
public async Task <IActionResult> GetUsers() { Users users = new Users(); try { users.Resources = new List <Models.User>(); // Initialize the GraphServiceClient. GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient(); // Load users profiles. var userList = await client.Users.Request().GetAsync(); // Copy Microsoft User to DTO User foreach (var user in userList) { var objUser = CopyHandler.UserProperty(user); users.Resources.Add(objUser); } return(Ok(users)); } catch (ServiceException ex) { if (ex.StatusCode == HttpStatusCode.BadRequest) { return(BadRequest()); } else { return(NotFound()); } } }
// Get ApplicationId of Service Principal if user doesn't provide this parameter private Guid GetApplicationId(Guid applicationId) { if (applicationId != Guid.Empty) { return(applicationId); } MicrosoftGraphClient graphClient = AzureSession.Instance.ClientFactory.CreateArmClient <MicrosoftGraphClient>( DefaultProfile.DefaultContext, AzureEnvironment.ExtendedEndpoint.MicrosoftGraphUrl); graphClient.TenantID = DefaultProfile.DefaultContext.Tenant.Id.ToString(); MicrosoftGraphServicePrincipal sp = null; try { sp = graphClient.ServicePrincipals.GetServicePrincipal(ObjectId.ToString()); } catch (Exception e) { string errorMessage = $"Can not find service princaipl per the parameter ObjectId:{ObjectId}, the error message is '{e.Message}'." + " Please specify Application Id explicitly by providing ApplicationId parameter and retry."; throw new AzPSArgumentException(errorMessage, nameof(ObjectId)); } var spApplicationId = Guid.Empty; Guid.TryParse(sp.AppId, out spApplicationId); Debug.Assert(spApplicationId != Guid.Empty); return(spApplicationId); }
public async Task <IActionResult> SearchUsersAndTeams([FromQuery] string keyword) { List <SearchModel> result = new List <SearchModel>(); try { if (String.IsNullOrEmpty(keyword) || keyword == "undefined") { return(Ok(result)); } // Initialize the GraphServiceClient. GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient(); // Load users profiles. var userList = await client.Users.Request().Filter($"startswith(DisplayName,'{keyword}') " + $"or startswith(UserPrincipalName,'{keyword}') " + $"or startswith(GivenName,'{keyword}')").Top(5).GetAsync(); // Copy Microsoft User to Search Model foreach (var user in userList) { if (!_currentUserService.UserId.Equals(user.Id)) { var objUser = new SearchModel { Id = new Guid(user.Id), Name = user.DisplayName, isTeam = false }; result.Add(objUser); } } // Copy Team to Search Model IEnumerable <TeamModel> teams = await Mediator.Send(new GetTeamsQuery { TeamName = keyword }); foreach (var team in teams) { var objTeam = new SearchModel { Id = team.Id, Name = team.Name, isTeam = true }; result.Add(objTeam); } result = result.OrderBy(x => x.Name).ToList(); return(Ok(result)); } catch (ServiceException ex) { if (ex.StatusCode == HttpStatusCode.BadRequest) { return(BadRequest()); } else { return(NotFound()); } } }
public async Task <ActionResult <IEnumerable <GroupDto> > > GetGroups(Guid userId) { var userExists = await _userRepository.UserExists(userId); if (!userExists) { return(NotFound()); } var allGroupsFromRepo = await _groupRepository.GetGroups(); var client = await MicrosoftGraphClient.GetGraphServiceClient(); var userGroupsIdsFromAzureAd = await _azureAdRepository .GetUserGroupsIds(client, userId.ToString()); var userGroupsFromAzureAd = new List <Group>(); foreach (var groupId in userGroupsIdsFromAzureAd) { var group = await _azureAdRepository .GetGroup(groupId.ToString()); userGroupsFromAzureAd.Add(group); } var mergedGroups = DataMerger.MergeGroupsWithAzureData(allGroupsFromRepo, userGroupsFromAzureAd, _mapper); return(Ok(mergedGroups)); }
public async Task <ActionResult <List <String> > > GetUserGroups(string userId) { try { if (string.IsNullOrEmpty(userId) || string.IsNullOrWhiteSpace(userId)) { return(BadRequest()); } // Initialize the GraphServiceClient. var client = await MicrosoftGraphClient.GetGraphServiceClient(); // Load user profile. var userGroups = await _azureAdRepository.GetUserGroupsIds(client, userId); return(Ok(userGroups)); } catch (ServiceException ex) { if (ex.StatusCode == HttpStatusCode.BadRequest) { return(BadRequest()); } else { return(NotFound()); } } }
public async Task <ActionResult <string> > GetUserPhoto(string userId) { try { // Initialize the GraphServiceClient. var client = await MicrosoftGraphClient.GetGraphServiceClient(); var pictureStream = await _azureAdRepository.GetUserPhoto(client, userId); var pictureBase64 = PhotoBase64Converter.StreamToBase64ImageString(pictureStream); return(Ok(pictureBase64)); } catch (ServiceException ex) { if (ex.StatusCode == HttpStatusCode.BadRequest) { return(BadRequest()); } else { return(NotFound()); } } }
// GET api/values/5 public async Task <string> Get(string filter) { try { GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient2(); //var resultaat = await client.Users["db4fef52-9274-49e2-846c-1f325c4b9d7c"].Drive.Root.Children.Request().GetAsync(); var resultaat = await client.Users["db4fef52-9274-49e2-846c-1f325c4b9d7c"].Request().GetAsync(); //var resultaat = await client.Request("https://graph.microsoft.com/v1.0/me/").GetAsync(); Debug.WriteLine(resultaat.ToString()); return(resultaat.ToString()); } catch (MsalUiRequiredException) { return("request fout"); // The application does not have sufficient permissions // - did you declare enough app permissions in during the app creation? // - did the tenant admin needs to grant permissions to the application. } catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011")) { return("request fout"); // Invalid scope. The scope has to be of the form "https://resourceurl/.default" // Mitigation: change the scope to be as expected ! } }
public async Task <IActionResult> UpdateUser([FromRoute] string id, [FromBody] UserDto userRequest) { try { if (string.IsNullOrEmpty(id) || string.IsNullOrWhiteSpace(id)) { return(BadRequest()); } // Initialize the GraphServiceClient. GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient(); var user = new Microsoft.Graph.User { DisplayName = userRequest.DisplayName, GivenName = userRequest.GivenName, Surname = userRequest.Surname, }; await client.Users[id].Request().UpdateAsync(user); return(NoContent()); } catch (ServiceException ex) { if (ex.StatusCode == HttpStatusCode.BadRequest) { return(BadRequest()); } else { return(NotFound()); } } }
public async Task <IActionResult> GetGroup(string id) { Models.Group objGroup = new Models.Group(); try { // Initialize the GraphServiceClient. GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient(); // Load group profile. var group = await client.Groups[id].Request().GetAsync(); // Copy Microsoft-Graph Group to DTO Group objGroup = CopyHandler.GroupProperty(group); return(Ok(objGroup)); } catch (ServiceException ex) { if (ex.StatusCode == HttpStatusCode.BadRequest) { return(BadRequest()); } else { return(NotFound()); } } }
public async Task <IGraphServiceGroupsCollectionPage> GetGroups() { var client = await MicrosoftGraphClient.GetGraphServiceClient(); var groupList = await client.Groups.Request() .Filter("securityEnabled eq true") .GetAsync(); return(groupList); }
/// <summary> /// Setups the management clients. /// </summary> /// <param name="context">The context.</param> private void SetupManagementClients(MockContext context) { var rmClient = context.GetServiceClient <ResourceManagementClient>(TestEnvironmentFactory.GetTestEnvironment()); var subClient = context.GetServiceClient <SubscriptionClient>(TestEnvironmentFactory.GetTestEnvironment()); var storageSyncClient = context.GetServiceClient <StorageSyncManagementClient>(TestEnvironmentFactory.GetTestEnvironment()); var storageClient = context.GetServiceClient <StorageManagementClient>(TestEnvironmentFactory.GetTestEnvironment()); MicrosoftGraphClient microsoftGraphClient = GetGraphClient(context); var authClient = context.GetServiceClient <AuthorizationManagementClient>(TestEnvironmentFactory.GetTestEnvironment()); _helper.SetupManagementClients(rmClient, subClient, storageSyncClient, storageClient, microsoftGraphClient, authClient); }
public async Task GetUserPhoto_UserGroupIdsIsNull_ThrowsArgumentNullException() { // Arrange var azureRepository = new AzureAdRepository(); var client = await MicrosoftGraphClient.GetGraphServiceClient(); // Act await Assert.ThrowsExceptionAsync <ArgumentNullException>( // Act () => azureRepository.GetUserGroupsIds(client, null)); }
public TestPnPContextFactory( ILogger <PnPContext> logger, SharePointRestClient sharePointRestClient, MicrosoftGraphClient microsoftGraphClient, IOptions <PnPContextFactoryOptions> contextOptions, IOptions <PnPGlobalSettingsOptions> globalOptions) : base(logger, sharePointRestClient, microsoftGraphClient, contextOptions, globalOptions) { if (TelemetryManager != null && !TestCommon.RunningInGitHubWorkflow()) { // Send telemetry to the test Azure AppInsights instance TelemetryManager.TelemetryClient.InstrumentationKey = "6073339d-9e70-4004-9ff7-1345316ade97"; } }
/// <summary> /// Ensures the service principal. /// </summary> /// <returns>PSADServicePrincipal.</returns> public MicrosoftGraphServicePrincipal GetServicePrincipalOrNull() { string applicationId = CurrentApplicationId.ToString(); // TODO: Remove this call once Az Powershell supports MSGraphClient in Test framework. MicrosoftGraphServicePrincipal servicePrincipal = this.StorageSyncResourceManager.GetServicePrincipalOrNull(); if (servicePrincipal == null) { var oDataQuery = new ODataQuery <MicrosoftGraphServicePrincipal>(sp => sp.AppId == applicationId); servicePrincipal = MicrosoftGraphClient.FilterServicePrincipals(oDataQuery).FirstOrDefault(); } return(servicePrincipal); }
public async Task <ActionResult <IEnumerable <UserDto> > > GetUsers() { var allUsersFromRepo = await _userRepository.GetUsers(); var client = await MicrosoftGraphClient.GetGraphServiceClient(); var allUsersFromAzureAd = await _azureAdRepository.GetUsers(client); var mergedUsers = DataMerger.MergeUsersWithAzureData(allUsersFromRepo, allUsersFromAzureAd, _mapper); return(Ok(mergedUsers)); }
public async Task <ActionResult <UserDto> > CreateUser([FromBody] UserCreationDto userToAdd) { var client = await MicrosoftGraphClient.GetGraphServiceClient(); try { await _azureAdRepository.GetUser(client, userToAdd.Id.ToString()); } catch (ServiceException e) { if (e.StatusCode == HttpStatusCode.NotFound) { ModelState.AddModelError("azureAdUserNotFound", $"User with id: {userToAdd.Id} was not found on Azure AD"); } } var userExists = await _userRepository.UserExists(userToAdd.Id); if (userExists) { return(Conflict("User already exists")); } if (userToAdd.SmartLockUsers.Count > 0) { foreach (var smartLockUser in userToAdd.SmartLockUsers) { var smartLockExist = await _smartLockRepository.SmartLockExists(smartLockUser.SmartLockId); if (!smartLockExist) { ModelState.AddModelError("smartLockNotExist", $"Smart lock with id: {smartLockUser.SmartLockId} doesn't exist"); } } } if (!ModelState.IsValid) { return(ValidationProblem(ModelState)); } var userEntity = _mapper.Map <User>(userToAdd); _userRepository.AddUser(userEntity); await _userRepository.Save(); var userDto = _mapper.Map <UserDto>(userEntity); return(CreatedAtAction("GetUser", new { userId = userDto.Id }, userDto)); }
public async Task <Group> GetGroup(string groupId) { if (groupId == null) { throw new ArgumentNullException(nameof(groupId)); } var client = await MicrosoftGraphClient.GetGraphServiceClient(); var group = await client.Groups[groupId].Request().GetAsync(); return(group); }
public SynapseAnalyticsRoleClient(string workspaceName, IAzureContext context) { if (context == null) { throw new AzPSInvalidOperationException(Resources.InvalidDefaultSubscription); } string suffix = context.Environment.GetEndpoint(AzureEnvironment.ExtendedEndpoint.AzureSynapseAnalyticsEndpointSuffix); Uri uri = new Uri("https://" + workspaceName + "." + suffix); _roleAssignmentsClient = new RoleAssignmentsClient(uri, new AzureSessionCredential(context)); _roleDefinitionsClient = new RoleDefinitionsClient(uri, new AzureSessionCredential(context)); _graphClient = AzureSession.Instance.ClientFactory.CreateArmClient <MicrosoftGraphClient>(context, AzureEnvironment.ExtendedEndpoint.MicrosoftGraphUrl); _graphClient.TenantID = context.Tenant.Id.ToString(); }
/// <summary> /// Initializes a new instance of the <see cref="StorageSyncClientWrapper" /> class. /// </summary> /// <param name="context">The context.</param> /// <param name="activeDirectoryClient">The active directory client.</param> public StorageSyncClientWrapper(IAzureContext context, MicrosoftGraphClient microsoftGraphClient) : this(AzureSession.Instance.ClientFactory.CreateArmClient <StorageSyncManagementClient>(context, AzureEnvironment.Endpoint.ResourceManager), AzureSession.Instance.ClientFactory.CreateArmClient <AuthorizationManagementClient>(context, AzureEnvironment.Endpoint.ResourceManager), AzureSession.Instance.ClientFactory.CreateArmClient <ResourceManagementClient>(context, AzureEnvironment.Endpoint.ResourceManager)) { MicrosoftGraphClient = microsoftGraphClient; if (AzureSession.Instance.TryGetComponent(StorageSyncConstants.StorageSyncResourceManager, out IStorageSyncResourceManager storageSyncResourceManager)) { StorageSyncResourceManager = storageSyncResourceManager; } else { StorageSyncResourceManager = new StorageSyncResourceManager(); } }
public async Task <ActionResult <UserDto> > GetCurrentUserAccessLevel() { var userId = Guid.Parse(_identityService.GetId()); var client = await MicrosoftGraphClient.GetGraphServiceClient(); var userGroupsIdsFromAzureAd = await _azureAdRepository.GetUserGroupsIds(client, userId.ToString()); var authSettings = Startup.Configuration.GetSection("AzureAd").Get <AzureAdOptions>(); if (userGroupsIdsFromAzureAd.Contains(authSettings.AdminGroupId)) { return(Ok("admin")); } return(Ok("user")); }
public async Task <ActionResult <UserDto> > GetUser(Guid userId) { var userExists = await _userRepository.UserExists(userId); if (!userExists) { return(NotFound()); } var userFromRepo = await _userRepository.GetUser(userId); var client = await MicrosoftGraphClient.GetGraphServiceClient(); var userFromAzureAd = await _azureAdRepository.GetUser(client, userId.ToString()); var mergedUser = DataMerger.MergeUserWithAzureData(userFromRepo, userFromAzureAd, _mapper); return(Ok(mergedUser)); }
public async Task <ActionResult <IEnumerable <UserDto> > > GetSmartLockUsers(Guid smartLockId) { var smartLockExists = await _smartLockRepository.SmartLockExists(smartLockId); if (!smartLockExists) { return(NotFound()); } var allSmartLockUsersFromRepo = await _smartLockRepository.GetSmartLockUsers(smartLockId); var client = await MicrosoftGraphClient.GetGraphServiceClient(); var allUsersFromAzureAd = await _azureAdRepository.GetUsers(client); var mergedSmartLockUsers = DataMerger.MergeUsersWithAzureData( allSmartLockUsersFromRepo, allUsersFromAzureAd, _mapper); return(Ok(mergedSmartLockUsers)); }
public async Task <IActionResult> GetUsersNotInTeam(string teamId) { UsersDto users = new UsersDto(); try { users.Resources = new List <UserDto>(); // Initialize the GraphServiceClient. GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient(); // Load users profiles. var userList = await client.Users.Request().GetAsync(); TeamModel team = await Mediator.Send(new GetTeamQuery { TeamId = new Guid(teamId) }); // Copy Microsoft User to DTO User foreach (var user in userList) { if (!team.Users.Any(x => x.UserId.ToString().Equals(user.Id))) { var objUser = CopyHandler.UserProperty(user); users.Resources.Add(objUser); } } users.TotalResults = users.Resources.Count; return(Ok(users)); } catch (ServiceException ex) { if (ex.StatusCode == HttpStatusCode.BadRequest) { return(BadRequest()); } else { return(NotFound()); } } }
public async Task <ActionResult <IEnumerable <UserDto> > > GetGroupUsers(Guid groupId) { var groupExists = await _groupRepository.GroupExists(groupId); if (!groupExists) { return(NotFound()); } var allUsersFromRepo = await _userRepository.GetUsers(); var client = await MicrosoftGraphClient.GetGraphServiceClient(); var groupUsersFromAzureAd = await _azureAdRepository .GetGroupMembers(client, groupId.ToString()); var mergedUsers = DataMerger.MergeUsersWithAzureData(allUsersFromRepo, groupUsersFromAzureAd, _mapper); return(Ok(mergedUsers)); }
public async Task <ActionResult <UserAccessDto> > AccessSmartLock(SmartLockUserAccessDto smartLockUser) { var userExists = await _userRepository.UserExists(smartLockUser.UserId); if (!userExists) { return(NotFound()); } var smartLockExists = await _smartLockRepository.SmartLockExists(smartLockUser.SmartLockId); if (!smartLockExists) { return(NotFound()); } var client = await MicrosoftGraphClient.GetGraphServiceClient(); try { await _azureAdRepository.GetUser(client, smartLockUser.UserId.ToString()); } catch (ServiceException e) { if (e.StatusCode == HttpStatusCode.NotFound) { ModelState.AddModelError("azureAdUserNotFound", $"User with id: {smartLockUser.UserId} was not found on Azure AD"); } } if (!ModelState.IsValid) { return(ValidationProblem(ModelState)); } var userAccessStatus = await _accessService.GetUserAccessStatus(smartLockUser); return(Ok(userAccessStatus)); }
public async Task <ActionResult <AzureAdUserDto> > GetUser(string userId) { try { if (string.IsNullOrEmpty(userId) || string.IsNullOrWhiteSpace(userId)) { return(BadRequest()); } // Initialize the GraphServiceClient. var client = await MicrosoftGraphClient.GetGraphServiceClient(); // Load user profile. var user = await _azureAdRepository.GetUser(client, userId); var userDto = _mapper.Map <AzureAdUserDto>(user); var userExist = await _userRepository.UserExists(userDto.Id); if (userExist) { userDto.AddedToDb = true; } return(Ok(userDto)); } catch (ServiceException ex) { if (ex.StatusCode == HttpStatusCode.BadRequest) { return(BadRequest()); } else { return(NotFound()); } } }
public async Task <ActionResult <IEnumerable <AzureAdUserDto> > > GetUsers() { var users = new List <UserDto>(); try { // Initialize the GraphServiceClient. var client = await MicrosoftGraphClient.GetGraphServiceClient(); // Load users profiles. var userList = await _azureAdRepository.GetUsers(client); var userListDto = _mapper.Map <IEnumerable <AzureAdUserDto> >(userList); foreach (var azureAdUserDto in userListDto) { var userExist = await _userRepository.UserExists(azureAdUserDto.Id); if (userExist) { azureAdUserDto.AddedToDb = true; } } return(Ok(userListDto)); } catch (ServiceException ex) { if (ex.StatusCode == HttpStatusCode.BadRequest) { return(BadRequest()); } else { return(NotFound()); } } }
public async Task <ActionResult <IEnumerable <UserDto> > > AddSmartLockUser(Guid smartLockId, SmartLockUserCreationDto smartLockUser) { var client = await MicrosoftGraphClient.GetGraphServiceClient(); try { await _azureAdRepository.GetUser(client, smartLockUser.UserId.ToString()); } catch (ServiceException e) { if (e.StatusCode == HttpStatusCode.NotFound) { _logger.LogWarning("User was not found on Azure AD"); ModelState.AddModelError("azureAdUserNotFound", $"User with id: {smartLockUser.UserId} was not found on Azure AD"); } } if (!ModelState.IsValid) { return(ValidationProblem(ModelState)); } var userExists = await _smartLockRepository.SmartLockUserExists(smartLockId, smartLockUser.UserId); if (userExists) { _logger.LogWarning("User already exists for this smart lock"); return(Conflict("User already exists for this smart lock")); } _smartLockRepository.AddSmartLockUser(smartLockId, smartLockUser.UserId); await _smartLockRepository.Save(); return(CreatedAtAction("GetSmartLockUser", new { smartLockId = smartLockId, userId = smartLockUser.UserId }, smartLockUser)); }
public async Task <IActionResult> Get() { //return new string[] { "value1", "value2" }; Groups groups = new Groups(); try { groups.resources = new List <Models.Group>(); // Initialize the GraphServiceClient. GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient(); // Load groups profiles. var groupList = await client.Groups.Request().GetAsync(); // Copy Microsoft-Graph Group to DTO Group foreach (var group in groupList) { var objGroup = CopyHandler.GroupProperty(group); groups.resources.Add(objGroup); } groups.totalResults = groups.resources.Count; return(Ok(groups)); } catch (ServiceException ex) { if (ex.StatusCode == HttpStatusCode.BadRequest) { return(BadRequest()); } else { return(NotFound()); } } }