Files
social-media/backend/Modules/Identity/Data/IdentityService.cs

69 lines
1.7 KiB
C#

using System.Security.Claims;
using Hutopy.Modules.Identity.Models;
namespace Hutopy.Modules.Identity.Data;
public class IdentityService(
UserManager userManager,
IHttpContextAccessor contextAccessor
)
{
public async Task<UserModel?> GetCurrentUserAsync()
{
string? currentUserId = contextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(currentUserId))
{
return null;
}
UserModel? ret;
User? user = await userManager.FindByIdAsync(currentUserId);
if (user == null)
{
ret = null;
}
else
{
UserModel userModel = new()
{
Id = user.Id,
Username = user.UserName ?? string.Empty,
PhoneNumber = user.PhoneNumber ?? string.Empty,
Email = user.Email ?? string.Empty,
PortraitUrl = user.PortraitUrl,
Alias = user.Alias,
Firstname = user.Firstname,
Lastname = user.Lastname,
BirthDate = user.BirthDate,
Address = user.Address
};
ret = userModel;
}
return ret;
}
public async Task<IList<string>> GetCurrentUserRolesAsync()
{
UserModel? currentUserModel = await GetCurrentUserAsync();
if (currentUserModel is null)
{
return [];
}
User? currentUser = await userManager.FindByIdAsync(currentUserModel.Id.ToString());
if (currentUser is null)
{
return [];
}
IList<string> userRoles = await userManager.GetRolesAsync(currentUser);
return userRoles;
}
}