예제 #1
0
        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));
        }
예제 #2
0
        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());
                }
            }
        }
예제 #3
0
        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());
                }
            }
        }
예제 #4
0
        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());
                }
            }
        }
예제 #5
0
        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());
                }
            }
        }
예제 #6
0
        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 <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());
                }
            }
        }
예제 #9
0
        public async Task <IGraphServiceGroupsCollectionPage> GetGroups()
        {
            var client = await MicrosoftGraphClient.GetGraphServiceClient();

            var groupList = await client.Groups.Request()
                            .Filter("securityEnabled eq true")
                            .GetAsync();

            return(groupList);
        }
예제 #10
0
        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));
        }
예제 #11
0
        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));
        }
예제 #12
0
        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));
        }
예제 #13
0
        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);
        }
예제 #14
0
        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"));
        }
예제 #15
0
        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));
        }
예제 #17
0
        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));
        }
예제 #19
0
        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));
        }
예제 #23
0
        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());
                }
            }
        }
        public async Task <ActionResult <IEnumerable <AzureAdUserDto> > > GetGroupMembers(string groupId)
        {
            try
            {
                // Initialize the GraphServiceClient.
                var client = await MicrosoftGraphClient.GetGraphServiceClient();

                // Load group profile.
                var members = await _azureAdRepository.GetGroupMembers(client, groupId);

                return(Ok(_mapper.Map <IEnumerable <AzureAdUserDto> >(members)));
            }
            catch (ServiceException ex)
            {
                if (ex.StatusCode == HttpStatusCode.BadRequest)
                {
                    return(BadRequest());
                }
                else
                {
                    return(NotFound());
                }
            }
        }