drinkrate/DrinkRateAPI/Controllers/UserProfileController.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

40 lines
No EOL
1.3 KiB
C#

using System.Security.Claims;
using DrinkRateAPI.ApiModels.UserProfile;
using DrinkRateAPI.AuthorizationPolicies;
using DrinkRateAPI.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace DrinkRateAPI.Controllers;
[ApiController]
[Route("userProfile")]
public class UserProfileController : ControllerBase
{
private readonly ILogger<UserProfileController> _logger;
private readonly UserProfileService _userProfileService;
public UserProfileController(ILogger<UserProfileController> logger, UserProfileService userProfileService)
{
_logger = logger;
_userProfileService = userProfileService;
}
[HttpPut]
public UserProfileGet PutUserProfile([FromBody] UserProfilePut userProfile)
{
throw new ApplicationException();
var x = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; //HttpContext.User.Identities.First();
return new();
}
[HttpPut("{userId}/adminStatus")]
[Authorize(Policy = PolicyConstants.AdminOnly)]
[Produces("application/json")]
public async Task<IActionResult> PutUserAdminStatus(string userId, [FromBody] UserProfileAdminStatusPut body)
{
var changedProfile = await _userProfileService.PutUserProfileAdminStatusAsync(userId, body.ChangeStatusTo);
return Ok(changedProfile);
}
}