public async Task OnGetAsync()
        {
            var currentUser = _requestContext.GetCurrentUserName();
            var roleNames   = await _roleManager.Roles
                              .Select(role => role.Name)
                              .OrderBy(role => role)
                              .ToListAsync();

            Users = await _userManager.Users
                    .Select(user => new UserModel
            {
                UserName = user.UserName,
                Roles    = new List <string>()
            })
                    .OrderBy(user => user.UserName)
                    .ToListAsync();

            Users.ForEach(user => user.AllowDelete = _identityLogic.IsLegalToDeleteUser(user.UserName));

            foreach (var roleName in roleNames)
            {
                var usersInRole = await _userManager.GetUsersInRoleAsync(roleName);

                foreach (var user in usersInRole)
                {
                    Users.FirstOrDefault(u => u.UserName == user.UserName)?.Roles.Add(roleName);
                }
            }
        }
Exemple #2
0
        public async Task <IActionResult> OnPostAsync()
        {
            var currentUserName = _requestContext.GetCurrentUserName();

            var user = await _userManager.FindByNameAsync(UserName);

            if (user == null)
            {
                return(NotFound($"Unable to load user '{UserName}'."));
            }

            if (!_identityLogic.IsLegalToDeleteUser(user.UserName))
            {
                ModelState.AddModelError(string.Empty, $"You do not have permission to delete user '{user.UserName}'.");
                return(Page());
            }

            var result = await _userManager.DeleteAsync(user);

            if (!result.Succeeded)
            {
                ModelState.AddModelError(string.Empty, $"Unexpected error occurred when deleting user '{user.UserName}'.");

                _logger.LogWarning("Unexpected error occurred when {@User} deleting user {@UserName}, Errors: {@Errors}.", currentUserName, user.UserName,
                                   string.Join(", ", result.Errors.Select(x => x.Description)));
                return(Page());
            }

            _logger.LogInformation("{@User} deleted user {@UserName}.", currentUserName, user.UserName);

            StatusMessage = $"Deleted user '{user.UserName}'.";

            return(RedirectToPage("Users"));
        }