private async Task <bool> UpdateRoleAsync(UserDAO user)
        {
            var currentUserName = _requestContext.GetCurrentUserName();

            var newRoles = Input.Roles
                           .Where(role => role.HasRole)
                           .Select(role => role.Name)
                           .ToList();
            var currentRoles = await _userManager.GetRolesAsync(user);

            var rolesToRemove = currentRoles.Where(r => !newRoles.Contains(r)).ToList();
            var rolesToAdd    = newRoles.Where(r => !currentRoles.Contains(r)).ToList();

            if (rolesToRemove.Count > 0)
            {
                // don't allow remove super users from Admin role
                if (_identityLogic.IsSuperAdminUser(user.UserName) && rolesToRemove.Contains(RoleType.Administrator))
                {
                    ModelState.AddModelError(string.Empty, $"User {user.UserName} is super admin, you don't have permission to remove it from {RoleType.Administrator} role.");
                    return(false);
                }

                var removeRolesResult = await _userManager.RemoveFromRolesAsync(user, rolesToRemove);

                if (!removeRolesResult.Succeeded)
                {
                    var errors = AddToModelStateErrors(removeRolesResult);
                    _logger.LogInformation("{@User} failed when removed {@UserName} from role(s) {@Roles}, Errors {@Errors}.", currentUserName, user.UserName,
                                           string.Join(',', rolesToRemove), errors);
                    return(false);
                }
            }

            if (rolesToAdd.Count > 0)
            {
                var addRolesResult = await _userManager.AddToRolesAsync(user, rolesToAdd);

                if (!addRolesResult.Succeeded)
                {
                    var errors = AddToModelStateErrors(addRolesResult);
                    _logger.LogInformation("{@User} failed when added {@UserName} to role(s) {@Roles}, Errors {@Errors}.", currentUserName, user.UserName,
                                           string.Join(',', rolesToAdd), errors);
                    return(false);
                }
            }

            return(true);
        }
        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);
                }
            }
        }
Beispiel #3
0
        public bool IsLegalToDeleteUser(string userName)
        {
            var currentUser = _requestContext.GetCurrentUserName();

            return(!currentUser.Equals(userName, StringComparison.OrdinalIgnoreCase) &&
                   !IsSuperAdminUser(userName));
        }
Beispiel #4
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"));
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var currentUserName = _requestContext.GetCurrentUserName();
                var user            = new UserDAO {
                    UserName = Input.Email, Email = Input.Email, EmailConfirmed = true
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    var createdUser = await _userManager.FindByNameAsync(user.Email);

                    var roleNames = Input.Roles
                                    .Where(role => role.HasRole)
                                    .Select(role => role.Name)
                                    .ToList();
                    var assignRolesResult = await _userManager.AddToRolesAsync(createdUser, roleNames);

                    if (assignRolesResult.Succeeded)
                    {
                        StatusMessage = $"Created user '{user.UserName}'.";
                        _logger.LogInformation("{@User} created new account {@UserName} with role(s) {@Roles}.", currentUserName, user.UserName, string.Join(',', roleNames));
                    }
                    else
                    {
                        StatusMessage = $"Created user '{user.UserName}' but there was some problems when tried to assign user to role(s).";
                        _logger.LogWarning("{@User} created new account {@UserName}, but failed when assigned him to role(s) {@Roles}.", currentUserName, user.UserName, string.Join(',', roleNames));
                    }

                    return(RedirectToPage("Users"));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        private void AutomaticSetupAuditData()
        {
            var currentUserName = _currentUserService.GetCurrentUserName();

            foreach (var entry in ChangeTracker.Entries <AuditableDAO>())
            {
                switch (entry.State)
                {
                case EntityState.Added:
                    entry.Entity.CreatedBy   = currentUserName;
                    entry.Entity.CreatedDate = _dateTimeService.Now;
                    break;

                case EntityState.Modified:
                    entry.Entity.LastModifiedBy = currentUserName;
                    entry.Entity.LastModifyDate = _dateTimeService.Now;
                    break;
                }
            }
        }