コード例 #1
0
        public async Task <IdentityResult <UserWithRoles> > GetUserByKey(string key)
        {
            var res = new IdentityResult <UserWithRoles>();

            var apiKeyResult = await _context.ApiKeys.SingleOrDefaultAsync(apiKey => apiKey.Key == key && apiKey.Active);

            if (apiKeyResult == null)
            {
                res.Errors    = new[] { "Invalid key" };
                res.ErrorType = ErrorType.InvalidParameters;
                return(res);
            }

            var user = await _userManager.FindByNameAsync(apiKeyResult.User.UserName);

            if (user == null)
            {
                res.Errors    = new[] { "User with this username not found" };
                res.ErrorType = ErrorType.NotFound;
                return(res);
            }

            var details = new UserWithRoles
            {
                User  = user,
                Roles = await _userManager.GetRolesAsync(user)
            };

            res.Object  = details;
            res.Success = true;

            return(res);
        }
コード例 #2
0
        /// <summary>
        /// Validate user by username and password
        /// </summary>
        /// <param name="username">username</param>
        /// <param name="password">password</param>
        /// <param name="lockoutOnFailure">to disable the lockout feature, use false</param>
        /// <returns></returns>
        public async Task <IdentityResult <UserWithRoles> > GetUserByUsername(string username, string password, bool lockoutOnFailure)
        {
            var res = new IdentityResult <UserWithRoles>();

            var user = await _userManager.FindByNameAsync(username);

            if (user == null)
            {
                res.Errors    = new[] { "User with this username not found" };
                res.ErrorType = ErrorType.NotFound;
                return(res);
            }


            var userHasValidPassword = await _userManager.CheckPasswordAsync(user, password);

            if (!userHasValidPassword)
            {
                res.Errors = new[] { "Invalid password" };

                if (_userManager.SupportsUserLockout && lockoutOnFailure)
                {
                    // If lockout is requested, increment access failed count which might lock out the user
                    await _userManager.AccessFailedAsync(user);

                    if (await _userManager.IsLockedOutAsync(user))
                    {
                        res.Errors = new[] { "Invalid password", "Account is locked out" };
                    }
                }

                res.ErrorType = ErrorType.InvalidParameters;
                return(res);
            }

            // account is still in lockout period
            if (_userManager.SupportsUserLockout && user.LockoutEnabled && user.LockoutEnd.HasValue)
            {
                if (user.LockoutEnd.Value.DateTime > DateTime.UtcNow)
                {
                    res.Errors    = new[] { "Account is still locked out" };
                    res.ErrorType = ErrorType.InvalidParameters;
                    return(res);
                }
            }

            await _userManager.ResetLockout(user);

            var details = new UserWithRoles
            {
                User  = user,
                Roles = await _userManager.GetRolesAsync(user)
            };

            res.Object  = details;
            res.Success = true;

            return(res);
        }
コード例 #3
0
        public async Task <IdentityResult <UserWithRoles> > GetUserByUsername(string username)
        {
            var user = await _userManager.FindByNameAsync(username);

            if (user == null)
            {
                return(new IdentityResult <UserWithRoles>("User with this username not found", errorType: ErrorType.NotFound));
            }

            var details = new UserWithRoles
            {
                User  = user,
                Roles = await _userManager.GetRolesAsync(user)
            };

            var res = new IdentityResult <UserWithRoles>
            {
                Object  = details,
                Success = true
            };

            return(res);
        }
コード例 #4
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);
        }