Files
social-media/backend/Modules/Identity/Data/IdentityService.cs
2025-06-13 02:22:35 -04:00

61 lines
1.6 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()
{
var currentUserId = contextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(currentUserId))
{
return null;
}
UserModel? ret;
var user = await userManager.FindByIdAsync(currentUserId);
if (user == null) ret = null;
else
{
var userModel = new UserModel
{
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()
{
var currentUserModel = await GetCurrentUserAsync();
if (currentUserModel is null) return [];
var currentUser = await userManager.FindByIdAsync(currentUserModel.Id.ToString());
if (currentUser is null) return [];
var userRoles = await userManager.GetRolesAsync(currentUser);
return userRoles;
}
}