2020-12-06 18:31:05 +01:00
|
|
|
|
using AutoMapper;
|
|
|
|
|
using Serwer.Core.Domain;
|
|
|
|
|
using Serwer.Core.Repositories;
|
|
|
|
|
using Serwer.Infrastructure.DTO;
|
|
|
|
|
using Serwer.Infrastructure.Mappers;
|
|
|
|
|
using System;
|
2020-12-06 16:01:38 +01:00
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace Serwer.Infrastructure.Services
|
|
|
|
|
{
|
|
|
|
|
public class UserService: IUserService
|
|
|
|
|
{
|
2020-12-06 18:31:05 +01:00
|
|
|
|
private readonly IUserRepository _userRepository;
|
|
|
|
|
private readonly IJwtHandler _jwtHandler;
|
|
|
|
|
private readonly IMapper _mapper;
|
|
|
|
|
|
|
|
|
|
public UserService(IUserRepository userRepository, IJwtHandler jwtHandler, IMapper mapper)
|
|
|
|
|
{
|
|
|
|
|
_userRepository = userRepository;
|
|
|
|
|
_jwtHandler = jwtHandler;
|
|
|
|
|
_mapper = mapper;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task RegisterAsync(string email, string name, string surname, string login, string password)
|
|
|
|
|
{
|
|
|
|
|
if(await _userRepository.GetAsync(login) != null)
|
|
|
|
|
{
|
|
|
|
|
throw new Exception($"User with login: {login} already exists.");
|
|
|
|
|
}
|
|
|
|
|
var user = new User(email, name, surname, login, password);
|
|
|
|
|
await _userRepository.AddAsync(user);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<SignedUserDto> SignInAsync(string login, string password)
|
|
|
|
|
{
|
|
|
|
|
var user = await _userRepository.GetAsync(login);
|
|
|
|
|
if(user == null)
|
|
|
|
|
{
|
|
|
|
|
throw new Exception("User not found.");
|
|
|
|
|
}
|
|
|
|
|
if(user.Password != password)
|
|
|
|
|
{
|
|
|
|
|
throw new Exception("Incorrect password.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var jwt = _jwtHandler.CreateToken(user.Id);
|
|
|
|
|
|
|
|
|
|
return new SignedUserDto()
|
|
|
|
|
{
|
|
|
|
|
User = _mapper.Map<UserDto>(user),
|
|
|
|
|
Jwt = _mapper.Map<JwtDto>(jwt)
|
|
|
|
|
};
|
|
|
|
|
}
|
2020-12-06 16:01:38 +01:00
|
|
|
|
}
|
|
|
|
|
}
|