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.
46 lines
No EOL
1.2 KiB
C#
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);
|
|
}
|
|
}
|
|
} |