feat: Erweiterungsmethoden zum Extrahieren von Benutzerdetails in ControllerExtensions hinzugefügt

- Methoden implementiert, um Benutzer-ID, Benutzernamen, Nachnamen, Vornamen und E-Mail aus den Claims zu extrahieren
- Null-Überprüfungen und Parsing-Logik bereitgestellt, um eine gültige Extraktion sicherzustellen
This commit is contained in:
Developer 02 2024-10-24 22:10:02 +02:00
parent 4e5a68fa89
commit 2a81f33340

View File

@ -0,0 +1,94 @@
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace WorkFlow.API.Controllers
{
public static class ControllerExtensions
{
public static bool? TryGetUserId(this ControllerBase controller, out int id)
{
var value = controller.User.FindFirstValue(ClaimTypes.NameIdentifier);
if (value is null)
{
id = default;
return false;
}
if(int.TryParse(value, out int id_int))
{
id = id_int;
return true;
}
else
{
id = default;
return false;
}
}
public static bool TryGetUsername(this ControllerBase controller, out string username)
{
var value = controller.User.FindFirstValue(ClaimTypes.Name);
if (value is null)
{
username = string.Empty;
return false;
}
else
{
username = value;
return true;
}
}
public static bool TryGetName(this ControllerBase controller, out string name)
{
var value = controller.User.FindFirstValue(ClaimTypes.Surname);
if (value is null)
{
name = string.Empty;
return false;
}
else
{
name = value;
return true;
}
}
public static bool TryGetPrename(this ControllerBase controller, out string prename)
{
var value = controller.User.FindFirstValue(ClaimTypes.GivenName);
if (value is null)
{
prename = string.Empty;
return false;
}
else
{
prename = value;
return true;
}
}
public static bool TryGetEmail(this ControllerBase controller, out string email)
{
var value = controller.User.FindFirstValue(ClaimTypes.Email);
if (value is null)
{
email = string.Empty;
return false;
}
else
{
email = value;
return true;
}
}
}
}