diff --git a/TIAM.Core/Consts/TiamConst.cs b/TIAM.Core/Consts/TiamConst.cs new file mode 100644 index 00000000..29b54de5 --- /dev/null +++ b/TIAM.Core/Consts/TiamConst.cs @@ -0,0 +1,14 @@ +using AyCode.Core.Consts; + +namespace TIAM.Core.Consts; + +public class TiamConst : AcConst +{ + public static string ProjectIdString = "684f34d1-163a-4077-918f-a9d9df5ce789"; + + static TiamConst() + { + ProjectId = Guid.Parse(ProjectIdString); + ProjectSalt = GenerateProjectSalt(ProjectId.ToString("N")); + } +} \ No newline at end of file diff --git a/TIAM.Database.Test/AdminDalTest.cs b/TIAM.Database.Test/AdminDalTest.cs index 2bfdee32..d3acd53c 100644 --- a/TIAM.Database.Test/AdminDalTest.cs +++ b/TIAM.Database.Test/AdminDalTest.cs @@ -14,6 +14,7 @@ using TIAM.Entities.Users; using TIAM.Models.Dtos.Users; using TIAM.Entities.Transfers; using TIAM.Entities.Profiles; +using AyCode.Core.Extensions; namespace TIAM.Database.Test { @@ -235,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); @@ -262,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()); @@ -571,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.AddUser(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 080f34d3..74121880 100644 --- a/TIAM.Database.Test/TIAM.Database.Test.csproj +++ b/TIAM.Database.Test/TIAM.Database.Test.csproj @@ -10,14 +10,28 @@ - - - - + + + + + + PreserveNewest + true + PreserveNewest + + + + + + + + + + - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -29,6 +43,7 @@ + diff --git a/TIAM.Database.Test/UserDalTests.cs b/TIAM.Database.Test/UserDalTests.cs index c0eb5287..1bb0f980 100644 --- a/TIAM.Database.Test/UserDalTests.cs +++ b/TIAM.Database.Test/UserDalTests.cs @@ -1,32 +1,41 @@ -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 TIAM.Entities.ServiceProviders; using TIAM.Entities.Addresses; +using TIAMWebApp.Server.Services.Logins; +//using static Microsoft.ApplicationInsights.MetricDimensionNames.TelemetryContext; namespace TIAM.Database.Test { [TestClass] public class UserDalTests : AcUserDalTestBase { - private Mock _mockContext; + 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] public void TestInitialize() { + //AppSettingsConfiguration = InitAppSettingsConfiguration(); + + //_configuration["JWT:Key"] = "Cee4400-rDMFkVvHPufyLDSzbfu2grgRhpepos299IhTLOXsljkcpt3yUR4RRjPQ"; + //_configuration["JWT:Audience"] = "http://localhost:5000"; + //_configuration["JWT:Issuer"] = "http://localhost:5000"; + //var options = new DbContextOptionsBuilder() // .UseInMemoryDatabase(databaseName: "UserDatabase") // .Options; @@ -39,6 +48,63 @@ namespace TIAM.Database.Test //_userDal = new UserDal(_mockContext.Object); } + [TestMethod] + public async Task RegisterUser_ReturnsUser_WhenUserExist() + { + //var a = TiamConst.ProjectIdString; + + await Dal.RemoveUserAsync(_registerUserId); //kitöröljük a szemetet, ha korábbról bentmaradt - J. + + 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, false); + + Assert.IsNotNull(user); + Assert.IsNotNull(user.Profile); + Assert.IsNotNull(user.Profile.Address); + + await Dal.RemoveUserAsync(user); //kitöröljük a szemetet - J. + } + + [TestMethod] + public void LoginUser_ReturnsUser_WhenUserExist() + { + //var a = TiamConst.ProjectIdString; + + var loginService = new LoginService(Dal, AppSettingsConfiguration); + + #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] [DataRow("540271F6-C604-4C16-8160-D5A7CAFEDF00")] public void GetUserById_ReturnsUser_WhenUserAndRelationsExists(string userIdString) @@ -83,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); @@ -101,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, false); + + 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, false); + 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.json b/TIAM.Database.Test/appsettings.json new file mode 100644 index 00000000..48d14a21 --- /dev/null +++ b/TIAM.Database.Test/appsettings.json @@ -0,0 +1,22 @@ +{ + "ConnectionStrings": { + "DeveloperDbConnection": "Data Source=185.51.190.197;Initial Catalog=TIAM_DEV;Trusted_Connection=False;Connect Timeout=200;User ID=Anata_Development_Team;Password=v6f_?xNfg9N1;MultipleActiveResultSets=true" + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "JWT": { + "Key": "Cee4400-rDMFkVvHPufyLDSzbfu2grgRhpepos299IhTLOXsljkcpt3yUR4RRjPQ", + "Issuer": "http://localhost:5000", + "Audience": "http://localhost:5000" + }, + "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 8de6bc6d..a7d37ba4 100644 --- a/TIAM.Database/DataLayers/Admins/AdminDal.cs +++ b/TIAM.Database/DataLayers/Admins/AdminDal.cs @@ -90,49 +90,51 @@ 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 AddUser(User user) => TransactionAsync(ctx => ctx.AddUser(user)); + //public Task AddUserAsync(User user) => TransactionAsync(ctx => ctx.AddUser(user)); - public Task AddUser(User user, string profileName, Address address, string? firstName = null, string? lastName = null) - { - return TransactionAsync(ctx => - { - var profile = Activator.CreateInstance(); - - profile.Id = Guid.NewGuid(); - profile.Name = profileName; - profile.FirstName = firstName; - profile.LastName = lastName; - profile.Address = address; + //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.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)); public string GetProductsJson(bool includeUsers = true) => Session(ctx => ctx.ProductsWithUserRelations(includeUsers).ToJson()); public List GetProductsByServiceProviderId(Guid serviceProviderId, bool includeUsers = true) => Session(ctx => ctx.GetProductsByServiceProviderId(serviceProviderId, includeUsers).ToList()); public string GetProductsJsonByServiceProviderId(Guid serviceProviderId, bool includeUsers = true) => Session(ctx => ctx.GetProductsByServiceProviderId(serviceProviderId, includeUsers).ToJson()); - public Task AddProduct(Product product) => TransactionAsync(ctx => ctx.AddProduct(product)); + public Task AddProductAsync(Product product) => TransactionAsync(ctx => ctx.AddProduct(product)); - public Task UpdateProduct(Product product) => TransactionAsync(ctx => ctx.UpdateProduct(product)); - public Task RemoveProduct(Product product) => TransactionAsync(ctx => ctx.RemoveProduct(product)); + public Task UpdateProductAsync(Product product) => TransactionAsync(ctx => ctx.UpdateProduct(product)); + public Task RemoveProductAsync(Product product) => TransactionAsync(ctx => ctx.RemoveProduct(product)); public UserProductMapping? GetUserProductMappingById(Guid userProductMappingId, bool autoInclude = true) => Session(ctx => ctx.GetUserProductMappingById(userProductMappingId, autoInclude)); public Task GetUserProductMappingByIdAsync(Guid userProductMappingId, bool autoInclude = true) => SessionAsync(ctx => ctx.GetUserProductMappingById(userProductMappingId, autoInclude)); @@ -222,9 +224,9 @@ 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}"); - var _result = Context.SaveChangesAsync(); - return _result.Result > 0; + Console.WriteLine($@"Saving product to db {product.Id}, {product.Name}, {product.ServiceProviderId}"); + var result = Context.SaveChangesAsync(); + return result.Result > 0; } public Task> GetServiceProvidersAsync() @@ -234,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); } @@ -447,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 3c6a0052..7d7a6075 100644 --- a/TIAM.Database/DataLayers/Users/UserDal.cs +++ b/TIAM.Database/DataLayers/Users/UserDal.cs @@ -29,26 +29,26 @@ 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> GetAllUsersModelDtoDetailAsync() => SessionAsync(x => x.GetAllUsersModelDetailDto().ToList()); 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)); } @@ -63,29 +63,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/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/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/TIAM.Database/TIAM.Database.csproj b/TIAM.Database/TIAM.Database.csproj index b9bcb4c4..7388da77 100644 --- a/TIAM.Database/TIAM.Database.csproj +++ b/TIAM.Database/TIAM.Database.csproj @@ -7,9 +7,9 @@ - - - + + + diff --git a/TIAM.Entities/TIAM.Entities.csproj b/TIAM.Entities/TIAM.Entities.csproj index 711e424c..4d3fb02e 100644 --- a/TIAM.Entities/TIAM.Entities.csproj +++ b/TIAM.Entities/TIAM.Entities.csproj @@ -32,7 +32,7 @@ - + diff --git a/TIAMMobileApp/TIAMMobileApp.csproj b/TIAMMobileApp/TIAMMobileApp.csproj index 01bef5c6..81be8f98 100644 --- a/TIAMMobileApp/TIAMMobileApp.csproj +++ b/TIAMMobileApp/TIAMMobileApp.csproj @@ -52,8 +52,8 @@ - - + + @@ -83,15 +83,15 @@ - + - + - + diff --git a/TIAMSharedUI/Pages/Components/InputWizard.razor.cs b/TIAMSharedUI/Pages/Components/InputWizard.razor.cs index 11edc66a..096b12f3 100644 --- a/TIAMSharedUI/Pages/Components/InputWizard.razor.cs +++ b/TIAMSharedUI/Pages/Components/InputWizard.razor.cs @@ -17,6 +17,7 @@ using DevExpress.XtraPrinting; using TIAMSharedUI.Shared; using DevExpress.Pdf.Native.BouncyCastle.Asn1.Cms; using System.Text.RegularExpressions; +using AyCode.Core.Consts; namespace TIAMSharedUI.Pages.Components @@ -213,7 +214,7 @@ namespace TIAMSharedUI.Pages.Components editor.OpenComponent>(j++); editor.AddAttribute(j++, "Value", property.GetValue(Data)); - editor.AddAttribute(j++, "Mask", TIAMRegularExpressions.PhoneNumberMask); + editor.AddAttribute(j++, "Mask", AcRegExpression.PhoneNumberMask); editor.AddAttribute(j++, "MaskMode", MaskMode.RegEx); editor.AddAttribute(j++, "BindValueMode", BindValueMode.OnInput); editor.AddAttribute(j++, "NullText", "+11234567890"); @@ -238,7 +239,7 @@ namespace TIAMSharedUI.Pages.Components { editor.OpenComponent>(j++); editor.AddAttribute(j++, "Value", property.GetValue(Data)); - editor.AddAttribute(j++, "Mask", TIAMRegularExpressions.EmailMask); + editor.AddAttribute(j++, "Mask", AcRegExpression.EmailMask); editor.AddAttribute(j++, "MaskMode", MaskMode.RegEx); editor.AddAttribute(j++, "BindValueMode", BindValueMode.OnInput); diff --git a/TIAMSharedUI/Pages/Components/Step1.razor b/TIAMSharedUI/Pages/Components/Step1.razor index f89012db..50512031 100644 --- a/TIAMSharedUI/Pages/Components/Step1.razor +++ b/TIAMSharedUI/Pages/Components/Step1.razor @@ -1,5 +1,6 @@ @using TIAMWebApp.Shared.Application.Models.PageModels; @using TIAMWebApp.Shared.Application.Utility; +@using AyCode.Core.Consts @@ -44,7 +45,7 @@ public EventCallback RegModelChanged { get; set; } //string EmailMask { get; set; } = @"(\w|[.-])+@(\w|-)+\.(\w|-){2,4}"; - string EmailMask { get; set; } = TIAMRegularExpressions.EmailMask; + string EmailMask { get; set; } = AcRegExpression.EmailMask; MaskAutoCompleteMode AutoCompleteMode { get; set; } = MaskAutoCompleteMode.Strong; char Placeholder { get; set; } = '_'; bool PlaceholderVisible { get; set; } = false; diff --git a/TIAMSharedUI/Pages/Components/Step2.razor b/TIAMSharedUI/Pages/Components/Step2.razor index 3c00aae9..870114a0 100644 --- a/TIAMSharedUI/Pages/Components/Step2.razor +++ b/TIAMSharedUI/Pages/Components/Step2.razor @@ -1,5 +1,6 @@ @using TIAMWebApp.Shared.Application.Models.PageModels; @using TIAMWebApp.Shared.Application.Utility; +@using AyCode.Core.Consts

Step 2: Phone Number

@@ -48,7 +49,7 @@ public EventCallback 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/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/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/Services/WizardProcessor.cs b/TIAMWebApp/Client/Services/WizardProcessor.cs index 77059d5f..36d6e603 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/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/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/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 ddd93ed4..d16400c4 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,25 +169,25 @@ 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"); } else { - var result = _adminDal.AddProduct(product); + var result = _adminDal.AddProductAsync(product); return Ok(result); } } [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 f0024123..f70c022e 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 5fe37fa3..63ccbbbd 100644 --- a/TIAMWebApp/Server/Controllers/UserAPIController.cs +++ b/TIAMWebApp/Server/Controllers/UserAPIController.cs @@ -18,15 +18,17 @@ 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.Consts; +using AyCode.Core.Helpers; using TIAM.Entities.Profiles; using TIAM.Entities.Addresses; +using TIAMWebApp.Server.Services.Logins; namespace TIAMWebApp.Server.Controllers { @@ -35,11 +37,12 @@ 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; private readonly IWebHostEnvironment _webHostEnvironment; - readonly PasswordHasher _hasher = new(); + //readonly PasswordHasher _hasher = new(); /*private UserModel[] users = new UserModel[] @@ -58,105 +61,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 +116,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); @@ -188,8 +140,8 @@ namespace TIAMWebApp.Server.Controllers if (email != null) { //get user from db - dbUser = await _userDal.GetUserByEmailAsync(email.Value); - Console.WriteLine("DbUser email: " + dbUser?.EmailAddress); + dbUser = await _userDal.GetUserByEmailAsync(email.Value, true); + Console.WriteLine($@"DbUser email: {dbUser?.EmailAddress}"); } //mocking - update userModel with new refreshToken so it returns true after the check below @@ -198,12 +150,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,64 +172,24 @@ 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) + public async Task CreateUser([FromBody] JsonElement serializedRegistrationModel) { - Console.WriteLine("CreateUser called"); + 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) { @@ -297,10 +209,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)); } @@ -355,8 +267,8 @@ namespace TIAMWebApp.Server.Controllers [Route(APIUrls.CreateGuestUserRouteName)] public async Task CreateGuestUser([FromBody] JsonElement SerializedRegistrationModel) { - Console.WriteLine("CreateGuestUser called"); - bool result = false; + Console.WriteLine(@"CreateGuestUser called"); + var result = false; UserModelDtoDetail? guestUser = null; if (string.IsNullOrEmpty(SerializedRegistrationModel.GetRawText())) @@ -369,9 +281,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()); @@ -379,7 +291,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) { @@ -387,10 +299,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(); @@ -400,14 +312,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); - result = await _adminDal.AddUser(userToCreate); - guestUser = await _userDal.GetUserModelDtoDetailByIdAsync(userId); + 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, false); } } @@ -442,8 +354,9 @@ namespace TIAMWebApp.Server.Controllers public Task GetUserByEmail(string email) { Logger.Info($"GetUserByEmail called with email: {email}"); - Console.WriteLine($"GetUserByEmail called with email: {email}"); - return _userDal.GetUserModelDtoByEmailAsync(email); + Console.WriteLine($@"GetUserByEmail called with email: {email}"); + + return _userDal.GetUserModelDtoByEmailAsync(email, false); } [AllowAnonymous] @@ -452,7 +365,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] @@ -461,19 +374,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 = _hasher.VerifyPassword(password, hashedPassword); - return isPasswordValid; - } - - private string HashPassword(string password) - { - var hashedPassword = _hasher.HashPassword(password); - return hashedPassword; + return _userDal.GetUserModelDtoDetailByIdAsync(id, true); } } } \ No newline at end of file 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 new file mode 100644 index 00000000..7c34cdc6 --- /dev/null +++ b/TIAMWebApp/Server/Services/Logins/ILoginService.cs @@ -0,0 +1,17 @@ +using AyCode.Interfaces.Server.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 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..c103d464 --- /dev/null +++ b/TIAMWebApp/Server/Services/Logins/LoginService.cs @@ -0,0 +1,37 @@ +using System.Reflection.Metadata.Ecma335; +using System.Security; +using AyCode.Core.Consts; +using AyCode.Interfaces.Server.Logins; +using AyCode.Services.Server.Logins; +using AyCode.Utils.Extensions; +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; +using TIAMWebApp.Server.Models.Logins; + +namespace TIAMWebApp.Server.Services.Logins; + +public class LoginService(UserDal userDal, IConfiguration configuration) : AcLoginServiceServer(userDal, configuration), ILoginService + +{ + public override LoggedInModel Login(string? email, string? password) + { + return base.Login(email, password); + } + + public override bool Logout() + { + return base.Logout(); + } + + public override Task RegistrationAsync(string email, string password, string? phoneNumber = null) + { + return base.RegistrationAsync(email, password, phoneNumber); + } +} + \ No newline at end of file diff --git a/TIAMWebApp/Server/Services/NoticeSenderService.cs b/TIAMWebApp/Server/Services/NoticeSenderService.cs index 63c06561..740e491f 100644 --- a/TIAMWebApp/Server/Services/NoticeSenderService.cs +++ b/TIAMWebApp/Server/Services/NoticeSenderService.cs @@ -30,7 +30,7 @@ namespace TIAMWebApp.Server.Services case (int)MessageTypesEnum.email: if (message is MessageSenderModel emailMessage) { - Console.WriteLine($"EmailMessage!!!"); + Console.WriteLine($@"EmailMessage!!!"); // Access DerivedClass properties var _subject = emailMessage.Message.Subject; result = await SendMailWithSendgrid(emailMessage.Message); @@ -61,8 +61,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/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/Models/APIUrls.cs b/TIAMWebApp/Shared/Models/APIUrls.cs index 15dc408a..6cb463bb 100644 --- a/TIAMWebApp/Shared/Models/APIUrls.cs +++ b/TIAMWebApp/Shared/Models/APIUrls.cs @@ -37,7 +37,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; @@ -102,8 +105,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 350d6a37..c2a9c531 100644 --- a/TIAMWebApp/Shared/Services/ServiceProviderDataService.cs +++ b/TIAMWebApp/Shared/Services/ServiceProviderDataService.cs @@ -118,7 +118,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 878a85be..c8411269 100644 --- a/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj +++ b/TIAMWebApp/Shared/TIAMWebApp.Shared.Application.csproj @@ -6,6 +6,12 @@ enable + + + + + + @@ -13,15 +19,14 @@ - - + - - - + + + 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})"; - - } -}