RegModelChanged { get; set; }
//public string PhoneNumberMask { get; set; } = "\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*(\d{1,2})";
- public string PhoneNumberMask { get; set; } = TIAMRegularExpressions.PhoneNumberMask;
+ public string PhoneNumberMask { get; set; } = AcRegExpression.PhoneNumberMask;
char Placeholder = '_';
diff --git a/TIAMSharedUI/Pages/DbTestComponent.razor b/TIAMSharedUI/Pages/DbTestComponent.razor
index 440abd62..b2220fc0 100644
--- a/TIAMSharedUI/Pages/DbTestComponent.razor
+++ b/TIAMSharedUI/Pages/DbTestComponent.razor
@@ -1,4 +1,5 @@
-@using AyCode.Utils.Extensions
+@using AyCode.Core.Extensions
+@using AyCode.Utils.Extensions
@if (Users == null)
{
diff --git a/TIAMSharedUI/TIAMSharedUI.csproj b/TIAMSharedUI/TIAMSharedUI.csproj
index 8f0f9df9..4e27b8ef 100644
--- a/TIAMSharedUI/TIAMSharedUI.csproj
+++ b/TIAMSharedUI/TIAMSharedUI.csproj
@@ -15,8 +15,8 @@
-
-
+
+
@@ -32,6 +32,9 @@
..\..\AyCode.Core\AyCode.Services.Server\bin\Debug\net8.0\AyCode.Core.dll
+
+ ..\..\AyCode.Core\AyCode.Services.Server\bin\Debug\net8.0\AyCode.Core.Server.dll
+
..\..\AyCode.Core\AyCode.Services.Server\bin\Debug\net8.0\AyCode.Entities.dll
diff --git a/TIAMWebApp/Client/TIAMWebApp.Client.csproj b/TIAMWebApp/Client/TIAMWebApp.Client.csproj
index 48a53d21..2228e98d 100644
--- a/TIAMWebApp/Client/TIAMWebApp.Client.csproj
+++ b/TIAMWebApp/Client/TIAMWebApp.Client.csproj
@@ -11,10 +11,10 @@
-
-
-
-
+
+
+
+
diff --git a/TIAMWebApp/Server/Controllers/GoogleAPIController .cs b/TIAMWebApp/Server/Controllers/GoogleAPIController .cs
index 32cb0f32..40cb4c9b 100644
--- a/TIAMWebApp/Server/Controllers/GoogleAPIController .cs
+++ b/TIAMWebApp/Server/Controllers/GoogleAPIController .cs
@@ -156,7 +156,7 @@ namespace TIAMWebApp.Server.Controllers
new LocationEx(destination1),
new LocationEx(destination2)
},
- TravelMode = TravelMode.Driving,
+ TravelMode = TravelMode.DRIVING,
};
response = await GoogleApi.GoogleMaps.DistanceMatrix.QueryAsync(request);
diff --git a/TIAMWebApp/Server/Controllers/ServiceProviderAPIController.cs b/TIAMWebApp/Server/Controllers/ServiceProviderAPIController.cs
index 3fd352f8..31d68d73 100644
--- a/TIAMWebApp/Server/Controllers/ServiceProviderAPIController.cs
+++ b/TIAMWebApp/Server/Controllers/ServiceProviderAPIController.cs
@@ -176,7 +176,7 @@ namespace TIAMWebApp.Server.Controllers
}
else
{
- var result = _adminDal.AddProduct(product);
+ var result = _adminDal.AddProductAsync(product);
return Ok(result);
}
}
diff --git a/TIAMWebApp/Server/Controllers/UserAPIController.cs b/TIAMWebApp/Server/Controllers/UserAPIController.cs
index e62232b9..6ec3d219 100644
--- a/TIAMWebApp/Server/Controllers/UserAPIController.cs
+++ b/TIAMWebApp/Server/Controllers/UserAPIController.cs
@@ -39,7 +39,7 @@ namespace TIAMWebApp.Server.Controllers
private AdminDal _adminDal;
private readonly IConfiguration _configuration;
private readonly IWebHostEnvironment _webHostEnvironment;
- readonly PasswordHasher _hasher = new();
+ //readonly PasswordHasher _hasher = new();
/*private UserModel[] users = new UserModel[]
@@ -366,7 +366,7 @@ namespace TIAMWebApp.Server.Controllers
userToCreate.Profile.Address.AddressText = null;
userToCreate.Profile.Address.Latitude = Math.Round(90 + rnd.NextDouble(), 8);
userToCreate.Profile.Address.Longitude = Math.Round(180 + rnd.NextDouble(), 8);
- result = await _adminDal.AddUser(userToCreate);
+ result = await _adminDal.AddUserAsync(userToCreate);
guestUser = await _userDal.GetUserModelDtoDetailByIdAsync(userId);
}
}
@@ -415,13 +415,13 @@ namespace TIAMWebApp.Server.Controllers
private bool VerifyPassword(string password, string hashedPassword)
{
- var isPasswordValid = _hasher.VerifyPassword(password, hashedPassword);
+ var isPasswordValid = PasswordHasher.VerifyPassword(password, hashedPassword);
return isPasswordValid;
}
private string HashPassword(string password)
{
- var hashedPassword = _hasher.HashPassword(password);
+ var hashedPassword = PasswordHasher.HashPassword(password);
return hashedPassword;
}
}
diff --git a/TIAMWebApp/Server/Services/Logins/ILoginService.cs b/TIAMWebApp/Server/Services/Logins/ILoginService.cs
new file mode 100644
index 00000000..7b673e1e
--- /dev/null
+++ b/TIAMWebApp/Server/Services/Logins/ILoginService.cs
@@ -0,0 +1,17 @@
+using AyCode.Interfaces.Server.Logins;
+using AyCode.Models.Logins;
+using AyCode.Models.Server.Logins;
+using TIAM.Entities.Addresses;
+using TIAM.Entities.Profiles;
+using TIAM.Entities.ServiceProviders;
+using TIAM.Entities.Users;
+
+namespace TIAMWebApp.Server.Services.Logins;
+
+public interface ILoginModel : IAcLoggedInModelBase
+{}
+
+public interface ILoginService : IAcLoginServiceServer
+{
+
+}
\ No newline at end of file
diff --git a/TIAMWebApp/Server/Services/Logins/LoginService.cs b/TIAMWebApp/Server/Services/Logins/LoginService.cs
new file mode 100644
index 00000000..3e5bd2c5
--- /dev/null
+++ b/TIAMWebApp/Server/Services/Logins/LoginService.cs
@@ -0,0 +1,46 @@
+using System.Reflection.Metadata.Ecma335;
+using System.Security;
+using AyCode.Core.Consts;
+using AyCode.Interfaces.Server.Logins;
+using AyCode.Models.Server.Logins;
+using AyCode.Services.Server.Logins;
+using AyCode.Utils.Extensions;
+using AyCode.Utils.Helpers;
+using TIAM.Database.DataLayers.Admins;
+using TIAM.Database.DataLayers.Users;
+using TIAM.Database.DbContexts.Admins;
+using TIAM.Database.DbContexts.Users;
+using TIAM.Entities.Addresses;
+using TIAM.Entities.Profiles;
+using TIAM.Entities.ServiceProviders;
+using TIAM.Entities.Users;
+
+namespace TIAMWebApp.Server.Services.Logins;
+
+public class LoggedInModel : AcLoggedInModelServer, ILoginModel
+{}
+
+public class LoginService(UserDal userDal, IConfiguration configuration) : AcLoginServiceServer(userDal, configuration), ILoginService
+
+{
+ public override User? Login(string email, string password, out string accessToken)
+ {
+ return base.Login(email, password, out accessToken);
+ }
+
+ public override bool Logout()
+ {
+ return base.Logout();
+ }
+
+ public override Task RegistrationAsync(string email, string password, string? phoneNumber = null)
+ {
+ return base.RegistrationAsync(email, password, phoneNumber);
+ }
+
+ public override string GenerateDynamicSalt(Guid userId)
+ {
+ return base.GenerateDynamicSalt(userId);
+ }
+}
+
\ No newline at end of file
diff --git a/TIAMWebApp/Server/TIAMWebApp.Server.csproj b/TIAMWebApp/Server/TIAMWebApp.Server.csproj
index 150fbda5..021e8187 100644
--- a/TIAMWebApp/Server/TIAMWebApp.Server.csproj
+++ b/TIAMWebApp/Server/TIAMWebApp.Server.csproj
@@ -10,15 +10,15 @@
-
-
-
-
+
+
+
+
-
-
-
+
+
+
@@ -61,6 +61,12 @@
..\..\..\AyCode.Core\AyCode.Services.Server\bin\Debug\net8.0\AyCode.Models.Server.dll
+
+ ..\..\..\AyCode.Core\AyCode.Services.Server\bin\Debug\net8.0\AyCode.Services.dll
+
+
+ ..\..\..\AyCode.Core\AyCode.Services.Server\bin\Debug\net8.0\AyCode.Services.Server.dll
+
..\..\..\AyCode.Core\AyCode.Utils\bin\Debug\net8.0\AyCode.Utils.dll
diff --git a/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj b/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj
index 878a85be..280b9ba4 100644
--- a/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj
+++ b/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj
@@ -17,11 +17,11 @@
-
+
-
-
-
+
+
+
diff --git a/TIAMWebApp/Shared/Utility/TIAMRegularExpressions.cs b/TIAMWebApp/Shared/Utility/TIAMRegularExpressions.cs
deleted file mode 100644
index 0fa784e9..00000000
--- a/TIAMWebApp/Shared/Utility/TIAMRegularExpressions.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace TIAMWebApp.Shared.Application.Utility
-{
- public static class TIAMRegularExpressions
- {
-
- public const string EmailMask = @"(\w|[.-])+@(\w|-)+\.(\w|-){2,4}";
- //public const string EmailMask = @"((\w|[.-])+@(\w|-)+\.(\w|-){2,4})?";
- public const string PhoneNumberMask = "\\+(9[976]\\d|8[987530]\\d|6[987]\\d|5[90]\\d|42\\d|3[875]\\d|2[98654321]\\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\\W*\\d\\W*\\d\\W*\\d\\W*\\d\\W*\\d\\W*\\d\\W*\\d\\W*\\d\\W*(\\d{1,2})";
-
- }
-}
From 764bc7138652df88f1d9ccfdc2b6259ea29ee8cd Mon Sep 17 00:00:00 2001
From: "jozsef.b@aycode.com" <9Rj@D}fVwBaN>
Date: Tue, 23 Apr 2024 14:46:49 +0200
Subject: [PATCH 2/4] refactoring, improvements, fixes, etc...
---
TIAM.Database.Test/UserDalTests.cs | 67 ++++--
TIAM.Database/DataLayers/Admins/AdminDal.cs | 10 +-
TIAM.Database/DataLayers/Users/UserDal.cs | 24 +--
TIAMWebApp/Client/Services/WizardProcessor.cs | 2 +-
.../Server/Controllers/EmailAPIController.cs | 3 +-
.../Server/Controllers/FileAPIController.cs | 2 +-
.../ServiceProviderAPIController.cs | 22 +-
.../Controllers/TransferDataAPIController.cs | 58 +++---
.../Server/Controllers/UserAPIController.cs | 197 +++++-------------
.../UserPermissionAPIController.cs | 8 +-
.../Server/Models/Logins/LoggedInModel.cs | 12 ++
.../Server/Services/Logins/ILoginService.cs | 6 +-
.../Server/Services/Logins/LoginService.cs | 17 +-
.../Server/Services/NoticeSenderService.cs | 6 +-
TIAMWebApp/Shared/Models/APIUrls.cs | 9 +-
.../Services/ServiceProviderDataService.cs | 2 +-
.../TIAMWebApp.Shared.Application.csproj | 7 +-
17 files changed, 189 insertions(+), 263 deletions(-)
create mode 100644 TIAMWebApp/Server/Models/Logins/LoggedInModel.cs
diff --git a/TIAM.Database.Test/UserDalTests.cs b/TIAM.Database.Test/UserDalTests.cs
index 1004c913..ae22e85e 100644
--- a/TIAM.Database.Test/UserDalTests.cs
+++ b/TIAM.Database.Test/UserDalTests.cs
@@ -1,22 +1,12 @@
-using AyCode.Database.DataLayers;
-using AyCode.Database.Tests;
-using AyCode.Database.Tests.Users;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.VisualStudio.TestPlatform.ObjectModel;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
+using AyCode.Database.Tests.Users;
using Newtonsoft.Json;
-using System.Text.Json.Serialization;
-using System.Text.Json;
+using AyCode.Core.Consts;
using TIAM.Database.DataLayers.Users;
using TIAM.Database.DbContexts.Users;
using TIAM.Entities.Profiles;
using TIAM.Entities.Users;
using TIAM.Models.Dtos.Users;
-using AyCode.Interfaces.Users.Dtos;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
-using Microsoft.Extensions.Configuration;
-using TIAM.Core.Consts;
using TIAM.Entities.ServiceProviders;
using TIAM.Entities.Addresses;
using TIAMWebApp.Server.Services.Logins;
@@ -27,7 +17,14 @@ namespace TIAM.Database.Test
[TestClass]
public class UserDalTests : AcUserDalTestBase
{
- private WebAssemblyHostConfiguration _configuration = new WebAssemblyHostConfiguration();
+ private Guid _registerUserId = Guid.Parse("1f7e0591-330b-463b-81ad-d01f2e65e23e");
+ private const string RegisterEmail = "qwerty@xxxxx.com";
+ private const string RegisterPassword = "elem'r";
+
+ private const string LoginEmail = "asdfsdf@ggggg.hu";
+ private const string LoginPassword = "alad'r";
+
+ private WebAssemblyHostConfiguration _configuration = new();
//private Mock _mockContext;
[TestInitialize]
@@ -53,27 +50,53 @@ namespace TIAM.Database.Test
//_userDal = new UserDal(_mockContext.Object);
}
- //[TestMethod]
+ [TestMethod]
public async Task RegisterUser_ReturnsUser_WhenUserExist()
{
//var a = TiamConst.ProjectIdString;
- var userId = Guid.Parse("1ded6045-1278-4b92-a10a-3eb9426e41a3");
- //await Dal.RemoveUserAsync(userId); //kitöröljük a szemetet, ha korábbról bentmaradt - J.
+ await Dal.RemoveUserAsync(_registerUserId); //kitöröljük a szemetet, ha korábbról bentmaradt - J.
- var loginService = new LoginService(Dal, new WebAssemblyHostConfiguration());
- var user = await loginService.RegistrationAsync(userId, "asdfsdf@ggggg.hu", "alad'r", null);
- Assert.IsNotNull(user);
+ var loginService = new LoginService(Dal, _configuration);
+ var errorCode = await loginService.RegistrationAsync(_registerUserId, RegisterEmail, RegisterPassword, null);
+
+ Assert.IsTrue(errorCode == AcErrorCode.Unset);
}
[TestMethod]
public void LoginUser_ReturnsUser_WhenUserExist()
{
//var a = TiamConst.ProjectIdString;
-
+
var loginService = new LoginService(Dal, _configuration);
- var user = loginService.Login("asdfsdf@ggggg.hu", "alad'r", out _);
- Assert.IsNotNull(user);
+
+ #region Valid email+password test
+ var loggedInModel = loginService.Login(LoginEmail, LoginPassword);
+
+ Assert.IsNotNull(loggedInModel);
+ Assert.IsNotNull(loggedInModel.LoggedInUser);
+ Assert.IsNotNull(loginService.LoggedInModel?.LoggedInUser);
+
+ Assert.IsTrue(loggedInModel.LoginErrorCode == AcErrorCode.Unset, $"errorCode: {loggedInModel.LoginErrorCode}");
+ Assert.IsTrue(loggedInModel.IsLoggedIn, $"loggedInModel.IsLoggedIn == false; errorCode: {loggedInModel.LoginErrorCode}");
+ Assert.IsTrue(string.Equals(loggedInModel.LoggedInUser.EmailAddress, LoginEmail, StringComparison.CurrentCultureIgnoreCase));
+ #endregion Valid email+password test
+
+ #region Wrong email test
+ loggedInModel = loginService.Login("gffsdgdfg@gu.hu", LoginPassword);
+
+ Assert.IsNotNull(loggedInModel);
+ Assert.IsFalse(loggedInModel.IsLoggedIn);
+ Assert.IsTrue(loggedInModel.LoginErrorCode == AcErrorCode.WrongLoginData);
+ #endregion Wrong email test
+
+ #region Wrong password test
+ loggedInModel = loginService.Login(LoginEmail, "fsdgfsdg");
+
+ Assert.IsNotNull(loggedInModel);
+ Assert.IsFalse(loggedInModel.IsLoggedIn);
+ Assert.IsTrue(loggedInModel.LoginErrorCode == AcErrorCode.WrongLoginData);
+ #endregion Wrong password test
}
[TestMethod]
diff --git a/TIAM.Database/DataLayers/Admins/AdminDal.cs b/TIAM.Database/DataLayers/Admins/AdminDal.cs
index ad8a8b45..7435efcb 100644
--- a/TIAM.Database/DataLayers/Admins/AdminDal.cs
+++ b/TIAM.Database/DataLayers/Admins/AdminDal.cs
@@ -123,8 +123,8 @@ namespace TIAM.Database.DataLayers.Admins
});
}
- public Task RemoveUserAsync(User user) => TransactionAsync(ctx => ctx.RemoveUserAsync(user));
- public Task RemoveUserAsync(Guid userId) => TransactionAsync(ctx => ctx.RemoveUserAsync(userId));
+ public Task RemoveUserAsync(User user) => TransactionAsync(ctx => ctx.RemoveUser(user));
+ public Task RemoveUserAsync(Guid userId) => TransactionAsync(ctx => ctx.RemoveUser(userId));
public Product? GetProductById(Guid contextId, bool includeUsers = true) => Session(ctx => ctx.GetProductById(contextId, includeUsers));
@@ -224,7 +224,7 @@ namespace TIAM.Database.DataLayers.Admins
public bool CreateProductAsync(Product product)
{
Context.CreateProduct(product);
- Console.WriteLine($"Saving product to db {product.Id}, {product.Name}, {product.ServiceProviderId}");
+ Console.WriteLine($@"Saving product to db {product.Id}, {product.Name}, {product.ServiceProviderId}");
var result = Context.SaveChangesAsync();
return result.Result > 0;
}
@@ -236,7 +236,7 @@ namespace TIAM.Database.DataLayers.Admins
public virtual Task GetServiceProviderByIdAsync(Guid id)
{
- Console.WriteLine($"Getting serviceProvider from db {id}");
+ Console.WriteLine($@"Getting serviceProvider from db {id}");
return Context.ServiceProviders.SingleOrDefaultAsync(x => x.Id == id);
}
@@ -449,7 +449,7 @@ namespace TIAM.Database.DataLayers.Admins
}
foreach (var row in result)
{
- Console.WriteLine($"GetPermissionsOfUserProductMappingsAndGroupsAsyncByContextId: {row.ContextId}, {row.SubjectId}, {row.SubjectType}, {row.Name}, {row.PermissionsValue}");
+ Console.WriteLine($@"GetPermissionsOfUserProductMappingsAndGroupsAsyncByContextId: {row.ContextId}, {row.SubjectId}, {row.SubjectType}, {row.Name}, {row.PermissionsValue}");
}
return Task.FromResult(result);
}
diff --git a/TIAM.Database/DataLayers/Users/UserDal.cs b/TIAM.Database/DataLayers/Users/UserDal.cs
index 57f9b025..c1e1528a 100644
--- a/TIAM.Database/DataLayers/Users/UserDal.cs
+++ b/TIAM.Database/DataLayers/Users/UserDal.cs
@@ -40,14 +40,14 @@ namespace TIAM.Database.DataLayers.Users
public Task GetUserByPhoneNumberAsync(string phoneNumber)
{
- Console.WriteLine($"Getting user from db {phoneNumber}");
+ Console.WriteLine($@"Getting user from db {phoneNumber}");
var phoneNumberLower = phoneNumber.ToLower();
return Context.Users.SingleOrDefaultAsync(x=>x.PhoneNumber.Equals(phoneNumberLower, StringComparison.CurrentCultureIgnoreCase));
}
public Task GetUserByEmailOrPhoneNumberAsync(string emailOrPhoneNumber)
{
- Console.WriteLine($"Getting user from db {emailOrPhoneNumber}");
+ Console.WriteLine($@"Getting user from db {emailOrPhoneNumber}");
var emailOrPhoneNumberLower = emailOrPhoneNumber.ToLower();
return Context.Users.SingleOrDefaultAsync(x=>x.EmailAddress.Equals(emailOrPhoneNumberLower, StringComparison.CurrentCultureIgnoreCase) || x.PhoneNumber.Equals(emailOrPhoneNumberLower, StringComparison.CurrentCultureIgnoreCase));
}
@@ -62,29 +62,11 @@ namespace TIAM.Database.DataLayers.Users
public async Task CreateUserAsync(User user)
{
Context.Users.Add(user);
- Console.WriteLine($"Saving user to db {user.Id}, {user.EmailAddress}, {user.PhoneNumber}, {user.Password}");
+ Console.WriteLine($@"Saving user to db {user.Id}, {user.EmailAddress}, {user.PhoneNumber}, {user.Password}");
return await Context.SaveChangesAsync() > 0;
}
- public async Task UpdateJwtRefreshTokenAsync(string email, string refreshToken)
- {
- Console.WriteLine("UserDal Update refresh token");
- var existingUser = Context.Users.FirstOrDefault(u => u.EmailAddress == email);
- if (existingUser != null)
- {
- //user.Modified = DateTime.UtcNow; //ezt nem kell megadni, a háttérben ezt magától megcsinálja a DbContextBase - J.
- existingUser.RefreshToken = refreshToken;
-
- Context.Users.Update(existingUser);
- return await Context.SaveChangesAsync() > 0;
- }
- else
- {
- throw new Exception("User not found");
- }
- }
-
public async Task UpdateUserAsync(User user)
{
var existingUser = await Context.Users.CountAsync(u => u.EmailAddress == user.EmailAddress);
diff --git a/TIAMWebApp/Client/Services/WizardProcessor.cs b/TIAMWebApp/Client/Services/WizardProcessor.cs
index 7a914030..46d42f26 100644
--- a/TIAMWebApp/Client/Services/WizardProcessor.cs
+++ b/TIAMWebApp/Client/Services/WizardProcessor.cs
@@ -35,7 +35,7 @@ namespace TIAMWebApp.Client.Services
return result as TModelType;
case "TransferWizardModel":
- Console.WriteLine("TransferWizardModel");
+ Console.WriteLine(@"TransferWizardModel");
var transferResult = await TransferDataService.CreateTransfer((TransferWizardModel)data);
return transferResult as TModelType;
diff --git a/TIAMWebApp/Server/Controllers/EmailAPIController.cs b/TIAMWebApp/Server/Controllers/EmailAPIController.cs
index d17acc15..2e415798 100644
--- a/TIAMWebApp/Server/Controllers/EmailAPIController.cs
+++ b/TIAMWebApp/Server/Controllers/EmailAPIController.cs
@@ -17,7 +17,6 @@ using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using TIAM.Database.DataLayers.Users;
-using AyCode.Utils.Helpers;
using TIAM.Entities.Users;
using TIAMWebApp.Server.ModelsTIAMWebApp.Shared.Application.Models;
using TIAMWebApp.Shared.Application.Utility;
@@ -66,7 +65,7 @@ namespace TIAMWebApp.Server.Controllers
if (SerializedMessageSenderModel.MessageType == MessageTypesEnum.email && SerializedMessageSenderModel.Message is EmailMessage)
{
- Console.WriteLine($"EmailMessage!!!");
+ Console.WriteLine($@"EmailMessage!!!");
var result = await _messageSenderService.SendMessageAsync(SerializedMessageSenderModel.Message, (int)SerializedMessageSenderModel.MessageType);
//_adminDal.AddEmailMessageAsync((TIAM.Entities.Emails.EmailMessage)SerializedMessageSenderModel.Message);
diff --git a/TIAMWebApp/Server/Controllers/FileAPIController.cs b/TIAMWebApp/Server/Controllers/FileAPIController.cs
index 6769f951..ea35055c 100644
--- a/TIAMWebApp/Server/Controllers/FileAPIController.cs
+++ b/TIAMWebApp/Server/Controllers/FileAPIController.cs
@@ -42,7 +42,7 @@ namespace TIAMWebApp.Server.Controllers
[Route(APIUrls.UploadImageRouteName)]
public ActionResult UploadImage([FromForm] IFormFile file)
{
- Console.WriteLine($"Upload file called: {file.FileName}");
+ Console.WriteLine($@"Upload file called: {file.FileName}");
if (file == null || file.Length == 0)
return BadRequest("File not selected");
diff --git a/TIAMWebApp/Server/Controllers/ServiceProviderAPIController.cs b/TIAMWebApp/Server/Controllers/ServiceProviderAPIController.cs
index 31d68d73..ba4cd414 100644
--- a/TIAMWebApp/Server/Controllers/ServiceProviderAPIController.cs
+++ b/TIAMWebApp/Server/Controllers/ServiceProviderAPIController.cs
@@ -42,7 +42,7 @@ namespace TIAMWebApp.Server.Controllers
[EndpointSummary("Create assigned user")]
public async Task CreateServiceProvider([FromBody] ServiceProviderModel serializedServiceProviderModel)
{
- Console.WriteLine("CreateUser called");
+ Console.WriteLine(@"CreateUser called");
if (serializedServiceProviderModel == null)
{
return BadRequest("SerializedLoginModel is required");
@@ -72,7 +72,7 @@ namespace TIAMWebApp.Server.Controllers
else
{
- Console.WriteLine($"ServiceProvider to be created: {id}, {name}, {ownerId}");
+ Console.WriteLine($@"ServiceProvider to be created: {id}, {name}, {ownerId}");
await _adminDal.CreateServiceProviderAsync(new TiamServiceProvider(id, name, ownerId, Guid.NewGuid()));
}
@@ -99,7 +99,7 @@ namespace TIAMWebApp.Server.Controllers
[Route(APIUrls.GetServiceProviderByIdRouteName)]
public async Task GetServiceProviderById([FromBody] Guid id)
{
- Console.WriteLine($"GetServiceProviderById called with id: {id}");
+ Console.WriteLine($@"GetServiceProviderById called with id: {id}");
return await _adminDal.GetServiceProviderByIdAsync(id);
}
@@ -111,7 +111,7 @@ namespace TIAMWebApp.Server.Controllers
[Tags("Finished", "ServiceProvider")]
public async Task> GetServiceProvidersByOwnerId([FromBody] Guid ownerId)
{
- Console.WriteLine($"GetServiceProvidersByOwnerId called with ownerId: {ownerId}");
+ Console.WriteLine($@"GetServiceProvidersByOwnerId called with ownerId: {ownerId}");
var serviceProviders = await _adminDal.GetServiceProvidersAsync();
@@ -136,7 +136,7 @@ namespace TIAMWebApp.Server.Controllers
}
else
{
- Console.WriteLine($"CreateUserProductMappings called with ownerId: {createUserProductMappingModel.ContextId}, {createUserProductMappingModel.ContextId}");
+ Console.WriteLine($@"CreateUserProductMappings called with ownerId: {createUserProductMappingModel.ContextId}, {createUserProductMappingModel.ContextId}");
var userProductMapping = new UserProductMapping(createUserProductMappingModel.ContextId, createUserProductMappingModel.ContextId);
@@ -152,7 +152,7 @@ namespace TIAMWebApp.Server.Controllers
[Route(APIUrls.GetUserProductMappingsForProductRouteName)]
public async Task> GetUserProductMappingsForProduct(Guid serviceProviderId)
{
- Console.WriteLine($"GetUserProductMappingsForServiceProvider called with serviceProviderId: {serviceProviderId}");
+ Console.WriteLine($@"GetUserProductMappingsForServiceProvider called with serviceProviderId: {serviceProviderId}");
var userProductMappingDictionary = new Dictionary();
@@ -169,7 +169,7 @@ namespace TIAMWebApp.Server.Controllers
[Tags("In-Progress", "Product")]
public async Task AddProduct([FromBody] Product product)
{
- Console.WriteLine("AddProduct called");
+ Console.WriteLine(@"AddProduct called");
if (product == null)
{
return BadRequest("Product is required");
@@ -183,11 +183,11 @@ namespace TIAMWebApp.Server.Controllers
[AllowAnonymous]
[HttpPost]
- [Route(APIUrls.GetQRCodeByProductIdRouteName)]
+ [Route(APIUrls.GetQrCodeByProductIdRouteName)]
[Tags("In-Progress", "Product")]
public async Task GetQRCodeByProductId([FromBody] Guid productId)
{
- Console.WriteLine("GetQRCode called");
+ Console.WriteLine(@"GetQRCode called");
if (productId == Guid.Empty)
{
return BadRequest("Product is required");
@@ -202,7 +202,7 @@ namespace TIAMWebApp.Server.Controllers
//Bitmap qrCodeImage = qrCode.GetGraphic(20);
var rootpath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "assets");
var qrCodeImage = qrCode.GetGraphic(20, Color.DarkMagenta, Color.White, (Bitmap)Bitmap.FromFile(rootpath + "/myimage.png"));
- Console.WriteLine($"qrCodeLogo: {rootpath}/myimage.png");
+ Console.WriteLine($@"qrCodeLogo: {rootpath}/myimage.png");
var ms = new MemoryStream();
qrCodeImage.Save(ms, ImageFormat.Jpeg);
var byteImage = ms.ToArray();
@@ -219,7 +219,7 @@ namespace TIAMWebApp.Server.Controllers
[Tags("In-Progress", "Product")]
public IActionResult GetProductsByServiceProviderId([FromBody] Guid serviceProviderId)
{
- Console.WriteLine($"GetProductsByServiceProviderId called with serviceProviderId: {serviceProviderId}");
+ Console.WriteLine($@"GetProductsByServiceProviderId called with serviceProviderId: {serviceProviderId}");
if (serviceProviderId == Guid.Empty)
{
diff --git a/TIAMWebApp/Server/Controllers/TransferDataAPIController.cs b/TIAMWebApp/Server/Controllers/TransferDataAPIController.cs
index 3f00ce09..7545b7a5 100644
--- a/TIAMWebApp/Server/Controllers/TransferDataAPIController.cs
+++ b/TIAMWebApp/Server/Controllers/TransferDataAPIController.cs
@@ -86,7 +86,7 @@ namespace TIAMWebApp.Server.Controllers
[Route(APIUrls.CreateTransferDestinationRouteName)]
public async Task CreateTransferDestination([FromBody] JsonElement serializedTransferDestinationModel)
{
- Console.WriteLine("CreateTransferDestination called!");
+ Console.WriteLine(@"CreateTransferDestination called!");
if (string.IsNullOrEmpty(serializedTransferDestinationModel.GetRawText()))
{
return BadRequest("SerializedTramsferDestinationWizardModel is required");
@@ -108,16 +108,16 @@ namespace TIAMWebApp.Server.Controllers
}
else
{
- Console.WriteLine($"TransferDestination to be created: {id}");
- Console.WriteLine($"TransferDestination to be created: {transferDestination.AddressId}");
- Console.WriteLine($"TransferDestination to be created: {transferDestination.Name}");
- Console.WriteLine($"TransferDestination to be created: {transferDestination.Price}");
- Console.WriteLine($"TransferDestination to be created: {transferDestination.Price2}");
- Console.WriteLine($"TransferDestination to be created: {transferDestination.Price3}");
- Console.WriteLine($"TransferDestination to be created: {transferDestination.ExtraPrice}");
+ Console.WriteLine($@"TransferDestination to be created: {id}");
+ Console.WriteLine($@"TransferDestination to be created: {transferDestination.AddressId}");
+ Console.WriteLine($@"TransferDestination to be created: {transferDestination.Name}");
+ Console.WriteLine($@"TransferDestination to be created: {transferDestination.Price}");
+ Console.WriteLine($@"TransferDestination to be created: {transferDestination.Price2}");
+ Console.WriteLine($@"TransferDestination to be created: {transferDestination.Price3}");
+ Console.WriteLine($@"TransferDestination to be created: {transferDestination.ExtraPrice}");
//Console.WriteLine($"TransferDestination to be created: {transferDestination.ExtraPriceType}");
- Console.WriteLine($"TransferDestination to be created: {transferDestination.AddressString}");
- Console.WriteLine($"TransferDestination to be created: {transferDestination.Description}");
+ Console.WriteLine($@"TransferDestination to be created: {transferDestination.AddressString}");
+ Console.WriteLine($@"TransferDestination to be created: {transferDestination.Description}");
//await _transferDestinationDal.Context.TransferDestinations.AddAsync(transferDestination);
await _adminDal.AddTransferDestinationAsync(transferDestination);
@@ -140,18 +140,18 @@ namespace TIAMWebApp.Server.Controllers
[Route(APIUrls.UpdateTransferDestinationRouteName)]
public async Task UpdateTransferDestination([FromBody]JsonElement serializedTransferDestination)
{
- Console.WriteLine("UpdateTransferDestination called!");
+ Console.WriteLine(@"UpdateTransferDestination called!");
if (string.IsNullOrEmpty(serializedTransferDestination.GetRawText()))
{
- Console.WriteLine("Bad request!");
+ Console.WriteLine(@"Bad request!");
return BadRequest("SerializedTramsferDestinationWizardModel is required");
}
else
{
- Console.WriteLine("Serialized model not empty!");
+ Console.WriteLine(@"Serialized model not empty!");
TransferDestination? transferDestination = JObject.Parse(serializedTransferDestination.GetRawText()).ToObject();
- Console.WriteLine($"TransferDestination to be updated: {serializedTransferDestination.GetRawText()}");
- Console.WriteLine($"TransferDestination to be updated: {transferDestination.AddressString}");
+ Console.WriteLine($@"TransferDestination to be updated: {serializedTransferDestination.GetRawText()}");
+ Console.WriteLine($@"TransferDestination to be updated: {transferDestination.AddressString}");
if (transferDestination != null)
@@ -162,20 +162,20 @@ namespace TIAMWebApp.Server.Controllers
if (transferDestination.Id == Guid.Empty || string.IsNullOrEmpty(transferDestination.Name) || string.IsNullOrEmpty(transferDestination.AddressString))
{
- Console.WriteLine("Serialized model not empty, but bad request!");
+ Console.WriteLine(@"Serialized model not empty, but bad request!");
return BadRequest("Invalid request");
}
else
{
- Console.WriteLine($"TransferDestination to be updated: {transferDestination.Id}");
- Console.WriteLine($"TransferDestination to be updated new name: {transferDestination.Name}");
- Console.WriteLine($"TransferDestination to be updated new price: {transferDestination.Price}");
+ Console.WriteLine($@"TransferDestination to be updated: {transferDestination.Id}");
+ Console.WriteLine($@"TransferDestination to be updated new name: {transferDestination.Name}");
+ Console.WriteLine($@"TransferDestination to be updated new price: {transferDestination.Price}");
//Console.WriteLine($"TransferDestination to be updated new price: {transferDestination.Price2}");
//Console.WriteLine($"TransferDestination to be updated new price: {transferDestination.Price3}");
//Console.WriteLine($"TransferDestination to be updated new priceType: {transferDestination.PriceType}");
- Console.WriteLine($"TransferDestination to be updated new address: {transferDestination.AddressString}");
- Console.WriteLine($"TransferDestination to be updated new description: {transferDestination.Description}");
+ Console.WriteLine($@"TransferDestination to be updated new address: {transferDestination.AddressString}");
+ Console.WriteLine($@"TransferDestination to be updated new description: {transferDestination.Description}");
//var dbTransferDestinationJson = _adminDal.GetTransferDestinationJsonById(transferDestination.Id);
//Console.WriteLine($"TransferDestination JSON to be updated: {dbTransferDestinationJson}");
@@ -216,7 +216,7 @@ namespace TIAMWebApp.Server.Controllers
[Route(APIUrls.CreateTransferRouteName)]
public async Task CreateTransfer([FromBody] JsonElement serializedTransferModel)
{
- Console.WriteLine("CreateTransfer called!");
+ Console.WriteLine(@"CreateTransfer called!");
if (string.IsNullOrEmpty(serializedTransferModel.GetRawText()))
{
return BadRequest("SerializedTramsferDestinationWizardModel is required");
@@ -238,11 +238,11 @@ namespace TIAMWebApp.Server.Controllers
}
else
{
- Console.WriteLine($"TransferDestination to be created: {id}");
- Console.WriteLine($"TransferDestination to be created: {transfer.FromAddress}");
- Console.WriteLine($"TransferDestination to be created: {transfer.ToAddress}");
- Console.WriteLine($"TransferDestination to be created: {transfer.ProductId}");
- Console.WriteLine($"TransferDestination to be created: {transfer.Price}");
+ Console.WriteLine($@"TransferDestination to be created: {id}");
+ Console.WriteLine($@"TransferDestination to be created: {transfer.FromAddress}");
+ Console.WriteLine($@"TransferDestination to be created: {transfer.ToAddress}");
+ Console.WriteLine($@"TransferDestination to be created: {transfer.ProductId}");
+ Console.WriteLine($@"TransferDestination to be created: {transfer.Price}");
var from = await _adminDal.Context.TransferDestinations.FirstOrDefaultAsync(x => x.AddressString == transfer.FromAddress);
var to = await _adminDal.Context.TransferDestinations.FirstOrDefaultAsync(x => x.AddressString == transfer.ToAddress);
@@ -273,14 +273,14 @@ namespace TIAMWebApp.Server.Controllers
[Route(APIUrls.CreateTransfersRouteName)]
public async Task CreateTransfers([FromBody] JsonElement serializedTransferModel)
{
- Console.WriteLine("CreateTransfers called!");
+ Console.WriteLine(@"CreateTransfers called!");
if (string.IsNullOrEmpty(serializedTransferModel.GetRawText()))
{
return BadRequest("SerializedTramsferDestinationWizardModel is required");
}
else
{
- Console.WriteLine($"Serialized model: {serializedTransferModel.GetRawText()}");
+ Console.WriteLine($@"Serialized model: {serializedTransferModel.GetRawText()}");
var settings = new JsonSerializerSettings
{
diff --git a/TIAMWebApp/Server/Controllers/UserAPIController.cs b/TIAMWebApp/Server/Controllers/UserAPIController.cs
index 6ec3d219..1492aa17 100644
--- a/TIAMWebApp/Server/Controllers/UserAPIController.cs
+++ b/TIAMWebApp/Server/Controllers/UserAPIController.cs
@@ -18,15 +18,16 @@ using AyCode.Core.Logger;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using TIAM.Database.DataLayers.Users;
-using AyCode.Utils.Helpers;
using TIAM.Entities.Users;
using TIAM.Models.Dtos.Users;
using TIAMWebApp.Server.ModelsTIAMWebApp.Shared.Application.Models;
using TIAMWebApp.Shared.Application.Utility;
using TIAM.Database.DataLayers.Admins;
using System;
+using AyCode.Core.Helpers;
using TIAM.Entities.Profiles;
using TIAM.Entities.Addresses;
+using TIAMWebApp.Server.Services.Logins;
namespace TIAMWebApp.Server.Controllers
{
@@ -35,6 +36,7 @@ namespace TIAMWebApp.Server.Controllers
[Route("api/v1/[controller]")]
public class UserAPIController : ControllerBase
{
+ private LoginService _loginService;
private UserDal _userDal;
private AdminDal _adminDal;
private readonly IConfiguration _configuration;
@@ -58,105 +60,54 @@ namespace TIAMWebApp.Server.Controllers
_webHostEnvironment = webHostEnvironment;
_userDal = userDal;
_adminDal = adminDal;
+
+ _loginService = new LoginService(_userDal, _configuration);
}
[AllowAnonymous]
[HttpPost]
- [Route(APIUrls.AuthenticateUserRouteName)]
- public async Task AuthenticateUser([FromBody] JsonElement SerializedLoginModel)
+ [Route(APIUrls.LogoutUserRouteName)]
+ public IActionResult LogoutUser()
{
- Console.WriteLine("AuthenticateUser called");
- var authenticateUser = JObject.Parse(SerializedLoginModel.GetRawText()).ToObject();
+ _loginService.Logout();
- //check if userModel exists
- //var userModel = await _userManager.FindByNameAsync(authenticateUser.UserName);
- //if (userModel == null) return Unauthorized();
- Console.WriteLine(authenticateUser.Email);
-
- //var dbUser = await GetUserByEmail(authenticateUser.Email);
- var dbUser = await _userDal.GetUserByEmailAsync(authenticateUser.Email);
-
- //check if password is valid
- //bool isValidUser = await _userManager.CheckPasswordAsync(userModel, authenticateUser.Password);
-
- //mocking
- if (dbUser is null)
- {
- return Unauthorized();
- }
- else
- {
- var isValidUser = false;
-
- if (dbUser.Password == authenticateUser.Password)
- {
- Console.WriteLine("Password is valid");
- isValidUser = true;
-
- }
-
- if (isValidUser)
- {
- Console.WriteLine("UserModel authenticated, let's start JWT");
- var accessToken = GenerateAccessToken(dbUser);
- Console.WriteLine("Generate refresh token");
- var refreshToken = GenerateRefreshToken();
- dbUser.RefreshToken = refreshToken;
- //Update userModel with refreshToken!!
- await _userDal.UpdateJwtRefreshTokenAsync(dbUser.EmailAddress, dbUser.RefreshToken);
-
- var response = new MainResponse
- {
- Content = new AuthenticationResponse
- {
- RefreshToken = refreshToken,
- AccessToken = accessToken
- },
- IsSuccess = true,
- ErrorMessage = ""
- };
- return Ok(response);
- }
- else
- {
- Console.WriteLine("User not valid");
- return Unauthorized();
- }
- }
+ //TODO: Implementálni a Logout-ot kliens és szerver oldalon is! - J.
+ return new RedirectToActionResult(APIUrls.BaseUrlWithSlashAndVersion, null, null);
}
- private string GenerateAccessToken(User user)
+ [AllowAnonymous]
+ [HttpPost]
+ [Route(APIUrls.AuthenticateUserRouteName)]
+ public async Task AuthenticateUser([FromBody] JsonElement serializedLoginModel)
{
- var tokenHandler = new JwtSecurityTokenHandler();
- Console.WriteLine("----------------------------------------------------------");
+ Console.WriteLine(@"AuthenticateUser called");
+ var authenticateUser = JObject.Parse(serializedLoginModel.GetRawText()).ToObject();
- if (_configuration["JWT:Key"] == null)
- throw new SecurityTokenException("Token is null");
+ if (authenticateUser == null) throw new NullReferenceException("authenticateUser == null");
- var keyDetail = Encoding.UTF8.GetBytes(_configuration["JWT:Key"] ?? string.Empty);
- Console.WriteLine(_configuration["JWT:Key"]);
+ Console.WriteLine(authenticateUser.Email);
- var claims = new List
+ var loggedInModel = _loginService.Login(authenticateUser.Email, authenticateUser.Password);
+ if (loggedInModel.IsLoggedIn)
{
- new(ClaimTypes.NameIdentifier, user.Id.ToString()),
- new(ClaimTypes.Email, user.EmailAddress)
- };
+ var response = new MainResponse
+ {
+ Content = new AuthenticationResponse
+ {
+ RefreshToken = loggedInModel.AccessToken,
+ AccessToken = loggedInModel.LoggedInUser.RefreshToken
+ },
- var tokenDescriptor = new SecurityTokenDescriptor
- {
- Audience = _configuration["JWT:Audience"],
- Issuer = _configuration["JWT:Issuer"],
- Expires = DateTime.UtcNow.AddMinutes(30),
- Subject = new ClaimsIdentity(claims),
- SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(keyDetail), SecurityAlgorithms.HmacSha256Signature)
- };
+ IsSuccess = true,
+ ErrorMessage = ""
+ };
- var token = tokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken;
- var writtenToken = tokenHandler.WriteToken(token);
- Console.WriteLine(writtenToken);
+ return Ok(response);
+ }
- return writtenToken;
+ Console.WriteLine(@"User not valid! errorCode: " + loggedInModel.LoginErrorCode);
+ return Unauthorized();
}
[AllowAnonymous]
@@ -164,21 +115,21 @@ namespace TIAMWebApp.Server.Controllers
[Route(APIUrls.RefreshTokenRouteName)]
public async Task RefreshToken(RefreshTokenRequest? refreshTokenRequest)
{
- Console.WriteLine("RefreshToken called");
+ Console.WriteLine(@"RefreshToken called");
var response = new MainResponse();
if (refreshTokenRequest is null)
{
- Console.WriteLine("RefreshTokenRequest is null");
+ Console.WriteLine(@"RefreshTokenRequest is null");
response.ErrorMessage = "Invalid request";
return BadRequest(response);
}
- var principal = GetPrincipalFromExpiredToken(refreshTokenRequest.AccessToken);
+ var principal = _loginService.GetPrincipalFromExpiredToken(refreshTokenRequest.AccessToken);
if (principal != null)
{
- Console.WriteLine("Principal is not null");
+ Console.WriteLine(@"Principal is not null");
var email = principal.Claims.FirstOrDefault(f => f.Type == ClaimTypes.Email);
//var userModel = await _userManager.FindByEmailAsync(email?.Value);
@@ -189,7 +140,7 @@ namespace TIAMWebApp.Server.Controllers
{
//get user from db
dbUser = await _userDal.GetUserByEmailAsync(email.Value);
- Console.WriteLine("DbUser email: " + dbUser?.EmailAddress);
+ Console.WriteLine($@"DbUser email: {dbUser?.EmailAddress}");
}
//mocking - update userModel with new refreshToken so it returns true after the check below
@@ -198,12 +149,12 @@ namespace TIAMWebApp.Server.Controllers
if (dbUser is null || dbUser.RefreshToken != refreshTokenRequest.RefreshToken)
{
response.ErrorMessage = "Invalid Request";
- Console.WriteLine($"{dbUser?.RefreshToken}, {refreshTokenRequest.RefreshToken}");
+ Console.WriteLine($@"{dbUser?.RefreshToken}, {refreshTokenRequest.RefreshToken}");
return BadRequest(response);
}
- var newAccessToken = GenerateAccessToken(dbUser);
- var refreshToken = GenerateRefreshToken();
+ var newAccessToken = _loginService.GenerateAccessToken(dbUser);
+ var refreshToken = _loginService.GenerateRefreshToken();
//mocking - update userModel with new refreshToken
dbUser.RefreshToken = refreshToken;
@@ -220,56 +171,16 @@ namespace TIAMWebApp.Server.Controllers
return Ok(response);
}
- Console.WriteLine("Principal is null");
+ Console.WriteLine(@"Principal is null");
return NotFound("Invalid Token Found");
}
- private ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
- {
- var tokenHandler = new JwtSecurityTokenHandler();
-
- if (_configuration["JWT:Key"] == null)
- throw new SecurityTokenException("Token is null");
-
- var keyDetail = Encoding.UTF8.GetBytes(_configuration["JWT:Key"] ?? string.Empty);
-
- var tokenValidationParameter = new TokenValidationParameters
- {
- ValidateIssuer = false,
- ValidateAudience = false,
- ValidateLifetime = false,
- ValidateIssuerSigningKey = true,
- ValidIssuer = _configuration["JWT:Issuer"],
- ValidAudience = _configuration["JWT:Audience"],
- IssuerSigningKey = new SymmetricSecurityKey(keyDetail),
- };
-
- var principal = tokenHandler.ValidateToken(token, tokenValidationParameter, out var securityToken);
-
- if (securityToken is not JwtSecurityToken jwtSecurityToken || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
- throw new SecurityTokenException("Invalid token");
-
- return principal;
- }
-
- private string GenerateRefreshToken()
- {
-
- var randomNumber = new byte[32];
- using (var rng = RandomNumberGenerator.Create())
- {
- rng.GetBytes(randomNumber);
- return Convert.ToBase64String(randomNumber);
- }
- }
-
-
[AllowAnonymous]
[HttpPost]
[Route("CreateUser")]
public async Task CreateUser([FromBody] JsonElement SerializedRegistrationModel)
{
- Console.WriteLine("CreateUser called");
+ Console.WriteLine(@"CreateUser called");
if (string.IsNullOrEmpty(SerializedRegistrationModel.GetRawText()))
{
@@ -297,10 +208,10 @@ namespace TIAMWebApp.Server.Controllers
}
else
{
- Console.WriteLine($"User to be created: {userId}");
- Console.WriteLine($"User to be created: {email}");
- Console.WriteLine($"User to be created: {phoneNumber}");
- Console.WriteLine($"User to be created: {password}");
+ Console.WriteLine($@"User to be created: {userId}");
+ Console.WriteLine($@"User to be created: {email}");
+ Console.WriteLine($@"User to be created: {phoneNumber}");
+ Console.WriteLine($@"User to be created: {password}");
await _userDal.CreateUserAsync(new User(userId, email, phoneNumber, password));
}
@@ -315,7 +226,7 @@ namespace TIAMWebApp.Server.Controllers
[Route(APIUrls.CreateGuestUserRouteName)]
public async Task CreateGuestUser([FromBody] JsonElement SerializedRegistrationModel)
{
- Console.WriteLine("CreateGuestUser called");
+ Console.WriteLine(@"CreateGuestUser called");
bool result = false;
UserModelDtoDetail? guestUser = null;
@@ -347,10 +258,10 @@ namespace TIAMWebApp.Server.Controllers
}
else
{
- Console.WriteLine($"User to be created: {userId}");
- Console.WriteLine($"User to be created: {email}");
- Console.WriteLine($"User to be created: {phoneNumber}");
- Console.WriteLine($"User to be created: {password}");
+ Console.WriteLine($@"User to be created: {userId}");
+ Console.WriteLine($@"User to be created: {email}");
+ Console.WriteLine($@"User to be created: {phoneNumber}");
+ Console.WriteLine($@"User to be created: {password}");
User userToCreate = new(userId, email, phoneNumber, password);
userToCreate.ProfileId = Guid.NewGuid();
@@ -391,7 +302,7 @@ namespace TIAMWebApp.Server.Controllers
public Task GetUserByEmail(string email)
{
Logger.Info($"GetUserByEmail called with email: {email}");
- Console.WriteLine($"GetUserByEmail called with email: {email}");
+ Console.WriteLine($@"GetUserByEmail called with email: {email}");
return _userDal.GetUserModelDtoByEmailAsync(email);
}
diff --git a/TIAMWebApp/Server/Controllers/UserPermissionAPIController.cs b/TIAMWebApp/Server/Controllers/UserPermissionAPIController.cs
index 9d1f8a3e..fe7508ea 100644
--- a/TIAMWebApp/Server/Controllers/UserPermissionAPIController.cs
+++ b/TIAMWebApp/Server/Controllers/UserPermissionAPIController.cs
@@ -46,7 +46,7 @@ namespace TIAMWebApp.Server.Controllers
}
else
{
- Console.WriteLine($"GetPermissionContextByUserId called with userId: {userId}");
+ Console.WriteLine($@"GetPermissionContextByUserId called with userId: {userId}");
//List response = await _serviceProviderDal.GetPermissionModelByUserIdAsync(userId);
//return Ok(response);
@@ -68,7 +68,7 @@ namespace TIAMWebApp.Server.Controllers
else
{
- Console.WriteLine($"GetPermissionsForContextByContextId called with contextId: {contextId}");
+ Console.WriteLine($@"GetPermissionsForContextByContextId called with contextId: {contextId}");
Dictionary permissionsDictionary = new Dictionary();
var permissions = await _adminDal.GetPermissionsForContextByContextIdAsync(contextId);
return Ok(permissions);
@@ -82,7 +82,7 @@ namespace TIAMWebApp.Server.Controllers
[Route("AssignPermissionToUserForContext")]
public async Task AssignPermissionToUserForContext(AssignPermissionModel assignPermissionModel)
{
- Console.WriteLine("AssignPermissionToUserForContext called");
+ Console.WriteLine(@"AssignPermissionToUserForContext called");
if (assignPermissionModel == null)
{
return BadRequest("ContextId and UserId are required");
@@ -116,7 +116,7 @@ namespace TIAMWebApp.Server.Controllers
[Route("CreatePermissionType")]
public async Task CreatePermissionType(string name, Guid contextId)
{
- Console.WriteLine("CreatePermissionType called");
+ Console.WriteLine(@"CreatePermissionType called");
if (String.IsNullOrEmpty(name) || contextId == Guid.Empty)
{
return BadRequest("SerializedPermissionTypeModel is required");
diff --git a/TIAMWebApp/Server/Models/Logins/LoggedInModel.cs b/TIAMWebApp/Server/Models/Logins/LoggedInModel.cs
new file mode 100644
index 00000000..59043b4b
--- /dev/null
+++ b/TIAMWebApp/Server/Models/Logins/LoggedInModel.cs
@@ -0,0 +1,12 @@
+using AyCode.Models.Server.Logins;
+using TIAM.Entities.Addresses;
+using TIAM.Entities.Profiles;
+using TIAM.Entities.ServiceProviders;
+using TIAM.Entities.Users;
+using TIAMWebApp.Server.Services.Logins;
+
+namespace TIAMWebApp.Server.Models.Logins;
+
+public class LoggedInModel : AcLoggedInModelServer, ILoginModel
+{
+}
\ No newline at end of file
diff --git a/TIAMWebApp/Server/Services/Logins/ILoginService.cs b/TIAMWebApp/Server/Services/Logins/ILoginService.cs
index 7b673e1e..7c34cdc6 100644
--- a/TIAMWebApp/Server/Services/Logins/ILoginService.cs
+++ b/TIAMWebApp/Server/Services/Logins/ILoginService.cs
@@ -1,17 +1,17 @@
using AyCode.Interfaces.Server.Logins;
-using AyCode.Models.Logins;
using AyCode.Models.Server.Logins;
using TIAM.Entities.Addresses;
using TIAM.Entities.Profiles;
using TIAM.Entities.ServiceProviders;
using TIAM.Entities.Users;
+using TIAMWebApp.Server.Models.Logins;
namespace TIAMWebApp.Server.Services.Logins;
-public interface ILoginModel : IAcLoggedInModelBase
+public interface ILoginModel : IAcLoggedInModelBase
{}
-public interface ILoginService : IAcLoginServiceServer
+public interface ILoginService : IAcLoginServiceServer
{
}
\ No newline at end of file
diff --git a/TIAMWebApp/Server/Services/Logins/LoginService.cs b/TIAMWebApp/Server/Services/Logins/LoginService.cs
index 3e5bd2c5..c103d464 100644
--- a/TIAMWebApp/Server/Services/Logins/LoginService.cs
+++ b/TIAMWebApp/Server/Services/Logins/LoginService.cs
@@ -2,10 +2,8 @@
using System.Security;
using AyCode.Core.Consts;
using AyCode.Interfaces.Server.Logins;
-using AyCode.Models.Server.Logins;
using AyCode.Services.Server.Logins;
using AyCode.Utils.Extensions;
-using AyCode.Utils.Helpers;
using TIAM.Database.DataLayers.Admins;
using TIAM.Database.DataLayers.Users;
using TIAM.Database.DbContexts.Admins;
@@ -14,18 +12,16 @@ using TIAM.Entities.Addresses;
using TIAM.Entities.Profiles;
using TIAM.Entities.ServiceProviders;
using TIAM.Entities.Users;
+using TIAMWebApp.Server.Models.Logins;
namespace TIAMWebApp.Server.Services.Logins;
-public class LoggedInModel : AcLoggedInModelServer, ILoginModel
-{}
-
public class LoginService(UserDal userDal, IConfiguration configuration) : AcLoginServiceServer(userDal, configuration), ILoginService
{
- public override User? Login(string email, string password, out string accessToken)
+ public override LoggedInModel Login(string? email, string? password)
{
- return base.Login(email, password, out accessToken);
+ return base.Login(email, password);
}
public override bool Logout()
@@ -33,14 +29,9 @@ public class LoginService(UserDal userDal, IConfiguration configuration) : AcLog
return base.Logout();
}
- public override Task RegistrationAsync(string email, string password, string? phoneNumber = null)
+ public override Task RegistrationAsync(string email, string password, string? phoneNumber = null)
{
return base.RegistrationAsync(email, password, phoneNumber);
}
-
- public override string GenerateDynamicSalt(Guid userId)
- {
- return base.GenerateDynamicSalt(userId);
- }
}
\ No newline at end of file
diff --git a/TIAMWebApp/Server/Services/NoticeSenderService.cs b/TIAMWebApp/Server/Services/NoticeSenderService.cs
index c0a71416..b5d78616 100644
--- a/TIAMWebApp/Server/Services/NoticeSenderService.cs
+++ b/TIAMWebApp/Server/Services/NoticeSenderService.cs
@@ -29,7 +29,7 @@ namespace TIAMWebApp.Server.Services
case (int)MessageTypesEnum.email:
if (message is EmailMessage emailMessage)
{
- Console.WriteLine($"EmailMessage!!!");
+ Console.WriteLine($@"EmailMessage!!!");
// Access DerivedClass properties
var _subject = emailMessage.Subject;
result = await SendMailWithSendgrid(emailMessage);
@@ -60,8 +60,8 @@ namespace TIAMWebApp.Server.Services
public async Task SendMailWithSendgrid(EmailMessage message)
{
- Console.WriteLine($"Sender: {message.SenderId}");
- Console.WriteLine($"Message: {message.Message}");
+ Console.WriteLine($@"Sender: {message.SenderId}");
+ Console.WriteLine($@"Message: {message.Message}");
//resolve user!!!
var senderUser = _userDal.Context.Users.FirstOrDefault(x => x.Id == message.SenderId);
var receiverUser = _userDal.Context.Users.FirstOrDefault(x => x.Id == message.ReceiverId);
diff --git a/TIAMWebApp/Shared/Models/APIUrls.cs b/TIAMWebApp/Shared/Models/APIUrls.cs
index 05ff6d0e..de75ba2e 100644
--- a/TIAMWebApp/Shared/Models/APIUrls.cs
+++ b/TIAMWebApp/Shared/Models/APIUrls.cs
@@ -33,7 +33,10 @@ namespace TIAMWebApp.Shared.Application.Models
public const string AuthenticateUserRouteName = "AuthenticateUser";
public const string AuthenticateUser = UserAPI + AuthenticateUserRouteName;
-
+
+ public const string LogoutUserRouteName = "LogoutUser";
+ public const string LogoutUser = UserAPI + LogoutUserRouteName;
+
public const string CreateUserRouteName = "CreateUser";
public const string CreateUser = UserAPI + CreateUserRouteName;
@@ -92,8 +95,8 @@ namespace TIAMWebApp.Shared.Application.Models
public const string GetServiceProvidersByOwnerIdRouteName = "GetServiceProvidersByOwnerId";
public const string GetServiceProvidersByOwnerId = ServiceProviderAPI+GetServiceProvidersByOwnerIdRouteName;
- public const string GetQRCodeByProductIdRouteName = "GetQRCodeByProductId";
- public const string GetQRCodeByProductId = ServiceProviderAPI+GetQRCodeByProductIdRouteName;
+ public const string GetQrCodeByProductIdRouteName = "GetQRCodeByProductId";
+ public const string GetQrCodeByProductId = ServiceProviderAPI+GetQrCodeByProductIdRouteName;
public const string AddProductRouteName = "AddProduct";
public const string AddProductRouteUrl = ServiceProviderAPI + AddProductRouteName;
diff --git a/TIAMWebApp/Shared/Services/ServiceProviderDataService.cs b/TIAMWebApp/Shared/Services/ServiceProviderDataService.cs
index 2e0a5ce1..dd000942 100644
--- a/TIAMWebApp/Shared/Services/ServiceProviderDataService.cs
+++ b/TIAMWebApp/Shared/Services/ServiceProviderDataService.cs
@@ -117,7 +117,7 @@ namespace TIAMWebApp.Shared.Application.Services
{
- var url = APIUrls.GetQRCodeByProductId;
+ var url = APIUrls.GetQrCodeByProductId;
var response = await http.PostAsJsonAsync(url, productId);
if (response.IsSuccessStatusCode)
{
diff --git a/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj b/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj
index 280b9ba4..c8411269 100644
--- a/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj
+++ b/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj
@@ -6,6 +6,12 @@
enable
+
+
+
+
+
+
@@ -13,7 +19,6 @@
-
From 3af9cb10e0fa9d806f495ac21869f32d9838f8f4 Mon Sep 17 00:00:00 2001
From: "jozsef.b@aycode.com" <9Rj@D}fVwBaN>
Date: Wed, 24 Apr 2024 06:50:53 +0200
Subject: [PATCH 3/4] refactoring, improvements...
---
TIAM.Database.Test/AdminDalTest.cs | 46 --------------
TIAM.Database.Test/TIAM.Database.Test.csproj | 8 +--
TIAM.Database.Test/UserDalTests.cs | 62 +++++++++++++++++--
.../appsettings.Development.json | 17 -----
TIAM.Database/DataLayers/Admins/AdminDal.cs | 40 ++++++------
.../DbContexts/Users/UserDbContext.cs | 1 +
.../Server/Controllers/UserAPIController.cs | 2 +-
7 files changed, 80 insertions(+), 96 deletions(-)
delete mode 100644 TIAM.Database.Test/appsettings.Development.json
diff --git a/TIAM.Database.Test/AdminDalTest.cs b/TIAM.Database.Test/AdminDalTest.cs
index b11a561c..0f5c4de0 100644
--- a/TIAM.Database.Test/AdminDalTest.cs
+++ b/TIAM.Database.Test/AdminDalTest.cs
@@ -572,51 +572,5 @@ namespace TIAM.Database.Test
}
#endregion EmailMessage
-
- #region User
- [DataTestMethod]
- [DataRow(["e31044d7-1771-4a32-8dd9-6f9853ed53c6", "0a831191-70a3-4504-9ec4-c5902affaba7", "8eed080c-d2ce-4cc3-bcfe-2268c220bba7", "addUser_test9432@tiam.hu"])]
- public async Task AddUserTest(string[] userIdProfileIdAddressIdEmailStrings)
- {
- var userId = Guid.Parse(userIdProfileIdAddressIdEmailStrings[0]);
- var profileId = Guid.Parse(userIdProfileIdAddressIdEmailStrings[1]);
- var addressId = Guid.Parse(userIdProfileIdAddressIdEmailStrings[2]);
- var email = userIdProfileIdAddressIdEmailStrings[3];
-
- var fromAddress = "Budapest, Liszt Ferenc tér";
- var toAddress = "1211 Budapest, Kossuth Lajos utca 145";
- //var userProductToCarId = Guid.Parse("97179a87-d99f-4f12-b7b2-75e21aaec6ab");
-
- await Dal.RemoveUserAsync(userId); //kitöröljük a szemetet, ha korábbról bentmaradt - J.
-
- var user = new User(userId, email, "235664", "dsfglfjg45r34903t3kggvq");
- //user.ProfileId = profileId;
-
- var profile = new Profile();
- profile.Id = profileId;;
- profile.Name = "Add user test name";
-
- var address = new Address();
- address.Id = addressId;
- address.Latitude = 5362.2341652256;
- address.Longitude = 5362.2341333317;
- address.AddressText = "1214 Kossuth Lajos utca 124.";
-
- user.Profile = profile;
- user.Profile.Address = address;
-
- Assert.IsTrue(await Dal.AddUserAsync(user));
- user = Dal.GetUserById(userId);
-
- Assert.IsNotNull(user);
- Assert.IsNotNull(user.Profile);
- Assert.IsNotNull(user.Profile.Address);
-
- Assert.IsTrue(await Dal.RemoveUserAsync(userId)); //mielőbb kitöröljük, h ne maradjon szemét a db-ben - J.
-
- user = Dal.GetUserById(userId);
- Assert.IsNull(user); //a korábbi törlés miatt NULL kell legyen - J.
- }
- #endregion
}
}
diff --git a/TIAM.Database.Test/TIAM.Database.Test.csproj b/TIAM.Database.Test/TIAM.Database.Test.csproj
index e871fda1..74121880 100644
--- a/TIAM.Database.Test/TIAM.Database.Test.csproj
+++ b/TIAM.Database.Test/TIAM.Database.Test.csproj
@@ -10,16 +10,10 @@
-
-
- PreserveNewest
- true
- PreserveNewest
-
PreserveNewest
true
@@ -32,6 +26,8 @@
+
+
diff --git a/TIAM.Database.Test/UserDalTests.cs b/TIAM.Database.Test/UserDalTests.cs
index ae22e85e..152be2ee 100644
--- a/TIAM.Database.Test/UserDalTests.cs
+++ b/TIAM.Database.Test/UserDalTests.cs
@@ -24,15 +24,13 @@ namespace TIAM.Database.Test
private const string LoginEmail = "asdfsdf@ggggg.hu";
private const string LoginPassword = "alad'r";
- private WebAssemblyHostConfiguration _configuration = new();
+ //private WebAssemblyHostConfiguration _configuration = new();
//private Mock _mockContext;
[TestInitialize]
public void TestInitialize()
{
- _configuration = new WebAssemblyHostConfiguration();
- _configuration.Build();
- _configuration.Reload();
+ //AppSettingsConfiguration = InitAppSettingsConfiguration();
//_configuration["JWT:Key"] = "Cee4400-rDMFkVvHPufyLDSzbfu2grgRhpepos299IhTLOXsljkcpt3yUR4RRjPQ";
//_configuration["JWT:Audience"] = "http://localhost:5000";
@@ -57,10 +55,18 @@ namespace TIAM.Database.Test
await Dal.RemoveUserAsync(_registerUserId); //kitöröljük a szemetet, ha korábbról bentmaradt - J.
- var loginService = new LoginService(Dal, _configuration);
+ var loginService = new LoginService(Dal, AppSettingsConfiguration);
var errorCode = await loginService.RegistrationAsync(_registerUserId, RegisterEmail, RegisterPassword, null);
Assert.IsTrue(errorCode == AcErrorCode.Unset);
+
+ var user = Dal.GetUserByEmail(RegisterEmail);
+
+ Assert.IsNotNull(user);
+ Assert.IsNotNull(user.Profile);
+ Assert.IsNotNull(user.Profile.Address);
+
+ await Dal.RemoveUserAsync(user); //kitöröljük a szemetet - J.
}
[TestMethod]
@@ -68,7 +74,7 @@ namespace TIAM.Database.Test
{
//var a = TiamConst.ProjectIdString;
- var loginService = new LoginService(Dal, _configuration);
+ var loginService = new LoginService(Dal, AppSettingsConfiguration);
#region Valid email+password test
var loggedInModel = loginService.Login(LoginEmail, LoginPassword);
@@ -161,6 +167,50 @@ namespace TIAM.Database.Test
Assert.IsTrue(userModel.UserToServiceProviders.Count > 0);
}
+ [DataTestMethod]
+ [DataRow(["e31044d7-1771-4a32-8dd9-6f9853ed53c6", "0a831191-70a3-4504-9ec4-c5902affaba7", "8eed080c-d2ce-4cc3-bcfe-2268c220bba7", "addUser_test9432@tiam.hu"])]
+ public async Task AddUserTest(string[] userIdProfileIdAddressIdEmailStrings)
+ {
+ var userId = Guid.Parse(userIdProfileIdAddressIdEmailStrings[0]);
+ var profileId = Guid.Parse(userIdProfileIdAddressIdEmailStrings[1]);
+ var addressId = Guid.Parse(userIdProfileIdAddressIdEmailStrings[2]);
+ var email = userIdProfileIdAddressIdEmailStrings[3];
+
+ var fromAddress = "Budapest, Liszt Ferenc tér";
+ var toAddress = "1211 Budapest, Kossuth Lajos utca 145";
+ //var userProductToCarId = Guid.Parse("97179a87-d99f-4f12-b7b2-75e21aaec6ab");
+
+ await Dal.RemoveUserAsync(userId); //kitöröljük a szemetet, ha korábbról bentmaradt - J.
+
+ var user = new User(userId, email, "235664", "dsfglfjg45r34903t3kggvq");
+ user.ProfileId = profileId;
+
+ var profile = new Profile();
+ profile.Id = profileId;;
+ profile.Name = "Add user test name";
+
+ var address = new Address();
+ address.Id = addressId;
+ address.Latitude = 5362.2341652256;
+ address.Longitude = 5362.2341333317;
+ address.AddressText = "1214 Kossuth Lajos utca 124.";
+
+ user.Profile = profile;
+ user.Profile.AddressId = addressId;
+ user.Profile.Address = address;
+
+ Assert.IsTrue(await Dal.AddUserAsync(user));
+ user = Dal.GetUserById(userId);
+
+ Assert.IsNotNull(user);
+ Assert.IsNotNull(user.Profile);
+ Assert.IsNotNull(user.Profile.Address);
+
+ Assert.IsTrue(await Dal.RemoveUserAsync(userId)); //mielőbb kitöröljük, h ne maradjon szemét a db-ben - J.
+
+ user = Dal.GetUserById(userId);
+ Assert.IsNull(user); //a korábbi törlés miatt NULL kell legyen - J.
+ }
//[TestMethod]
//[DataRow("test@tiam.hu")]
//public async Task GetUserByEmailAsync_ReturnsUser_WhenUserExists(string email)
diff --git a/TIAM.Database.Test/appsettings.Development.json b/TIAM.Database.Test/appsettings.Development.json
deleted file mode 100644
index 23ad61ca..00000000
--- a/TIAM.Database.Test/appsettings.Development.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft.AspNetCore": "Warning"
- }
- },
- "JWT": {
- "Key": "Cee4400-rDMFkVvHPufyLDSzbfu2grgRhpepos299IhTLOXsljkcpt3yUR4RRjPQ",
- "Issuer": "https://localhost:7116",
- "Audience": "http://localhost:7116"
- },
- "SendGrid": {
- //"Key": "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"
- "Key": "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"
- }
-}
diff --git a/TIAM.Database/DataLayers/Admins/AdminDal.cs b/TIAM.Database/DataLayers/Admins/AdminDal.cs
index 7435efcb..73663f9d 100644
--- a/TIAM.Database/DataLayers/Admins/AdminDal.cs
+++ b/TIAM.Database/DataLayers/Admins/AdminDal.cs
@@ -101,30 +101,30 @@ namespace TIAM.Database.DataLayers.Admins
public string? GetUserJsonById(Guid userId) => Session(ctx => ctx.GetUserById(userId)?.ToJson());
public string GetUsersJson() => Session(ctx => ctx.Users.ToJson());
- public Task AddUserAsync(User user) => TransactionAsync(ctx => ctx.AddUser(user));
+ //public Task AddUserAsync(User user) => TransactionAsync(ctx => ctx.AddUser(user));
- public Task AddUserAsync(User user, string profileName, Address address, string? firstName = null, string? lastName = null)
- {
- return TransactionAsync(ctx =>
- {
- var profile = new Profile
- {
- Id = Guid.NewGuid(),
- Name = profileName,
- FirstName = firstName,
- LastName = lastName,
- Address = address,
- AddressId = address.Id
- };
+ //public Task AddUserAsync(User user, string profileName, Address address, string? firstName = null, string? lastName = null)
+ //{
+ // return TransactionAsync(ctx =>
+ // {
+ // var profile = new Profile
+ // {
+ // Id = Guid.NewGuid(),
+ // Name = profileName,
+ // FirstName = firstName,
+ // LastName = lastName,
+ // Address = address,
+ // AddressId = address.Id
+ // };
- user.Profile= profile;
+ // user.Profile= profile;
- return ctx.AddUser(user);
- });
- }
+ // return ctx.AddUser(user);
+ // });
+ //}
- public Task RemoveUserAsync(User user) => TransactionAsync(ctx => ctx.RemoveUser(user));
- public Task RemoveUserAsync(Guid userId) => TransactionAsync(ctx => ctx.RemoveUser(userId));
+ //public Task RemoveUserAsync(User user) => TransactionAsync(ctx => ctx.RemoveUser(user));
+ //public Task RemoveUserAsync(Guid userId) => TransactionAsync(ctx => ctx.RemoveUser(userId));
public Product? GetProductById(Guid contextId, bool includeUsers = true) => Session(ctx => ctx.GetProductById(contextId, includeUsers));
diff --git a/TIAM.Database/DbContexts/Users/UserDbContext.cs b/TIAM.Database/DbContexts/Users/UserDbContext.cs
index c75d88e5..3b99bf24 100644
--- a/TIAM.Database/DbContexts/Users/UserDbContext.cs
+++ b/TIAM.Database/DbContexts/Users/UserDbContext.cs
@@ -31,6 +31,7 @@ namespace TIAM.Database.DbContexts.Users
public DbSet Users { get; set; }
public DbSet UserTokens { get; set; }
+ public DbSet Profiles { get; set; }
public DbSet Addresses { get; set; }
public DbSet Transfers { get; set; }
diff --git a/TIAMWebApp/Server/Controllers/UserAPIController.cs b/TIAMWebApp/Server/Controllers/UserAPIController.cs
index 1492aa17..26625471 100644
--- a/TIAMWebApp/Server/Controllers/UserAPIController.cs
+++ b/TIAMWebApp/Server/Controllers/UserAPIController.cs
@@ -277,7 +277,7 @@ namespace TIAMWebApp.Server.Controllers
userToCreate.Profile.Address.AddressText = null;
userToCreate.Profile.Address.Latitude = Math.Round(90 + rnd.NextDouble(), 8);
userToCreate.Profile.Address.Longitude = Math.Round(180 + rnd.NextDouble(), 8);
- result = await _adminDal.AddUserAsync(userToCreate);
+ result = await _userDal.AddUserAsync(userToCreate);
guestUser = await _userDal.GetUserModelDtoDetailByIdAsync(userId);
}
}
From 7d0117f4dd52bd375c727f39b7a99435d7ea0318 Mon Sep 17 00:00:00 2001
From: "jozsef.b@aycode.com" <9Rj@D}fVwBaN>
Date: Wed, 24 Apr 2024 17:58:43 +0200
Subject: [PATCH 4/4] improvements, fixes, etc...
---
TIAM.Database.Test/AdminDalTest.cs | 4 +-
TIAM.Database.Test/UserDalTests.cs | 8 ++--
TIAM.Database/DataLayers/Admins/AdminDal.cs | 14 +++---
TIAM.Database/DataLayers/Users/UserDal.cs | 12 ++---
.../DbSets/Users/UserDbSetExtensions.cs | 16 +++----
TIAMSharedUI/Pages/Login.razor | 2 +-
TIAMSharedUI/Pages/Login.razor.cs | 20 ++++----
.../Server/Controllers/UserAPIController.cs | 46 ++++++++-----------
8 files changed, 56 insertions(+), 66 deletions(-)
diff --git a/TIAM.Database.Test/AdminDalTest.cs b/TIAM.Database.Test/AdminDalTest.cs
index 0f5c4de0..d3acd53c 100644
--- a/TIAM.Database.Test/AdminDalTest.cs
+++ b/TIAM.Database.Test/AdminDalTest.cs
@@ -236,7 +236,7 @@ namespace TIAM.Database.Test
NullValueHandling = NullValueHandling.Ignore
};
- var userModel = Dal.GetUserModelDtoById(userId);
+ var userModel = Dal.GetUserModelDtoById(userId, false);
var serializedUserModel = JsonConvert.SerializeObject(userModel, options);
userModel = JsonConvert.DeserializeObject(serializedUserModel);
@@ -263,7 +263,7 @@ namespace TIAM.Database.Test
public void GetSerializedUserEntity_ReturnDeserializedUser_WhenUserAndRelationsExists(string userIdString)
{
var userId = Guid.Parse(userIdString);
- var userJson = Dal.GetUserJsonById(userId);
+ var userJson = Dal.GetUserJsonById(userId, false);
Assert.IsFalse(userJson?.IsNullOrWhiteSpace());
diff --git a/TIAM.Database.Test/UserDalTests.cs b/TIAM.Database.Test/UserDalTests.cs
index 152be2ee..1bb0f980 100644
--- a/TIAM.Database.Test/UserDalTests.cs
+++ b/TIAM.Database.Test/UserDalTests.cs
@@ -60,7 +60,7 @@ namespace TIAM.Database.Test
Assert.IsTrue(errorCode == AcErrorCode.Unset);
- var user = Dal.GetUserByEmail(RegisterEmail);
+ var user = Dal.GetUserByEmail(RegisterEmail, false);
Assert.IsNotNull(user);
Assert.IsNotNull(user.Profile);
@@ -149,7 +149,7 @@ namespace TIAM.Database.Test
NullValueHandling = NullValueHandling.Ignore
};
- var userModel = await Dal.GetUserModelDtoByIdAsync(userId).ConfigureAwait(false);
+ var userModel = await Dal.GetUserModelDtoByIdAsync(userId, false).ConfigureAwait(false);
var serializedUserModel = JsonConvert.SerializeObject(userModel, options);
userModel = JsonConvert.DeserializeObject(serializedUserModel);
@@ -200,7 +200,7 @@ namespace TIAM.Database.Test
user.Profile.Address = address;
Assert.IsTrue(await Dal.AddUserAsync(user));
- user = Dal.GetUserById(userId);
+ user = Dal.GetUserById(userId, false);
Assert.IsNotNull(user);
Assert.IsNotNull(user.Profile);
@@ -208,7 +208,7 @@ namespace TIAM.Database.Test
Assert.IsTrue(await Dal.RemoveUserAsync(userId)); //mielőbb kitöröljük, h ne maradjon szemét a db-ben - J.
- user = Dal.GetUserById(userId);
+ user = Dal.GetUserById(userId, false);
Assert.IsNull(user); //a korábbi törlés miatt NULL kell legyen - J.
}
//[TestMethod]
diff --git a/TIAM.Database/DataLayers/Admins/AdminDal.cs b/TIAM.Database/DataLayers/Admins/AdminDal.cs
index 73663f9d..a7d37ba4 100644
--- a/TIAM.Database/DataLayers/Admins/AdminDal.cs
+++ b/TIAM.Database/DataLayers/Admins/AdminDal.cs
@@ -90,15 +90,15 @@ namespace TIAM.Database.DataLayers.Admins
public User? GetUserById(Guid userId, bool autoInclude = false) => Session(ctx => ctx.GetUserById(userId, autoInclude));
public User? GetUserByEmail(string email, bool autoInclude = false) => Session(ctx => ctx.GetUserByEmail(email, autoInclude));
- public UserModelDtoDetail? GetUserModelDtoDetailById(Guid userId) => Session(ctx => ctx.GetUserModelDtoDetailById(userId));
- public Task GetUserModelDtoDetailByIdAsync(Guid userId) => SessionAsync(ctx => ctx.GetUserModelDtoDetailById(userId));
- public UserModelDtoDetail? GetUserModelDtoDetailByEmail(string email) => Session(ctx => ctx.GetUserModelDtoDetailByEmail(email));
+ public UserModelDtoDetail? GetUserModelDtoDetailById(Guid userId, bool onlyConfirmed) => Session(ctx => ctx.GetUserModelDtoDetailById(userId, onlyConfirmed));
+ public Task GetUserModelDtoDetailByIdAsync(Guid userId, bool onlyConfirmed) => SessionAsync(ctx => ctx.GetUserModelDtoDetailById(userId, onlyConfirmed));
+ public UserModelDtoDetail? GetUserModelDtoDetailByEmail(string email, bool onlyConfirmed) => Session(ctx => ctx.GetUserModelDtoDetailByEmail(email, onlyConfirmed));
- public UserModelDto? GetUserModelDtoById(Guid userId) => Session(ctx => ctx.GetUserModelDtoById(userId));
- public Task GetUserModelDtoByIdAsync(Guid userId) => SessionAsync(ctx => ctx.GetUserModelDtoById(userId));
- public UserModelDto? GetUserModelDtoByEmail(string email) => Session(ctx => ctx.GetUserModelDtoByEmail(email));
+ public UserModelDto? GetUserModelDtoById(Guid userId, bool onlyConfirmed) => Session(ctx => ctx.GetUserModelDtoById(userId, onlyConfirmed));
+ public Task GetUserModelDtoByIdAsync(Guid userId, bool onlyConfirmed) => SessionAsync(ctx => ctx.GetUserModelDtoById(userId, onlyConfirmed));
+ public UserModelDto? GetUserModelDtoByEmail(string email, bool onlyConfirmed) => Session(ctx => ctx.GetUserModelDtoByEmail(email, onlyConfirmed));
- public string? GetUserJsonById(Guid userId) => Session(ctx => ctx.GetUserById(userId)?.ToJson());
+ public string? GetUserJsonById(Guid userId, bool onlyConfirmed) => Session(ctx => ctx.GetUserById(userId, onlyConfirmed)?.ToJson());
public string GetUsersJson() => Session(ctx => ctx.Users.ToJson());
//public Task AddUserAsync(User user) => TransactionAsync(ctx => ctx.AddUser(user));
diff --git a/TIAM.Database/DataLayers/Users/UserDal.cs b/TIAM.Database/DataLayers/Users/UserDal.cs
index c1e1528a..04e0a18d 100644
--- a/TIAM.Database/DataLayers/Users/UserDal.cs
+++ b/TIAM.Database/DataLayers/Users/UserDal.cs
@@ -29,13 +29,13 @@ namespace TIAM.Database.DataLayers.Users
{
}
- public UserModelDtoDetail? GetUserModelDtoDetailById(Guid userId) => Session(ctx => ctx.GetUserModelDtoDetailById(userId));
- public Task GetUserModelDtoDetailByIdAsync(Guid userId) => SessionAsync(ctx => ctx.GetUserModelDtoDetailById(userId));
- public UserModelDtoDetail? GetUserModelDtoDetailByEmail(string email) => Session(ctx => ctx.GetUserModelDtoDetailByEmail(email));
+ public UserModelDtoDetail? GetUserModelDtoDetailById(Guid userId, bool onlyConfirmed) => Session(ctx => ctx.GetUserModelDtoDetailById(userId, onlyConfirmed));
+ public Task GetUserModelDtoDetailByIdAsync(Guid userId, bool onlyConfirmed) => SessionAsync(ctx => ctx.GetUserModelDtoDetailById(userId, onlyConfirmed));
+ public UserModelDtoDetail? GetUserModelDtoDetailByEmail(string email, bool onlyConfirmed) => Session(ctx => ctx.GetUserModelDtoDetailByEmail(email, onlyConfirmed));
- public UserModelDto? GetUserModelDtoById(Guid userId) => Session(x => x.GetUserModelDtoById(userId));
- public Task GetUserModelDtoByIdAsync(Guid userId) => SessionAsync(x => x.GetUserModelDtoById(userId));
- public Task GetUserModelDtoByEmailAsync(string email) => SessionAsync(x => x.GetUserModelDtoByEmail(email));
+ public UserModelDto? GetUserModelDtoById(Guid userId, bool onlyConfirmed) => Session(x => x.GetUserModelDtoById(userId, onlyConfirmed));
+ public Task GetUserModelDtoByIdAsync(Guid userId, bool onlyConfirmed) => SessionAsync(x => x.GetUserModelDtoById(userId, onlyConfirmed));
+ public Task GetUserModelDtoByEmailAsync(string email, bool onlyConfirmed) => SessionAsync(x => x.GetUserModelDtoByEmail(email, onlyConfirmed));
public Task> GetAllUsersModelDtoAsync() => SessionAsync(x => x.GetAllUsersModelDto().ToList());
public Task GetUserByPhoneNumberAsync(string phoneNumber)
diff --git a/TIAM.Database/DbSets/Users/UserDbSetExtensions.cs b/TIAM.Database/DbSets/Users/UserDbSetExtensions.cs
index 21c0581d..182b4d34 100644
--- a/TIAM.Database/DbSets/Users/UserDbSetExtensions.cs
+++ b/TIAM.Database/DbSets/Users/UserDbSetExtensions.cs
@@ -21,20 +21,20 @@ public static class UserDbSetExtensions
public static User? GetUserByEmail(this IUserDbSet ctx, string email, bool autoInclude)
=> ctx.UsersWithProductRelations(autoInclude).FirstOrDefault(x => x.EmailAddress == email);
- public static UserModelDto? GetUserModelDtoById(this IUserDbSet ctx, Guid userId)
- => ctx.GetUsersById(userId).Select(user => new UserModelDto(user)).FirstOrDefault();
+ public static UserModelDto? GetUserModelDtoById(this IUserDbSet ctx, Guid userId, bool onlyConfirmed)
+ => ctx.GetUsersById(userId, onlyConfirmed).Select(user => new UserModelDto(user)).FirstOrDefault();
- public static UserModelDto? GetUserModelDtoByEmail(this IUserDbSet ctx, string email)
- => ctx.GetUsersByEmail(email).Select(user => new UserModelDto(user)).FirstOrDefault();
+ public static UserModelDto? GetUserModelDtoByEmail(this IUserDbSet ctx, string email, bool onlyConfirmed)
+ => ctx.GetUsersByEmail(email, onlyConfirmed).Select(user => new UserModelDto(user)).FirstOrDefault();
public static IQueryable GetAllUsersModelDto(this IUserDbSet ctx)
=> ctx.Users.Select(user => new UserModelDto(user));
- public static UserModelDtoDetail? GetUserModelDtoDetailById(this IUserDbSet ctx, Guid userId)
- => ctx.GetUsersById(userId).Select(user => new UserModelDtoDetail(user)).FirstOrDefault();
+ public static UserModelDtoDetail? GetUserModelDtoDetailById(this IUserDbSet ctx, Guid userId, bool onlyConfirmed)
+ => ctx.GetUsersById(userId, onlyConfirmed).Select(user => new UserModelDtoDetail(user)).FirstOrDefault();
- public static UserModelDtoDetail? GetUserModelDtoDetailByEmail(this IUserDbSet ctx, string email)
- => ctx.GetUsersByEmail(email).Select(user => new UserModelDtoDetail(user)).FirstOrDefault();
+ public static UserModelDtoDetail? GetUserModelDtoDetailByEmail(this IUserDbSet ctx, string email, bool onlyConfirmed)
+ => ctx.GetUsersByEmail(email, onlyConfirmed).Select(user => new UserModelDtoDetail(user)).FirstOrDefault();
public static IQueryable GetAllUsersModelDetailDto(this IUserDbSet ctx)
=> ctx.Users.Select(user => new UserModelDtoDetail(user));
diff --git a/TIAMSharedUI/Pages/Login.razor b/TIAMSharedUI/Pages/Login.razor
index 95e07efe..04c91b43 100644
--- a/TIAMSharedUI/Pages/Login.razor
+++ b/TIAMSharedUI/Pages/Login.razor
@@ -86,7 +86,7 @@
@code {
- LoginModel loginModel = new LoginModel("test@test", "test1234");
+ LoginModel loginModel = new LoginModel("test@tiam.hu", "test1234");
}
\ No newline at end of file
diff --git a/TIAMSharedUI/Pages/Login.razor.cs b/TIAMSharedUI/Pages/Login.razor.cs
index fb32c431..43bcefc2 100644
--- a/TIAMSharedUI/Pages/Login.razor.cs
+++ b/TIAMSharedUI/Pages/Login.razor.cs
@@ -71,28 +71,28 @@ namespace TIAMSharedUI.Pages
//var Mainresponse = JsonSerializer.Deserialize(response);
- var Mainresponse = JsonSerializer.Deserialize(response, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
+ var mainResponse = JsonSerializer.Deserialize(response, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
- if (Mainresponse != null)
+ if (mainResponse != null)
{
//check for bad request
//TODO: fix hacky solution
- string AuthResponseJson = JsonSerializer.Serialize(Mainresponse.Content);
+ string authResponseJson = JsonSerializer.Serialize(mainResponse.Content);
- var AuthResponse = JsonSerializer.Deserialize(AuthResponseJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
+ var authResponse = JsonSerializer.Deserialize(authResponseJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
- string accessToken = AuthResponse.AccessToken;
+ string accessToken = authResponse.AccessToken;
var token = ProcessToken(accessToken);
- string _userId = token.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value;
- string _email = token.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.Email).Value;
+ string userId = token.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.NameId).Value;
+ string email = token.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.Email).Value;
- var myId = Guid.Parse(_userId);
+ var myId = Guid.Parse(userId);
//userDataService.User.Email = _email;
- var userBasicDetails = new UserBasicDetails(_userId, _email, AuthResponse.AccessToken, AuthResponse.RefreshToken);
+ var userBasicDetails = new UserBasicDetails(userId, email, authResponse.AccessToken, authResponse.RefreshToken);
string userBasicDetailsJson = JsonSerializer.Serialize(userBasicDetails);
@@ -103,7 +103,7 @@ namespace TIAMSharedUI.Pages
- if (!Mainresponse.IsSuccess)
+ if (!mainResponse.IsSuccess)
{
//await App.Current.MainPage.DisplayAlert("Error", "Invalid credentials", "Ok");
//display error message via jsinterop
diff --git a/TIAMWebApp/Server/Controllers/UserAPIController.cs b/TIAMWebApp/Server/Controllers/UserAPIController.cs
index 26625471..67c9ad04 100644
--- a/TIAMWebApp/Server/Controllers/UserAPIController.cs
+++ b/TIAMWebApp/Server/Controllers/UserAPIController.cs
@@ -24,6 +24,7 @@ using TIAMWebApp.Server.ModelsTIAMWebApp.Shared.Application.Models;
using TIAMWebApp.Shared.Application.Utility;
using TIAM.Database.DataLayers.Admins;
using System;
+using AyCode.Core.Consts;
using AyCode.Core.Helpers;
using TIAM.Entities.Profiles;
using TIAM.Entities.Addresses;
@@ -139,7 +140,7 @@ namespace TIAMWebApp.Server.Controllers
if (email != null)
{
//get user from db
- dbUser = await _userDal.GetUserByEmailAsync(email.Value);
+ dbUser = await _userDal.GetUserByEmailAsync(email.Value, true);
Console.WriteLine($@"DbUser email: {dbUser?.EmailAddress}");
}
@@ -178,17 +179,17 @@ namespace TIAMWebApp.Server.Controllers
[AllowAnonymous]
[HttpPost]
[Route("CreateUser")]
- public async Task CreateUser([FromBody] JsonElement SerializedRegistrationModel)
+ public async Task CreateUser([FromBody] JsonElement serializedRegistrationModel)
{
Console.WriteLine(@"CreateUser called");
- if (string.IsNullOrEmpty(SerializedRegistrationModel.GetRawText()))
+ if (string.IsNullOrEmpty(serializedRegistrationModel.GetRawText()))
{
return BadRequest("SerializedLoginModel is required");
}
else
{
- var user = JObject.Parse(SerializedRegistrationModel.GetRawText()).ToObject();
+ var user = JObject.Parse(serializedRegistrationModel.GetRawText()).ToObject();
if (user != null)
{
@@ -227,7 +228,7 @@ namespace TIAMWebApp.Server.Controllers
public async Task CreateGuestUser([FromBody] JsonElement SerializedRegistrationModel)
{
Console.WriteLine(@"CreateGuestUser called");
- bool result = false;
+ var result = false;
UserModelDtoDetail? guestUser = null;
if (string.IsNullOrEmpty(SerializedRegistrationModel.GetRawText()))
@@ -240,9 +241,9 @@ namespace TIAMWebApp.Server.Controllers
if (user != null)
{
- Random random = new Random();
- string chars = "1234567890";
- string nameExtension = new string(Enumerable.Repeat(chars, 10)
+ var random = new Random();
+ var chars = "1234567890";
+ var nameExtension = new string(Enumerable.Repeat(chars, 10)
.Select(s => s[random.Next(s.Length)]).ToArray());
@@ -250,7 +251,7 @@ namespace TIAMWebApp.Server.Controllers
var email = user?.Email;
var phoneNumber = user?.PhoneNumber;
var password = user?.Password;
- Guid? referralId = user?.ReferralId;
+ var referralId = user?.ReferralId;
if (email is null || phoneNumber is null || password is null)
{
@@ -271,14 +272,14 @@ namespace TIAMWebApp.Server.Controllers
userToCreate.RefferalId = referralId;
userToCreate.Profile.AddressId = Guid.NewGuid();
- Random rnd = new Random();
+ //Random rnd = new Random();
userToCreate.Profile.Address = new Address();
userToCreate.Profile.Address.Id = userToCreate.Profile.AddressId;
userToCreate.Profile.Address.AddressText = null;
- userToCreate.Profile.Address.Latitude = Math.Round(90 + rnd.NextDouble(), 8);
- userToCreate.Profile.Address.Longitude = Math.Round(180 + rnd.NextDouble(), 8);
+ userToCreate.Profile.Address.Latitude = null; //Math.Round(90 + rnd.NextDouble(), 8);
+ userToCreate.Profile.Address.Longitude = null; //Math.Round(180 + rnd.NextDouble(), 8);
result = await _userDal.AddUserAsync(userToCreate);
- guestUser = await _userDal.GetUserModelDtoDetailByIdAsync(userId);
+ guestUser = await _userDal.GetUserModelDtoDetailByIdAsync(userId, false);
}
}
@@ -303,7 +304,8 @@ namespace TIAMWebApp.Server.Controllers
{
Logger.Info($"GetUserByEmail called with email: {email}");
Console.WriteLine($@"GetUserByEmail called with email: {email}");
- return _userDal.GetUserModelDtoByEmailAsync(email);
+
+ return _userDal.GetUserModelDtoByEmailAsync(email, false);
}
[AllowAnonymous]
@@ -312,7 +314,7 @@ namespace TIAMWebApp.Server.Controllers
public Task GetUserById([FromBody] Guid id)
{
Logger.Info($"GetUserById called with id: {id}");
- return _userDal.GetUserModelDtoByIdAsync(id);
+ return _userDal.GetUserModelDtoByIdAsync(id, true);
}
[AllowAnonymous]
@@ -321,19 +323,7 @@ namespace TIAMWebApp.Server.Controllers
public Task GetUserDetailById([FromBody] Guid id)
{
Logger.Info($"GetUserDetailById called with id: {id}");
- return _userDal.GetUserModelDtoDetailByIdAsync(id);
- }
-
- private bool VerifyPassword(string password, string hashedPassword)
- {
- var isPasswordValid = PasswordHasher.VerifyPassword(password, hashedPassword);
- return isPasswordValid;
- }
-
- private string HashPassword(string password)
- {
- var hashedPassword = PasswordHasher.HashPassword(password);
- return hashedPassword;
+ return _userDal.GetUserModelDtoDetailByIdAsync(id, true);
}
}
}
\ No newline at end of file