BotSharp/src/Infrastructure/BotSharp.Core/Users/Services/UserIdentity.cs

60 lines
1.6 KiB
C#
Raw Normal View History

2023-06-17 02:42:35 +00:00
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
2024-03-07 18:27:29 +00:00
using System.Text.Json.Serialization;
2023-06-17 02:42:35 +00:00
namespace BotSharp.Core.Users.Services;
public class UserIdentity : IUserIdentity
{
private readonly IHttpContextAccessor _contextAccessor;
2023-11-10 16:01:03 +00:00
private IEnumerable<Claim> _claims => _contextAccessor.HttpContext?.User.Claims!;
2023-06-17 02:42:35 +00:00
public UserIdentity(IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
2024-02-14 23:45:28 +00:00
public string Id
2023-11-10 16:01:03 +00:00
=> _claims?.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value!;
2023-06-17 02:42:35 +00:00
2024-03-07 18:27:29 +00:00
[JsonPropertyName("user_name")]
2024-01-05 03:20:50 +00:00
public string UserName
=> _claims?.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value!;
2024-02-14 23:45:28 +00:00
public string Email
2023-11-10 16:01:03 +00:00
=> _claims?.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value!;
2023-06-17 02:42:35 +00:00
2024-03-07 18:27:29 +00:00
[JsonPropertyName("first_name")]
2024-02-14 23:45:28 +00:00
public string FirstName
{
get
{
var givenName = _claims?.FirstOrDefault(x => x.Type == ClaimTypes.GivenName);
if (givenName == null)
{
return UserName;
}
return givenName.Value;
}
}
2023-06-17 02:42:35 +00:00
2024-03-07 18:27:29 +00:00
[JsonPropertyName("last_name")]
public string LastName
2023-11-10 16:01:03 +00:00
=> _claims?.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value!;
2024-01-31 19:57:54 +00:00
2024-03-07 18:27:29 +00:00
[JsonPropertyName("full_name")]
2024-01-31 19:57:54 +00:00
public string FullName
2024-03-07 18:27:29 +00:00
{
get
{
var fullName = _claims?.FirstOrDefault(x => x.Type == "full_name")?.Value;
if (!string.IsNullOrEmpty(fullName))
{
return fullName;
}
return $"{FirstName} {LastName}".Trim();
}
}
2023-06-17 02:42:35 +00:00
}