feat(UserConroller): Added method to get authorized user.
This commit is contained in:
parent
79167a7f9d
commit
eb45c6aefa
@ -5,7 +5,7 @@ namespace WorkFlow.API.Controllers
|
|||||||
{
|
{
|
||||||
public static class ControllerExtensions
|
public static class ControllerExtensions
|
||||||
{
|
{
|
||||||
public static bool? TryGetUserId(this ControllerBase controller, out int id)
|
public static bool TryGetUserId(this ControllerBase controller, out int? id)
|
||||||
{
|
{
|
||||||
var value = controller.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
var value = controller.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||||
|
|
||||||
@ -22,7 +22,7 @@ namespace WorkFlow.API.Controllers
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
id = default;
|
id = null;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
44
WorkFlow.API/Controllers/UserController.cs
Normal file
44
WorkFlow.API/Controllers/UserController.cs
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
using DigitalData.Core.DTO;
|
||||||
|
using DigitalData.UserManager.Application.Contracts;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace WorkFlow.API.Controllers
|
||||||
|
{
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
[ApiController]
|
||||||
|
[Authorize]
|
||||||
|
public class UserController(ILogger<UserController> logger, IUserService userService) : ControllerBase
|
||||||
|
{
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<IActionResult> GetAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!this.TryGetUserId(out int? id))
|
||||||
|
{
|
||||||
|
logger.LogError("Authorization failed: User ID claim not found.");
|
||||||
|
return StatusCode(StatusCodes.Status500InternalServerError, "Failed to retrieve user identity.");
|
||||||
|
}
|
||||||
|
else if(id is int id_int)
|
||||||
|
return await userService.ReadByIdAsync(id_int).ThenAsync(
|
||||||
|
Success: Ok,
|
||||||
|
Fail: IActionResult (msg, ntc) =>
|
||||||
|
{
|
||||||
|
logger.LogNotice(ntc);
|
||||||
|
return NotFound();
|
||||||
|
});
|
||||||
|
else
|
||||||
|
{
|
||||||
|
logger.LogError("Invalid user ID: Retrieved ID is null or not an integer.");
|
||||||
|
return StatusCode(StatusCodes.Status500InternalServerError, "Invalid user ID.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch(Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(exception: ex, "{message}", ex.Message);
|
||||||
|
return StatusCode(StatusCodes.Status500InternalServerError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user