astral-api/Astral.ApiServer/Providers/IdentityProvider.cs

46 lines
1.3 KiB
C#
Raw Permalink Normal View History

2024-12-14 18:48:03 +01:00
// <copyright file="IdentityProvider.cs" company="alveus.dev">
// Copyright (c) alveus.dev. All rights reserved. Licensed under the MIT License.
// </copyright>
using System.Security.Claims;
using Astral.Services.Constants;
using Astral.Services.Interfaces;
using Injectio.Attributes;
namespace Astral.ApiServer.Providers;
/// <inheritdoc />
[RegisterScoped]
public class IdentityProvider : IIdentityProvider
{
/// <summary>
/// Initializes a new instance of the <see cref="IdentityProvider"/> class.
/// </summary>
/// <param name="httpContextAccessor">Instance of <see cref="IHttpContextAccessor"/>.</param>
public IdentityProvider(IHttpContextAccessor httpContextAccessor)
{
var claims = httpContextAccessor.HttpContext?.User.Claims;
if (claims is not null)
{
Claims = claims;
}
}
/// <summary>
/// Session claims.
/// </summary>
private IEnumerable<Claim> Claims { get; set; }
/// <inheritdoc />
public Guid GetUserId()
{
return Guid.TryParse(Claims.FirstOrDefault(c => c.Type == ClaimIds.UserId)?.Value, out var guid) ? guid : Guid.Empty;
}
/// <inheritdoc />
public string GetUserName()
{
return Claims.FirstOrDefault(c => c.Type == ClaimIds.UserName)?.Value;
}
}