Exemplo n.º 1
0
        public async Task <IHttpActionResult> Get(int userId)
        {
            var resultadoUsuario = string.Empty;//usuario.ObtenerPorId(userId);


            var usuarioApp = _userManager.Users.FirstOrDefault(x => x.Email == resultadoUsuario);

            var assignedRoles = await _userManager.GetRolesAsync(usuarioApp.Id);

            var allRoles = _roleManager.Roles.ToList();

            var userRoles = allRoles.Select(r => new SelectListItem()
            {
                Value    = r.Name,
                Text     = r.Name,
                Selected = assignedRoles.Contains(r.Name),
            }).ToList();

            var viewModel = new UsuarioRolesViewModel()
            {
                Username  = usuarioApp.UserName,
                UserId    = (int)usuarioApp.Id,
                UserRoles = userRoles,
            };

            return(Ok(viewModel));
        }
Exemplo n.º 2
0
        public async Task <IHttpActionResult> Put([FromBody] UsuarioRolesViewModel viewModel)
        {
            var user = await _userManager.FindByIdAsync(viewModel.UserId);

            var possibleRoles = await _roleManager.Roles.ToListAsync();

            var userRoles = await _userManager.GetRolesAsync(user.Id);

            var submittedRoles = viewModel.SelectedRoles;

            var shouldUpdateSecurityStamp = false;

            foreach (var submittedRole in submittedRoles)
            {
                var hasRole = await _userManager.IsInRoleAsync(user.Id, submittedRole);

                if (!hasRole)
                {
                    shouldUpdateSecurityStamp = true;
                    await _userManager.AddToRoleAsync(user.Id, submittedRole);
                }
            }

            foreach (var removedRole in possibleRoles.Select(r => r.Name).Except(submittedRoles))
            {
                shouldUpdateSecurityStamp = true;
                await _userManager.RemoveFromRoleAsync(user.Id, removedRole);
            }

            if (shouldUpdateSecurityStamp)
            {
                await _userManager.UpdateSecurityStampAsync(user.Id);
            }

            return(Ok(true));
        }