Ejemplo n.º 1
0
        private async Task <ActionResult <IEnumerable <T> > > GetUsersGeneric <T>(UsersParameters parameters)
        {
            bool isValidMapping = _mappingService.ValidMappingExistsFor <T, ApplicationUser>(parameters.OrderBy);

            parameters.SetSortingMappingSourceTypeName(typeof(T).Name);

            if (!isValidMapping)
            {
                return(this.GetGenericProblem(HttpStatusCode.BadRequest,
                                              $"Sorting using '{parameters.OrderBy}' is not possible"));
            }

            parameters.SetSortingMappingDestinationTypeName(nameof(ApplicationUser));

            var result = await _identityService.GetUsersFromRole(parameters);


            if (!result.Success)
            {
                return(this.GetGenericProblem(result));
            }

            this.SetPaginationInfoHeader(result.Object);

            return(Ok(_mapper.Map <IEnumerable <T> >(result.Object)));
        }
        GetOwners([FromQuery] UsersParameters usersParameters)
        {
            var owners = await _carOwnerService.GetAllCarOwners(usersParameters);

            var resultMetadata = new
            {
                owners.TotalCount,
                owners.PageSize,
                owners.CurrentPage,
                owners.HasPrevious,
                owners.HasNext
            };

            _logger.LogInformation($"list users length is {owners.Count}");

            Response.Headers.Add(
                "X-Pagination",
                JsonConvert.SerializeObject(resultMetadata));

            Response.Headers.Add("Access-Control-Expose-Headers", "X-Pagination");



            var ownersResponces = new List <OwnerResponce>();

            owners.ForEach(o => ownersResponces
                           .Add(_customMapper.OwnerToOwnerResponse(o)));

            return(Ok(new Response <OwnerResponce[]>(ownersResponces.ToArray())));
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> GetUsersWithPage([FromQuery] UsersParameters usersParameters)
        {
            var actionResult = await _context.Users.Include(c => c.Role).Include(c => c.Group)
                               .Where(u =>
                                      (EF.Functions.Like(u.Id.ToString(), $"%{usersParameters.Text}%") ||
                                       EF.Functions.Like(u.UserName, $"%{usersParameters.Text}%") ||
                                       EF.Functions.Like(u.Name, $"%{usersParameters.Text}%") ||
                                       EF.Functions.Like(u.Surname, $"%{usersParameters.Text}%") ||
                                       EF.Functions.Like(u.Patronymic, $"%{usersParameters.Text}%") ||
                                       EF.Functions.Like(u.ReportCard, $"%{usersParameters.Text}%") ||
                                       EF.Functions.Like(u.Email, $"%{usersParameters.Text}%") ||
                                       EF.Functions.Like(u.Group.Name, $"%{usersParameters.Text}%")
                                      ) &&
                                      EF.Functions.Like(u.Role.Id.ToString(), $"%{usersParameters.Role}%") &&
                                      EF.Functions.Like(u.Group.Id.ToString(), $"%{usersParameters.Group}%")
                                      )
                               .ToListAsync();

            usersParameters.TotalCount = actionResult.Count;
            if (!usersParameters.Check())
            {
                return(NoContent());
            }
            Response.Headers.Add("X-Pagination", usersParameters.PaginationToJson());
            List <UserDTO> userDtos = new List <UserDTO>();

            actionResult = actionResult.Skip(usersParameters.Skip).Take(usersParameters.Take).ToList();
            foreach (var user in actionResult)
            {
                userDtos.Add(user.ToUserDto());
            }
            return(Ok(userDtos));
        }
Ejemplo n.º 4
0
        public async Task PostGetCarsByOwner()
        {
            //Arrange
            var client = _factory.CreateClient();

            var userParams = new UsersParameters()
            {
                PageSize = 1
            };

            var getOwnersUrl = ApiRoutes.Owners.GetAll;

            var propertyList = userParams.GetType().GetProperties();
            var queryString  = "?";

            foreach (var prop in propertyList)
            {
                queryString += $"{prop.Name}={prop.GetValue(userParams, null)}&";
            }
            queryString = queryString.Remove(queryString.Length - 1, 1);

            _output.WriteLine(queryString);
            var ownersUrlAndQuery = $"{getOwnersUrl}{queryString}";

            _output.WriteLine(ownersUrlAndQuery);

            var json = await client.GetStringAsync(ownersUrlAndQuery);

            Assert.NotNull(json);
            var ownerFromDbResponse = JsonConvert.DeserializeObject <Response <IEnumerable <OwnerResponce> > >(json);

            Assert.IsAssignableFrom <Response <IEnumerable <OwnerResponce> > >(ownerFromDbResponse);
            var owner = ownerFromDbResponse.Data.ToArray()[0];

            Assert.NotNull(owner);

            var jsonOwnerRequest = JsonConvert.SerializeObject(owner);

            var authSuccessLoginResponce = await GetLoginResponse();

            var url = ApiRoutes.Vehicles.GetCarsByOwner;

            var strContent = new StringContent(jsonOwnerRequest,
                                               Encoding.UTF8, "application/json");

            client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", authSuccessLoginResponce.Token);

            var response = await client.PostAsync(url, strContent);

            var carsJson = await response.Content.ReadAsStringAsync();

            var cars = JsonConvert.DeserializeObject <Response <List <Car> > >(carsJson);

            //Assert
            Assert.IsAssignableFrom <List <Car> >(cars.Data);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
Ejemplo n.º 5
0
        public async Task <PagedList <CustomUser> > GetAllCarOwners(UsersParameters usersParameters)
        {
            var iQueryableUsers = _repository.GetIQueryableUsers().OrderBy(u => u.FirstName);

            return(await PagedList <CustomUser>
                   .ToPagedList(
                       iQueryableUsers,
                       usersParameters.PageNum,
                       usersParameters.PageSize
                       ));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Parallel to <see cref="GetUsersAsync(UsersParameters)"/> to only get a single user.
        /// </summary>
        public async Task <User> GetUserAsync(string nameOrId)
        {
            UsersParameters parameters = new UsersParameters();

            if (int.TryParse(nameOrId, out _))
            {
                parameters.IDs = new[] { nameOrId }
            }
            ;
            else
            {
                parameters.Logins = new[] { nameOrId }
            };
            var users = await GetUsersAsync(parameters);

            return(users.Data.Single());
        }
Ejemplo n.º 7
0
        //public async Task<IdentityResult<IEnumerable<UserWithRoles>>> GetUsersFromRole(UsersParameters parameters)
        //{
        //    const int defaultRoleId = -1;

        //    var res = new IdentityResult<IEnumerable<UserWithRoles>>();

        //    int roleId;

        //    if (string.IsNullOrWhiteSpace(parameters.Role))
        //        roleId = defaultRoleId;
        //    else
        //    {
        //        var role = await _roleManager.FindByNameAsync(parameters.Role);
        //        if (role != null)
        //        {
        //            roleId = role.Id;
        //        }

        //        else
        //        {
        //            res.Success = false;
        //            res.Errors = new[] {"Invalid role"};
        //            res.ErrorType = ErrorType.NotFound;
        //            return res;
        //        }
        //    }

        //    // based on https://stackoverflow.com/questions/51004516/net-core-2-1-identity-get-all-users-with-their-associated-roles

        //    var usersList =
        //        (await _context.Users
        //                    //limit users to search to users that have the role selected
        //                .Where(user =>
        //                    roleId == defaultRoleId ||
        //                    _context.UserRoles.Where(r=> r.RoleId == roleId).Select(w=>w.UserId).Contains(user.Id)
        //                    )
        //                .SelectMany(
        //                    // -- below emulates a left outer join, as it returns DefaultIfEmpty in the collectionSelector
        //                    user => _context.UserRoles.Where(userRoleMapEntry => user.Id == userRoleMapEntry.UserId)
        //                        .DefaultIfEmpty(),
        //                    (user, roleMapEntry) => new {User = user, RoleMapEntry = roleMapEntry})
        //                .SelectMany(
        //                    // perform the same operation to convert role IDs from the role map entry to roles
        //                    x => _context.Roles.Where(role => role.Id == x.RoleMapEntry.RoleId).DefaultIfEmpty(),
        //                    (x, role) => new {User = x.User, RoleName = role.Name})
        //                .ToListAsync() // runs the queries and sends us back into EF Core LINQ world
        //        )
        //        .Aggregate(
        //            new Dictionary<ApplicationUser, List<string>>(), // seed (accumulator)
        //            (accumulator, itemToProcess) =>
        //            {
        //                // safely ensure the user entry is configured
        //                accumulator.TryAdd(itemToProcess.User, new List<string>());
        //                if (itemToProcess.RoleName != null)
        //                {
        //                    accumulator[itemToProcess.User].Add(itemToProcess.RoleName);
        //                }

        //                return accumulator;
        //            },
        //            x => x.Select(item => new UserWithRoles {User = item.Key, Roles = item.Value})
        //        );

        //    res.Success = true;
        //    res.Object = usersList;

        //    return res;
        //}

        public async Task <IdentityResult <PagedList <UserWithRoles> > > GetUsersFromRole(UsersParameters parameters)
        {
            const int defaultRoleId = -1;

            var res = new IdentityResult <PagedList <UserWithRoles> >();

            int roleId;

            if (string.IsNullOrWhiteSpace(parameters.Role))
            {
                roleId = defaultRoleId;
            }
            else
            {
                var role = await _roleManager.FindByNameAsync(parameters.Role);

                if (role != null)
                {
                    roleId = role.Id;
                }

                else
                {
                    res.Success   = false;
                    res.Errors    = new[] { "Invalid role" };
                    res.ErrorType = ErrorType.NotFound;
                    return(res);
                }
            }

            // based on https://stackoverflow.com/questions/51004516/net-core-2-1-identity-get-all-users-with-their-associated-roles

            var totalUsers = 0;
            var usersList  = _context.Users
                             //limit users to search to users that have the role selected
                             .Where(user =>
                                    roleId == defaultRoleId ||
                                    _context.UserRoles.Where(r => r.RoleId == roleId).Select(w => w.UserId).Contains(user.Id)
                                    );

            var propertyMappingDictionary =
                _sortingPropertyMappingService.GetPropertyMappingByTypeNames(parameters.GetSortingMappingSourceTypeName(), parameters.GetSortingMappingDestinationTypeName());

            usersList = usersList.ApplySort(parameters.OrderBy, parameters.Direction, propertyMappingDictionary);

            totalUsers = usersList.Count();

            var usersWithRoles = (await
                                  usersList
                                  .Skip((parameters.Page - 1) * parameters.PageSize).Take(parameters.PageSize)
                                  .SelectMany(
                                      // -- below emulates a left outer join, as it returns DefaultIfEmpty in the collectionSelector
                                      user => _context.UserRoles.Where(userRoleMapEntry => user.Id == userRoleMapEntry.UserId)
                                      .DefaultIfEmpty(),
                                      (user, roleMapEntry) => new { User = user, RoleMapEntry = roleMapEntry })
                                  .SelectMany(
                                      // perform the same operation to convert role IDs from the role map entry to roles
                                      x => _context.Roles.Where(role => role.Id == x.RoleMapEntry.RoleId).DefaultIfEmpty(),
                                      (x, role) => new { User = x.User, RoleName = role.Name })
                                  .ToListAsync()
                                  )
                                 .Aggregate(
                new Dictionary <ApplicationUser, List <string> >(),  // seed (accumulator)
                (accumulator, itemToProcess) =>
            {
                // safely ensure the user entry is configured
                accumulator.TryAdd(itemToProcess.User, new List <string>());
                if (itemToProcess.RoleName != null)
                {
                    accumulator[itemToProcess.User].Add(itemToProcess.RoleName);
                }

                return(accumulator);
            },
                x => x.Select(item => new UserWithRoles {
                User = item.Key, Roles = item.Value
            })
                );

            res.Success = true;
            res.Object  = new PagedList <UserWithRoles>(usersWithRoles, totalUsers, parameters.Page, parameters.PageSize);

            return(res);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets information about one or more specified Twitch users.
        /// Users are identified by optional user IDs and/or login name. If neither a user ID nor a login name is specified, the user is looked up by Bearer token.
        /// </summary>
        public async Task <ResponseWrapper <User[]> > GetUsersAsync(UsersParameters parameters)
        {
            string url = CombineUrls(BaseUrl, $"/users{parameters}");

            return(await GetTypedResponseAsync <User[]>(url));
        }
Ejemplo n.º 9
0
        public async Task <ActionResult <IEnumerable <UserDetailsShortResponse> > > GetUsersShort([FromQuery] UsersParameters parameters)

        {
            return(await GetUsersGeneric <UserDetailsShortResponse>(parameters));
        }