public async Task <IActionResult> RemoveFromRole(UserWithRoleFormViewModel model)
        {
            bool isRoleExisting = await this.roleManager.RoleExistsAsync(model.Role);

            User user = await this.userManager.FindByNameAsync(model.Username);

            if (!ModelState.IsValid || !isRoleExisting || user == null)
            {
                TempData.AddErrorMessage(InvalidIdentityDetailsErroMessage);

                return(RedirectToAction(nameof(Details), new { model.Username }));
            }

            IdentityResult removeFromRoleResult = await this.userManager.RemoveFromRoleAsync(user, model.Role);

            if (!removeFromRoleResult.Succeeded)
            {
                string errors = string.Join(Environment.NewLine, removeFromRoleResult.Errors.Select(e => e.Description));

                TempData.AddErrorMessage(string.Format(ChangeRoleErrorMessage, errors));

                return(RedirectToAction(nameof(Details), new { model.Username }));
            }

            await this.userManager.UpdateAsync(user);

            TempData.AddSuccessMessage(string.Format(RemoveFromRoleSuccessMessage, model.Username, model.Role));

            return(RedirectToAction(nameof(Details), new { model.Username }));
        }
Beispiel #2
0
        public async Task <IActionResult> AddToRole(UserWithRoleFormViewModel model)
        {
            bool isRoleExisting = await this.roleManager.RoleExistsAsync(model.Role);

            bool isUserExisting = await this.userManager.FindByIdAsync(model.UserId) != null;

            if (!isRoleExisting || !isUserExisting)
            {
                ModelState.AddModelError(string.Empty, "Invalid identity details.");
            }

            if (!ModelState.IsValid)
            {
                return(RedirectToAction(nameof(Index)));
            }

            User user = await this.userManager.FindByIdAsync(model.UserId);

            IdentityResult addToRoleResult = await this.userManager.AddToRoleAsync(user, model.Role);

            if (!addToRoleResult.Succeeded)
            {
                string errors = string.Join(Environment.NewLine, addToRoleResult.Errors.Select(e => e.Description));

                TempData.AddErrorMessage($"Error. {errors}");

                return(RedirectToAction(nameof(Index)));
            }

            await this.userManager.UpdateAsync(user);

            TempData.AddSuccessMessage($"User '{user.UserName}' has been added to role '{model.Role}'.");

            return(RedirectToAction(nameof(Index)));
        }