Files
social-media/src/Infrastructure/Services/UserService.cs
2024-05-18 00:04:10 -04:00

79 lines
2.2 KiB
C#

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<ApplicationUser> 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<UserModel?> 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<UserModel?> GetCurrentUserAsync()
{
var currentUserId = contextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(currentUserId))
{
return null;
}
return await FindUserByIdAsync(currentUserId);
}
public async Task<UserModel?> 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;
}
}