public async Task <bool> SetUserRole(ClaimsPrincipal currentUser, string userId, string roleName, bool status) { if (!ApplicationRoleManager.CanEdit(currentUser, roleName)) { return(false); } var user = _userManager.Users.SingleOrDefault(u => u.Id == userId); if (user == null) { return(false); } if (user.UserName == currentUser.Identity.Name && roleName == ApplicationRoleManager.Administrator) { return(false); } if (!currentUser.IsInRole(ApplicationRoleManager.MultiSyndicate) && await _userManager.IsInRoleAsync(user, ApplicationRoleManager.MultiSyndicate)) { return(false); } var roleExists = await _roleManager.RoleExistsAsync(roleName); if (!roleExists) { return(false); } if (status) { var result = await _userManager.AddToRoleAsync(user, roleName); if (!result.Succeeded) { return(false); } } else { var result = await _userManager.RemoveFromRoleAsync(user, roleName); if (!result.Succeeded) { return(false); } } return(true); }
public async Task <UserListViewModel> GetUserList(ClaimsPrincipal currentUser, Syndicate syndicate) { var loadAll = currentUser.IsInRole(ApplicationRoleManager.MultiSyndicate); if (!loadAll && syndicate == null) { return new UserListViewModel { Players = new List <Player>(), Roles = new Dictionary <string, bool>(), Users = new List <UserViewModel>(), } } ; var playerList = _dbContext.Player.Where(p => loadAll || p.SyndicateId == syndicate.Id).OrderBy(p => p.Name).AsEnumerable(); var roleList = _roleManager.Roles.ToDictionary(r => r.Name, r => ApplicationRoleManager.CanEdit(currentUser, r.Name)); var userList = _userManager.Users .AsEnumerable() //TODO: !BAD! for performance - think about the way to rewrite it .Where( u => loadAll || playerList.Any(p => p.Id == u.PlayerId) || u.SyndicateOverride == syndicate.Id ) .OrderBy(u => u.UserName) .Select(u => new UserViewModel { User = u, Player = null, // have to select it further down the road Roles = roleList.ToDictionary(r => r.Key, r => false), // We need to populate the roles later since ET lambdas do not support async ops AllowActivation = false, // Same as above } ).ToArray(); for (var i = 0; i < userList.Count(); i++) { userList[i].Player = playerList.SingleOrDefault(p => p.Id == userList[i].User.PlayerId); var userRoles = await _userManager.GetRolesAsync(userList[i].User); foreach (var role in roleList.Keys) { userList[i].Roles[role] = userRoles.Contains(role); } var maxRole = userRoles.Contains(ApplicationRoleManager.Administrator) ? ApplicationRoleManager.Administrator : userRoles.Contains(ApplicationRoleManager.Leader) ? ApplicationRoleManager.Leader : userRoles.Contains(ApplicationRoleManager.Officer) ? ApplicationRoleManager.Officer : ""; userList[i].AllowActivation = userList[i].User.UserName == currentUser.Identity.Name ? false : ApplicationRoleManager.CanActivate(currentUser, maxRole); } return(new UserListViewModel { Roles = roleList, Users = userList, Players = playerList, }); }