user service operaional

This commit is contained in:
ereshkigal 2024-09-07 15:24:05 +03:00
parent c39b481eb8
commit c1b3843e2a

View File

@ -4,13 +4,47 @@ using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Faker;
using Renis.Database.Models;
using Renis.Repositories;
using Renis.Services.Jwt;
using renis_backend.DTO;
using renis_backend.Exceptions.User;
namespace renis_backend.Services.Users
{
public class UserService : IUserService
{
private readonly ILogger<UserService> _logger;
private readonly IUserRepository _userRepository;
private readonly IJwtService _jwtService;
public UserService( ILogger<UserService> logger, IUserRepository userRepository, IJwtService jwtService)
{
_logger = logger;
_userRepository = userRepository;
_jwtService = jwtService;
}
public async Task<User> GetUserAsync(string phone)
{
try
{
var user = await _userRepository.GetUserByPhone(phone);
if(user == null)
{
throw new UserException("User not found");
}
return user;
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
if(ex is UserException)
{
throw;
}
throw new UserException(ex.Message);
}
}
public async Task<string> GenerateUser()
{
try
@ -30,8 +64,20 @@ namespace renis_backend.Services.Users
Phone = GenerateRussianPhoneNumber(),
Password = password
};
await _userRepository.AddUser(user);
return user.Phone;
if(await _userRepository.AddUser(user))
{
return _jwtService.GenerateAccessToken(user);
}
throw new UserException("User already exists");
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
if(ex is UserException)
{
throw;
}
throw new UserException(ex.Message);
}
}
@ -62,7 +108,5 @@ namespace renis_backend.Services.Users
string number = new string(Enumerable.Repeat("0123456789", 10).Select(c => c[random.Next(c.Length)]).ToArray());
return $"{prefix}{number}";
}
}
}