60 lines
2.2 KiB
C#
60 lines
2.2 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Security.Claims;
|
|
using LCU.Library.Internal.IncentiveApiModels.Entities;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Serilog;
|
|
|
|
namespace LCU.API.Internal.Operations.IncentiveApiLib.Persistence;
|
|
|
|
public class CurrentUserService : ICurrentUserService
|
|
{
|
|
protected readonly IHttpContextAccessor HttpContextAccessor;
|
|
|
|
public CurrentUserService(IHttpContextAccessor httpContextAccessor)
|
|
{
|
|
HttpContextAccessor = httpContextAccessor;
|
|
}
|
|
|
|
public ApplicationUser GetCurrentUser()
|
|
{
|
|
try
|
|
{
|
|
if (HttpContextAccessor != null && HttpContextAccessor.HttpContext != null)
|
|
{
|
|
var userClaimsPrincipal = HttpContextAccessor.HttpContext.User;
|
|
var parsedApplicationUser = new ApplicationUser
|
|
{
|
|
FirstName = userClaimsPrincipal.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.GivenName)?.Value,
|
|
LastName = userClaimsPrincipal.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Surname)?.Value,
|
|
Email = userClaimsPrincipal.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Upn)?.Value,
|
|
Roles = userClaimsPrincipal.Claims.Where((claim) => claim.Type == ClaimTypes.Role).Select((claim) => claim?.Value).ToArray(),
|
|
IsSystem = false,
|
|
};
|
|
Log.Debug($"ApplicationUser: {parsedApplicationUser.Email} successfully parsed from HttpContext");
|
|
return parsedApplicationUser;
|
|
}
|
|
|
|
Log.Debug("HttpContextAccessor or HttpContext are null, returning default System ApplicationUser");
|
|
return DefaultSystemApplicationUser();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Log.Error(ex, ex.Message);
|
|
return DefaultSystemApplicationUser();
|
|
}
|
|
}
|
|
|
|
private ApplicationUser DefaultSystemApplicationUser()
|
|
{
|
|
return new ApplicationUser()
|
|
{
|
|
FirstName = "Incentive",
|
|
LastName = "Manager",
|
|
Email = "",
|
|
Roles = new[] { Role.UNKNOWN_ROLE.Name },
|
|
IsSystem = true
|
|
};
|
|
}
|
|
}
|