using System.Security.Claims; using Hutopy.Domain.Interfaces; using Hutopy.Domain.Models; using Hutopy.Infrastructure.Identity; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; namespace Hutopy.Infrastructure.Services; public class UserService(UserManager userManager, IHttpContextAccessor contextAccessor) : IUserService { public async Task CreateUserAsync(string email, string userName, string firstName, string lastName, string password) { var applicationUser = new ApplicationUser { UserName = userName, Email = email, FirstName = firstName, LastName = lastName }; //todo: Need to handle errors better for the user. var response = await userManager.CreateAsync(applicationUser, password); if (response.Errors.Any()) { throw new InvalidOperationException(response.Errors.First().Description); } } public async Task FindUserByIdAsync(string id) { var response = await userManager.FindByIdAsync(id); if (response == null) return null; var userModel = new UserModel() { Id = response.Id, UserName = response.UserName, FirstName = response.FirstName, LastName = response.LastName, Email = response.Email, }; return userModel; } public async Task GetCurrentUserAsync() { var currentUserId = contextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (string.IsNullOrEmpty(currentUserId)) { return null; } return await FindUserByIdAsync(currentUserId); } public async Task FindUserByEmailAsync(string email) { var response = await userManager.FindByEmailAsync(email); if (response == null) return null; var userModel = new UserModel() { Id = response.Id, UserName = response.UserName, FirstName = response.FirstName, LastName = response.LastName, Email = response.Email }; return userModel; } }