public async Task <ActionResult> GetByRole(string roleId) { //If User is not an Admin, and passed the Admin RoleId, return Forbidden if (!User.IsInRole(AdministratorRoleName) && roleId == AdministratorRoleId) { return(Forbid()); } //Check if the role is valid before going on if (!ValidateRole(roleId)) { return(BadRequest("The provided roleId is not valid")); } //Get users in DB and filter by roleId var users = await userManager.GetUsersInRoleAsync(RoleHelper.GetRoleName(roleId)); //Order by Username, then convert to Dto var dtos = users .Select(u => UserDto.ConvertBack(u, roleId)) .OrderBy(u => u.UserName) .ToArray(); return(Ok(dtos)); }
public async Task <IActionResult> GetAll() { bool isAdmin = User.IsInRole(AdministratorRoleName); //Start by getting a list of User IDs with Role IDs var userWithRoles = await dbContext.UserRoles .ToDictionaryAsync ( ur => ur.UserId, ur => ur.RoleId ); //Initialize query by getting all users var users = await dbContext.Users.ToListAsync(); //Convert Models into Dtos var dtos = users .Select(u => UserDto.ConvertBack(u, userWithRoles.ContainsKey(u.Id) ? userWithRoles[u.Id] : null)) .ToArray(); //Order by RoleId and then by Username dtos = dtos .Where(u => u.Role != null && (isAdmin || u.Role.Id != AdministratorRoleId)) //If not an Administrator, filter non-Administrator Users .OrderBy(u => u.Role.Id) .ThenBy(u => u.UserName) .ToArray(); return(Ok(dtos)); }
public async Task <ActionResult> Get(string username) { var userInDb = await userManager.FindByNameAsync(username); if (userInDb == null) { return(NotFound()); } string roleName = await GetUserRoleName(userInDb); if (User.IsInRole(UserManagerRoleName) && roleName == AdministratorRoleName) { return(Forbid()); } return(Ok(UserDto.ConvertBack(userInDb, RoleHelper.GetRoleId(roleName)))); }