diff --git a/BusinessLogic/BusinessLogic.csproj b/BusinessLogic/BusinessLogic.csproj index c105ec7..ceab2d9 100644 --- a/BusinessLogic/BusinessLogic.csproj +++ b/BusinessLogic/BusinessLogic.csproj @@ -7,12 +7,13 @@ - + + diff --git a/BusinessLogic/BusinessLogic/UserLogic.cs b/BusinessLogic/BusinessLogic/UserLogic.cs index b028660..5fa0692 100644 --- a/BusinessLogic/BusinessLogic/UserLogic.cs +++ b/BusinessLogic/BusinessLogic/UserLogic.cs @@ -102,7 +102,7 @@ namespace BusinessLogic.BusinessLogic return UserConverter.ToView(user); } - public UserViewModel Login(string email, string password) + public string Login(string email, string password) { if (email is null) { @@ -120,7 +120,7 @@ namespace BusinessLogic.BusinessLogic { throw new AccountException("The passwords don't match."); } - return UserConverter.ToView(user); + return JwtProvider.Generate(user); } public void _validatePassword(string? password) diff --git a/BusinessLogic/Tools/JwtProvider.cs b/BusinessLogic/Tools/JwtProvider.cs new file mode 100644 index 0000000..e2a8758 --- /dev/null +++ b/BusinessLogic/Tools/JwtProvider.cs @@ -0,0 +1,41 @@ +using Contracts.BindingModels; +using Contracts.ViewModels; +using Microsoft.IdentityModel.Tokens; +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Security.Claims; +using System.Text; +using System.Threading.Tasks; + +namespace BusinessLogic.Tools +{ + public class JwtProvider + { + // TODO: Переместить ключ и время в надежное место + private const string _key = "secretkey_secretkey_secretkey_secretkey"; + + private const int _expiresHours = 24; + + public static string Generate(UserBindingModel user) + { + var signingCredentials = new SigningCredentials( + new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_key)), + SecurityAlgorithms.HmacSha256); + + Claim[] claims = [ + new("userId", user.Id.ToString()), + new("role", user.Role.Name) + ]; + + var token = new JwtSecurityToken(signingCredentials: signingCredentials, + expires: DateTime.UtcNow.AddHours(_expiresHours), + claims: claims); + + var stringToken = new JwtSecurityTokenHandler().WriteToken(token); + return stringToken; + } + } +} \ No newline at end of file diff --git a/Contracts/BusinessLogicContracts/IUserLogic.cs b/Contracts/BusinessLogicContracts/IUserLogic.cs index fdcc510..dc5c87a 100644 --- a/Contracts/BusinessLogicContracts/IUserLogic.cs +++ b/Contracts/BusinessLogicContracts/IUserLogic.cs @@ -12,7 +12,7 @@ namespace Contracts.BusinessLogicContracts { public interface IUserLogic { - UserViewModel Login(string email, string password); + string Login(string email, string password); UserViewModel Create(UserBindingModel model);