using CPRNIMS.Infrastructure.Database; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace CPRNIMS.WebApi.Security { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizeRolesAttribute : AuthorizeAttribute, IAuthorizationFilter { private readonly string _controllerName; public AuthorizeRolesAttribute(string controllerName) { _controllerName = controllerName; } public async void OnAuthorization(AuthorizationFilterContext context) { try { var serviceProvider = context.HttpContext.RequestServices; var dbContext = serviceProvider.GetRequiredService(); var roles = await (from ar in dbContext.AuthorizeRoles join r in dbContext.Roles on ar.RoleId equals r.Id into roleJoin from r in roleJoin.DefaultIfEmpty() where ar.IsActive && ar.Controller == _controllerName select r.Name).ToListAsync(); Roles = string.Join(",", roles); } catch (Exception) { //ex.ToString(); //var message = ex.InnerException?.ToString() ?? ex.Message.ToString(); //await PostErrorMessage(message, ApplicationName.Name.WebApi); context.Result = new StatusCodeResult(StatusCodes.Status500InternalServerError); } } } }