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

79 lines
2.7 KiB
C#
Raw Permalink 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)
{
2021-01-09 11:55:07 +01:00
throw new Exception($"Użytkownik z loginem: {login} już istnieje.");
2020-12-06 18:31:05 +01:00
}
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)
{
2021-01-09 11:55:07 +01:00
throw new Exception("Nie znaleziono użytkownika.");
2020-12-06 18:31:05 +01:00
}
if(user.Password != password)
{
2021-01-09 11:55:07 +01:00
throw new Exception("Hasło niepoprawne.");
2020-12-06 18:31:05 +01:00
}
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)
{
2021-01-09 11:55:07 +01:00
throw new Exception("Nie znaleziono użytkownika.");
2020-12-18 16:04:07 +01:00
}
var userLoginTaken = await _userRepository.GetAsync(userModel.Login);
if(userLoginTaken != null && userLoginTaken.Id != user.Id)
{
2021-01-09 11:55:07 +01:00
throw new Exception("Login jest już zajęty.");
2020-12-18 16:04:07 +01:00
}
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
}
}