using DrinkRateAPI.DbEntities; using DrinkRateAPI.Exceptions; using DrinkRateAPI.Services; namespace DrinkRateAPI.AuthorizationPolicies; using Microsoft.AspNetCore.Authorization; public class AdminOnlyRequirement : IAuthorizationRequirement { } public class AdminOnlyHandler : AuthorizationHandler { private readonly ApplicationUserService _applicationUserService; private readonly UserProfileService _userProfileService; public AdminOnlyHandler( ApplicationUserService applicationUserService, UserProfileService userProfileService) { _applicationUserService = applicationUserService; _userProfileService = userProfileService; } protected override async Task HandleRequirementAsync( AuthorizationHandlerContext context, AdminOnlyRequirement requirement) { DbUserProfile userProfile; try { userProfile = await _applicationUserService.UserProfileByApplicationUserAsync(context.User); } catch (NotFoundException _) { throw new ForbiddenException("You need to be logged in to do this action."); } if (_userProfileService.IsUserProfileAdmin(userProfile)) { context.Succeed(requirement); } } }