public async Task <IActionResult> AddRole(AddRolesToUserModel model)
        {
            var entity = await _service.GetUserByUserNameAsync(model.username);

            if (entity == null)
            {
                return(NotFound(AppResult.NotFound()));
            }
            var result = await _service.AddRolesForUserAsync(entity, model.roles);

            if (result.Succeeded)
            {
                return(NoContent());
            }
            foreach (var err in result.Errors)
            {
                ModelState.AddModelError(err.Code, err.Description);
            }
            return(BadRequest(AppResult.FailValidation(ModelState)));
        }
Exemplo n.º 2
0
        public async Task <IHttpActionResult> AssignRolesToUser([FromBody] AddRolesToUserModel artuModel)
        {
            //TODO: Should find by username instead
            var appUser = await this.UserManager.FindByNameAsync(artuModel.Username);

            if (appUser == null)
            {
                return(NotFound());
            }

            var currentRoles = await this.UserManager.GetRolesAsync(appUser.Id);

            var rolesNotExisting = artuModel.Roles.Except(this.AppRoleManager.Roles.Select(x => x.Name)).ToArray();

            if (rolesNotExisting.Any())
            {
                ModelState.AddModelError("", string.Format("Roles '{0}' do not exist in the system", string.Join(",", rolesNotExisting)));
                return(BadRequest(ModelState));
            }

            IdentityResult removeResult = await this.UserManager.RemoveFromRolesAsync(appUser.Id, currentRoles.ToArray());

            if (!removeResult.Succeeded)
            {
                ModelState.AddModelError("", "Failed to remove user roles");
                return(BadRequest(ModelState));
            }

            IdentityResult addResult = await this.UserManager.AddToRolesAsync(appUser.Id, artuModel.Roles);

            if (!addResult.Succeeded)
            {
                ModelState.AddModelError("", "Failed to add user roles");
                return(BadRequest(ModelState));
            }

            return(Ok());
        }