55 lines
1.6 KiB
C#
55 lines
1.6 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using foundation_system.Data;
|
|
using System.Security.Claims;
|
|
|
|
namespace foundation_system.Components;
|
|
|
|
public class MenuViewComponent : ViewComponent
|
|
{
|
|
private readonly ApplicationDbContext _context;
|
|
|
|
public MenuViewComponent(ApplicationDbContext context)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
public async Task<IViewComponentResult> InvokeAsync()
|
|
{
|
|
var userIdClaim = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier);
|
|
if (userIdClaim == null || !long.TryParse(userIdClaim.Value, out var userId))
|
|
{
|
|
return View(new List<foundation_system.Models.Permiso>());
|
|
}
|
|
|
|
var isRoot = HttpContext.User.IsInRole("ROOT");
|
|
|
|
List<foundation_system.Models.Permiso> menuItems;
|
|
|
|
if (isRoot)
|
|
{
|
|
menuItems = await _context.Permisos
|
|
.Include(p => p.Modulo)
|
|
.Where(p => p.EsMenu)
|
|
.OrderBy(p => p.Modulo!.Orden)
|
|
.ThenBy(p => p.Orden)
|
|
.ToListAsync();
|
|
}
|
|
else
|
|
{
|
|
menuItems = await _context.RolesUsuario
|
|
.Where(ru => ru.UsuarioId == userId)
|
|
.Join(_context.RolesPermisos, ru => ru.RolId, rp => rp.RolId, (ru, rp) => rp)
|
|
.Join(_context.Permisos, rp => rp.PermisoId, p => p.Id, (rp, p) => p)
|
|
.Include(p => p.Modulo)
|
|
.Where(p => p.EsMenu)
|
|
.OrderBy(p => p.Modulo!.Orden)
|
|
.ThenBy(p => p.Orden)
|
|
.Distinct()
|
|
.ToListAsync();
|
|
}
|
|
|
|
return View(menuItems);
|
|
}
|
|
}
|