public static Model.RoleUserPatchInfo Converter(string userName, Client.RoleUserPatchInfo clientRoleUserPatchInfo)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (clientRoleUserPatchInfo == null)
            {
                throw new ArgumentNullException(nameof(clientRoleUserPatchInfo));
            }

            var modelRoleUserPatchInfo = new Model.RoleUserPatchInfo(userName, clientRoleUserPatchInfo.UserRoles);

            return(modelRoleUserPatchInfo);
        }
Пример #2
0
        public async Task <IActionResult> PatchRoleAsync([FromRoute] string userName, [FromBody] Client.RoleUserPatchInfo clientPatchInfo,
                                                         CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (clientPatchInfo == null)
            {
                var error = Responses.BodyIsMissing(nameof(clientPatchInfo));
                return(BadRequest());
            }

            RoleUserPatchInfo modelPatchInfo;

            try
            {
                modelPatchInfo = ModelConverters.Roles.RoleUserPatchInfoConverter.Converter(userName, clientPatchInfo);
            }
            catch (ArgumentNullException ex)
            {
                var error = Responses.BodyIsMissing(ex.Message);
                return(BadRequest(error));
            }

            var user = await userManager.FindByNameAsync(userName);

            if (user == null)
            {
                var error = Responses.NotFoundError("User not found", userName);
                return(BadRequest());
            }

            List <string> modelUserRoles = new List <string>();

            foreach (var role in clientPatchInfo.UserRoles)
            {
                var tempRole = await roleManager.FindByNameAsync(role);

                if (tempRole != null)
                {
                    modelUserRoles.Add(role.ToLower());
                }
            }

            if (modelUserRoles.Count == 0)
            {
                var error = Responses.NotFoundError(nameof(clientPatchInfo.UserRoles), "UserRoles");
                return(BadRequest(error));
            }

            user.Roles = modelUserRoles;

            await userManager.UpdateAsync(user);

            return(Ok());
        }