Poszukiwacz/Serwer/Serwer.Infrastructure/Services/UserService.cs

79 lines
2.6 KiB
C#
Raw Normal View History

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;
2020-12-18 16:04:07 +01:00
using Serwer.Infrastructure.ViewModels;
2020-12-06 18:31:05 +01:00
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.");
}
2020-12-18 16:04:07 +01:00
var user = new User(Guid.NewGuid(), email, name, surname, login, password);
2020-12-06 18:31:05 +01:00
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-18 16:04:07 +01:00
public async Task<UserDto> UpdateAsync(UpdateUserModel userModel)
{
var user = await _userRepository.GetAsync(userModel.Id);
if(user == null)
{
throw new Exception("User not found.");
}
var userLoginTaken = await _userRepository.GetAsync(userModel.Login);
if(userLoginTaken != null && userLoginTaken.Id != user.Id)
{
throw new Exception("User login taken.");
}
var newUser = new User(user.Id, userModel.Email, userModel.Name, userModel.Surname, userModel.Login, user.Password);
2020-12-18 16:04:07 +01:00
await _userRepository.UpdateAsync(newUser);
newUser = await _userRepository.GetAsync(user.Id);
return _mapper.Map<UserDto>(newUser);
}
2020-12-06 16:01:38 +01:00
}
}