2021-12-11 16:47:28 +05:00
|
|
|
|
using AsbCloudApp.Services;
|
|
|
|
|
using Microsoft.AspNetCore.Authentication;
|
|
|
|
|
using Microsoft.AspNetCore.Authorization;
|
|
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace AsbCloudWebApi.Middlewares
|
|
|
|
|
{
|
|
|
|
|
public class PermissionsMiddlware
|
|
|
|
|
{
|
|
|
|
|
private readonly RequestDelegate next;
|
|
|
|
|
|
|
|
|
|
public PermissionsMiddlware(RequestDelegate next)
|
|
|
|
|
{
|
|
|
|
|
this.next = next;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
|
|
|
{
|
|
|
|
|
var endpoint = context.GetEndpoint();
|
|
|
|
|
var permission = endpoint?.Metadata.GetMetadata<PermissionAttribute>();
|
|
|
|
|
if (permission is null)
|
|
|
|
|
{
|
|
|
|
|
await next(context);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var idUser = context.User.GetUserId();
|
|
|
|
|
if (idUser is null)
|
|
|
|
|
{
|
|
|
|
|
await context.ForbidAsync();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var permissionName = permission.Name;
|
|
|
|
|
if (string.IsNullOrEmpty(permissionName))
|
|
|
|
|
permissionName = endpoint.Metadata
|
|
|
|
|
.GetMetadata<Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor>()
|
|
|
|
|
?.ControllerName
|
|
|
|
|
.ToLower();
|
2021-12-16 16:00:47 +05:00
|
|
|
|
|
2021-12-11 16:47:28 +05:00
|
|
|
|
var userService = context.RequestServices.GetRequiredService<IUserService>();
|
2021-12-16 16:00:47 +05:00
|
|
|
|
var isAuthorized = userService.HasPermission((int)idUser, permissionName);
|
2021-12-11 16:47:28 +05:00
|
|
|
|
|
|
|
|
|
if(isAuthorized)
|
|
|
|
|
await next?.Invoke(context);
|
|
|
|
|
else
|
|
|
|
|
await context.ForbidAsync();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|