drinkrate/DrinkRateAPI/AuthorizationPolicies/AdminOnlyRequirement.cs
martinshoob 9ec9139f69 Enhance AdminOnly authorization policy
Refactor the AdminOnly authorization policy to handle cases where a user profile is not found.
Instead of throwing a NotFoundException, it now throws a ForbiddenException, ensuring a more appropriate response for unauthorized access attempts.
Also introduces PolicyConstants for policy names.
2025-08-11 19:47:12 +02:00

46 lines
No EOL
1.2 KiB
C#

using DrinkRateAPI.DbEntities;
using DrinkRateAPI.Exceptions;
using DrinkRateAPI.Services;
namespace DrinkRateAPI.AuthorizationPolicies;
using Microsoft.AspNetCore.Authorization;
public class AdminOnlyRequirement : IAuthorizationRequirement
{
}
public class AdminOnlyHandler : AuthorizationHandler<AdminOnlyRequirement>
{
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();
}
if (_userProfileService.IsUserProfileAdmin(userProfile))
{
context.Succeed(requirement);
}
}
}