Api/Netina.Api/Services/CurrentUserService.cs

55 lines
2.2 KiB
C#
Raw Normal View History

2024-02-08 18:56:56 +03:30
using System.Security.Cryptography;
2024-04-16 20:01:34 +03:30
using Netina.Repository.Abstracts;
2024-04-16 20:01:34 +03:30
namespace Netina.Api.Services;
2024-08-09 21:55:16 +03:30
public class CurrentUserService(IHttpContextAccessor httpContextAccessor) : ICurrentUserService
{
2024-08-09 21:55:16 +03:30
public string? UserId => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
public string? RoleName => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Role);
public string? UserName => httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name);
public string? DeviceId => GetDeviceId(httpContextAccessor.HttpContext);
2024-02-08 18:56:56 +03:30
public bool IsAuthorized => GetAuthorized();
public JwtSecurityToken? JwtToken => GetJwtToken();
private JwtSecurityToken? GetJwtToken()
{
2024-08-09 21:55:16 +03:30
var stream = httpContextAccessor.HttpContext?.Request.Headers.Authorization.FirstOrDefault();
if (stream == null)
return null;
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream.Split(" ").Last());
return jsonToken as JwtSecurityToken;
}
2024-08-09 21:55:16 +03:30
public List<string>? Permissions => httpContextAccessor.HttpContext?.User?.FindAll("Permission")?.Select(c => c.Value)?.ToList();
2024-02-08 18:56:56 +03:30
private string? GetDeviceId(HttpContext? context)
{
if (context?.Request?.Headers == null)
return null;
string? userAgent = context.Request.Headers["User-Agent"];
string? ipAddress = context.Connection.RemoteIpAddress?.ToString();
string? origin = context.Request.Headers["Origin"];
string input = userAgent + "_" + ipAddress;
using SHA256 sha256Hash = SHA256.Create();
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
var uniqueId = builder.ToString();
return uniqueId;
}
private bool GetAuthorized()
{
2024-08-09 21:55:16 +03:30
if (httpContextAccessor.HttpContext?.User.Identity == null)
2024-02-08 18:56:56 +03:30
return false;
2024-08-09 21:55:16 +03:30
return httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
2024-02-08 18:56:56 +03:30
}
}