39 lines
1.4 KiB
C#
39 lines
1.4 KiB
C#
using KTUSAPS.Data;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using System;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace KTUSAPS.Auth
|
|
{
|
|
public class AdminAuthorizationHandler : AuthorizationHandler<AdminRequirement>
|
|
{
|
|
private readonly IServiceProvider serviceProvider;
|
|
public AdminAuthorizationHandler(IServiceProvider serviceProvider)
|
|
{
|
|
this.serviceProvider = serviceProvider;
|
|
}
|
|
|
|
protected async override Task HandleRequirementAsync(AuthorizationHandlerContext context, AdminRequirement requirement)
|
|
{
|
|
var idclaim = context.User.Claims.Where(c => c.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier").FirstOrDefault();
|
|
if(idclaim == default)
|
|
{
|
|
context.Fail();
|
|
return;
|
|
}
|
|
using var scope = serviceProvider.CreateScope();
|
|
var dataContext = scope.ServiceProvider.GetRequiredService<SAPSDataContext>();
|
|
var admin = await dataContext.Admins.Where(a => a.UserId == idclaim.Value).FirstOrDefaultAsync();
|
|
if (admin != default)
|
|
{
|
|
context.Succeed(requirement);
|
|
return;
|
|
}
|
|
context.Fail();
|
|
}
|
|
}
|
|
}
|