|
| 1 | +using Microsoft.AspNetCore.Mvc; |
| 2 | +using Microsoft.EntityFrameworkCore; |
| 3 | +using UserManagementApi.Data; |
| 4 | +using UserManagementApi.DTO; |
| 5 | + |
| 6 | +namespace UserManagementApi.Controllers |
| 7 | +{ |
| 8 | + |
| 9 | + [ApiController] |
| 10 | + [Route("api/users")] |
| 11 | + public class UsersController : ControllerBase |
| 12 | + { |
| 13 | + private readonly AppDbContext _db; |
| 14 | + public UsersController(AppDbContext db) => _db = db; |
| 15 | + |
| 16 | + // GET: api/users/{userId}/permissions |
| 17 | + [HttpGet("{userId:int}/permissions")] |
| 18 | + public async Task<ActionResult<UserPermissionsDto>> GetPermissions(int userId) |
| 19 | + { |
| 20 | + var user = await _db.Users.FirstOrDefaultAsync(u => u.Id == userId); |
| 21 | + if (user == null) return NotFound($"User {userId} not found."); |
| 22 | + |
| 23 | + // Build a single LINQ query that filters functions to those reachable |
| 24 | + // via the user's roles (no client-side filtering). |
| 25 | + var categories = await _db.Categories |
| 26 | + .Select(c => new CategoryDto( |
| 27 | + c.Id, |
| 28 | + c.Name, |
| 29 | + c.Modules |
| 30 | + .Select(m => new ModuleDto( |
| 31 | + m.Id, m.Name, m.Area, m.Controller, m.Action, |
| 32 | + m.Functions |
| 33 | + .Where(f => f.RoleFunctions |
| 34 | + .Any(rf => rf.Role.UserRoles.Any(ur => ur.UserId == userId))) |
| 35 | + .Select(f => new FunctionDto(f.Id, f.Code, f.DisplayName)) |
| 36 | + .ToList() |
| 37 | + )) |
| 38 | + .Where(md => md.Functions.Any()) // keep only modules with at least one permitted function |
| 39 | + .ToList() |
| 40 | + )) |
| 41 | + .Where(cd => cd.Modules.Any()) // keep only categories with at least one permitted module |
| 42 | + .ToListAsync(); |
| 43 | + |
| 44 | + var dto = new UserPermissionsDto(user.Id, user.UserName, categories); |
| 45 | + return Ok(dto); |
| 46 | + } |
| 47 | + } |
0 commit comments