diff --git a/RelationAnalysis.Migrations/InitialRecordsCreator.cs b/RelationAnalysis.Migrations/InitialRecordsCreator.cs index 57f88cc..6b0cb09 100644 --- a/RelationAnalysis.Migrations/InitialRecordsCreator.cs +++ b/RelationAnalysis.Migrations/InitialRecordsCreator.cs @@ -15,21 +15,21 @@ public async Task AddInitialRecords() { Name = "Admin", Permissions = - "'[\"/api/Access/GetPermissions\",\"/api/Admin/GetUser/{id}\",\"/api/Admin/GetAllUser\",\"/api/Admin/GetAllRoles\",\"/api/Admin/UpdateUser/{id}\",\"/api/Admin/UpdatePassword/{id}\",\"/api/Admin/DeleteUser/{id}\",\"/api/Admin/CreateUser\",\"/api/Admin/UpdateRoles/{id}\",\"/api/Auth/Login\", \"/api/User/GetUser\",\"/api/User/UpdateUser\",\"/api/User/UpdatePassword\",\"/api/User/Logout\"]'", + "[\"/api/Access/GetPermissions\",\"/api/Admin/GetUser/{id}\",\"/api/Admin/GetAllUser\",\"/api/Admin/GetAllRoles\",\"/api/Admin/UpdateUser/{id}\",\"/api/Admin/UpdatePassword/{id}\",\"/api/Admin/DeleteUser/{id}\",\"/api/Admin/CreateUser\",\"/api/Admin/UpdateRoles/{id}\",\"/api/Auth/Login\", \"/api/User/GetUser\",\"/api/User/UpdateUser\",\"/api/User/UpdatePassword\",\"/api/User/Logout\"]", Id = 1 }, new Role() { Name = "DataAdmin", Permissions = - "'[\"/api/Access/GetPermissions\",\"/api/Auth/Login\",\"/api/User/GetUser\",\"/api/User/UpdateUser\",\"/api/User/UpdatePassword\",\"/api/User/Logout\"]'", + "[\"/api/Access/GetPermissions\",\"/api/Auth/Login\",\"/api/User/GetUser\",\"/api/User/UpdateUser\",\"/api/User/UpdatePassword\",\"/api/User/Logout\"]", Id = 2 }, new Role() { Name = "DataAnalyst", Permissions = - "'[\"/api/Access/GetPermissions\",\"/api/Auth/Login\",\"/api/User/GetUser\",\"/api/User/UpdateUser\",\"/api/User/UpdatePassword\",\"/api/User/Logout\"]'", + "[\"/api/Access/GetPermissions\",\"/api/Auth/Login\",\"/api/User/GetUser\",\"/api/User/UpdateUser\",\"/api/User/UpdatePassword\",\"/api/User/Logout\"]", Id = 3 } }; diff --git a/RelationshipAnalysis.Test/Services/LoginServiceTests.cs b/RelationshipAnalysis.Test/Services/LoginServiceTests.cs index 7faec5e..3cbdd2b 100644 --- a/RelationshipAnalysis.Test/Services/LoginServiceTests.cs +++ b/RelationshipAnalysis.Test/Services/LoginServiceTests.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using Moq; using RelationshipAnalysis.Context; using RelationshipAnalysis.Dto; @@ -20,7 +21,7 @@ public class LoginServiceTests private readonly Mock _mockJwtTokenGenerator; private readonly Mock _mockPasswordVerifier; private readonly Mock _mockHttpResponse; - + private readonly IServiceProvider _serviceProvider; public LoginServiceTests() { var options = new DbContextOptionsBuilder() @@ -38,8 +39,13 @@ public LoginServiceTests() _mockHttpResponse = new Mock(); _mockHttpResponse.SetupGet(r => r.Cookies).Returns(mockResponseCookies.Object); + var serviceCollection = new ServiceCollection(); + serviceCollection.AddScoped(_ => _context); + + _serviceProvider = serviceCollection.BuildServiceProvider(); + _sut = new LoginService( - _context, + _serviceProvider, _mockCookieSetter.Object, _mockJwtTokenGenerator.Object, _mockPasswordVerifier.Object diff --git a/RelationshipAnalysis.Test/Services/PermissionServiceTests.cs b/RelationshipAnalysis.Test/Services/PermissionServiceTests.cs index a639101..7143313 100644 --- a/RelationshipAnalysis.Test/Services/PermissionServiceTests.cs +++ b/RelationshipAnalysis.Test/Services/PermissionServiceTests.cs @@ -1,5 +1,6 @@ using System.Security.Claims; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using Moq; using Newtonsoft.Json; using RelationshipAnalysis.Context; @@ -13,39 +14,46 @@ namespace RelationshipAnalysis.Test.Services; public class PermissionServiceTests { private readonly PermissionService _sut; - private readonly ApplicationDbContext _context; - private readonly List _userRoles = ["Read", "Write"]; - private readonly List _adminRoles = ["Delete", "Write"]; + private readonly IServiceProvider _serviceProvider; + private readonly List _userRoles = new List { "Read", "Write" }; + private readonly List _adminRoles = new List { "Delete", "Write" }; public PermissionServiceTests() { + var serviceCollection = new ServiceCollection(); + var options = new DbContextOptionsBuilder() .UseInMemoryDatabase(databaseName: "TestDatabase") .Options; + serviceCollection.AddScoped(_ => new ApplicationDbContext(options)); - _context = new ApplicationDbContext(options); + _serviceProvider = serviceCollection.BuildServiceProvider(); SeedDatabase(); - _sut = new PermissionService(_context); + _sut = new PermissionService(_serviceProvider); } private void SeedDatabase() { - _context.Roles.AddRange(new List + using (var scope = _serviceProvider.CreateScope()) { - new Role - { - Name = "User", - Permissions = JsonConvert.SerializeObject(_userRoles) - }, - new Role + var context = scope.ServiceProvider.GetRequiredService(); + context.Roles.AddRange(new List { - Name = "Admin", - Permissions = JsonConvert.SerializeObject(_adminRoles) - } - }); - _context.SaveChanges(); + new Role + { + Name = "User", + Permissions = JsonConvert.SerializeObject(_userRoles) + }, + new Role + { + Name = "Admin", + Permissions = JsonConvert.SerializeObject(_adminRoles) + } + }); + context.SaveChanges(); + } } [Fact] @@ -60,10 +68,13 @@ public async Task GetPermissionsAsync_ShouldReturnPermissions_WhenRolesExist() // Act var result = await _sut.GetPermissionsAsync(userClaims); + var expectedResult = _userRoles.Union(_adminRoles); + var expectedPermissions = JsonConvert.SerializeObject(expectedResult); // Assert - var expectedPermissions = JsonConvert.SerializeObject(expectedResult); + Assert.NotNull(result); + Assert.NotNull(result.Data); Assert.Equal(expectedPermissions, result.Data.Permissions); } } \ No newline at end of file diff --git a/RelationshipAnalysis.Test/Services/UserPasswordServiceTests.cs b/RelationshipAnalysis.Test/Services/UserPasswordServiceTests.cs index 181f9ff..cb553a7 100644 --- a/RelationshipAnalysis.Test/Services/UserPasswordServiceTests.cs +++ b/RelationshipAnalysis.Test/Services/UserPasswordServiceTests.cs @@ -1,4 +1,5 @@ using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using NSubstitute; using RelationshipAnalysis.Context; using RelationshipAnalysis.Dto; @@ -19,14 +20,20 @@ public class UserPasswordServiceTests private readonly IPasswordVerifier _passwordVerifier; private readonly IPasswordHasher _passwordHasher; private readonly IUserPasswordService _sut; - + private readonly IServiceProvider _serviceProvider; public UserPasswordServiceTests() { _context = new ApplicationDbContext(new DbContextOptionsBuilder() .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options); _passwordVerifier = Substitute.For(); _passwordHasher = Substitute.For(); - _sut = new UserPasswordService(_context, _passwordVerifier, _passwordHasher); + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddScoped(_ => _context); + + _serviceProvider = serviceCollection.BuildServiceProvider(); + + _sut = new UserPasswordService(_serviceProvider, _passwordVerifier, _passwordHasher); SeedDatabase(); } diff --git a/RelationshipAnalysis.Test/Services/UserReceiverTests.cs b/RelationshipAnalysis.Test/Services/UserReceiverTests.cs index a48fef7..93ffe62 100644 --- a/RelationshipAnalysis.Test/Services/UserReceiverTests.cs +++ b/RelationshipAnalysis.Test/Services/UserReceiverTests.cs @@ -1,9 +1,8 @@ using System.Security.Claims; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using RelationshipAnalysis.Context; -using RelationshipAnalysis.Models; using RelationshipAnalysis.Models.Auth; -using RelationshipAnalysis.Services; using RelationshipAnalysis.Services.UserPanelServices; namespace RelationshipAnalysis.Test.Services @@ -12,12 +11,20 @@ public class UserReceiverTests { private readonly ApplicationDbContext _context; private readonly UserReceiver _sut; + private readonly IServiceProvider _serviceProvider; public UserReceiverTests() { _context = new ApplicationDbContext(new DbContextOptionsBuilder() .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options); - _sut = new UserReceiver(_context); + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddScoped(_ => _context); + + _serviceProvider = serviceCollection.BuildServiceProvider(); + + + _sut = new UserReceiver(_serviceProvider); SeedDatabase(); } diff --git a/RelationshipAnalysis.Test/Services/UserRolesReceiverTests.cs b/RelationshipAnalysis.Test/Services/UserRolesReceiverTests.cs index d84552c..13474bb 100644 --- a/RelationshipAnalysis.Test/Services/UserRolesReceiverTests.cs +++ b/RelationshipAnalysis.Test/Services/UserRolesReceiverTests.cs @@ -1,5 +1,6 @@ using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using RelationshipAnalysis.Context; using RelationshipAnalysis.Models; using RelationshipAnalysis.Models.Auth; @@ -12,12 +13,17 @@ public class UserRolesReceiverTests { private readonly ApplicationDbContext _context; private readonly RoleReceiver _sut; - + private readonly IServiceProvider _serviceProvider; public UserRolesReceiverTests() { _context = new ApplicationDbContext(new DbContextOptionsBuilder() .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options); - _sut = new RoleReceiver(_context); + var serviceCollection = new ServiceCollection(); + serviceCollection.AddScoped(_ => _context); + + _serviceProvider = serviceCollection.BuildServiceProvider(); + + _sut = new RoleReceiver(_serviceProvider); SeedDatabase(); } diff --git a/RelationshipAnalysis.Test/Services/UserUpdateInfoServiceTests.cs b/RelationshipAnalysis.Test/Services/UserUpdateInfoServiceTests.cs index 93ffbf0..67961f3 100644 --- a/RelationshipAnalysis.Test/Services/UserUpdateInfoServiceTests.cs +++ b/RelationshipAnalysis.Test/Services/UserUpdateInfoServiceTests.cs @@ -1,154 +1,156 @@ - using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; -using NSubstitute; +using Microsoft.Extensions.DependencyInjection; +using Moq; using RelationshipAnalysis.Context; using RelationshipAnalysis.Dto; using RelationshipAnalysis.Enums; -using RelationshipAnalysis.Models; using RelationshipAnalysis.Models.Auth; -using RelationshipAnalysis.Services; using RelationshipAnalysis.Services.UserPanelServices; -using RelationshipAnalysis.Services.UserPanelServices.Abstraction.AuthServices.Abstraction; namespace RelationshipAnalysis.Test.Services { public class UserUpdateInfoServiceTests { - private readonly ApplicationDbContext _context; - private readonly IMapper _mapper; - private readonly ICookieSetter _cookieSetter; - private readonly IJwtTokenGenerator _jwtTokenGenerator; private readonly UserUpdateInfoService _sut; - + private readonly IServiceProvider _serviceProvider; + private readonly User _user = new User + { + Id = 1, + Username = "existinguser", + Email = "existing@example.com", + PasswordHash = "hashedpassword", + FirstName = "John", + LastName = "Doe" + }; public UserUpdateInfoServiceTests() { - _context = new ApplicationDbContext(new DbContextOptionsBuilder() - .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options); + var serviceCollection = new ServiceCollection(); + + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) + .Options; + + serviceCollection.AddScoped(_ => new ApplicationDbContext(options)); + serviceCollection.AddAutoMapper(typeof(UserUpdateInfoService)); + + _serviceProvider = serviceCollection.BuildServiceProvider(); + + var mapper = _serviceProvider.GetRequiredService(); + _sut = new UserUpdateInfoService(_serviceProvider, mapper); - _mapper = Substitute.For(); - _cookieSetter = Substitute.For(); - _jwtTokenGenerator = Substitute.For(); - _sut = new UserUpdateInfoService(_context, _mapper); SeedDatabase(); } private void SeedDatabase() { - _context.Users.AddRange(new User + using (var scope = _serviceProvider.CreateScope()) { - Id = 1, - Username = "ExistingUser", - Email = "user@example.com", - FirstName = "", - LastName = "", - PasswordHash = "HashedPassword" - }, - new User - { - Id = 2, - Username = "NewUserName", - Email = "newemail@example.com", - FirstName = "", - LastName = "", - PasswordHash = "HashedPassword" - }); - _context.SaveChanges(); + var context = scope.ServiceProvider.GetRequiredService(); + context.Users.AddRange(new List() + { + _user, + new User + { + Id = 2, + Username = "existinguser2", + Email = "existing2@example.com", + PasswordHash = "hashedpassword", + FirstName = "John", + LastName = "Doe" + } + }); + context.SaveChanges(); + } } [Fact] - public async Task UpdateUserAsync_ReturnsBadRequest_WhenEmailAlreadyExists() + public async Task UpdateUserAsync_ShouldReturnNotFound_WhenUserIsNull() { // Arrange - var user = await _context.Users.FindAsync(1); - var userUpdateInfoDto = new UserUpdateInfoDto + User user = null; + var dto = new UserUpdateInfoDto { - Username = "ExistingUser", - Email = "newemail@example.com" + Username = "newuser", + Email = "new@example.com" }; - var response = Substitute.For(); + var response = new Mock().Object; // Act - var result = await _sut.UpdateUserAsync(user, userUpdateInfoDto, response); + var result = await _sut.UpdateUserAsync(user, dto, response); // Assert - Assert.NotNull(result); - Assert.Equal(StatusCodeType.BadRequest, result.StatusCode); - Assert.Equal(Resources.EmailExistsMessage, result.Data.Message); + Assert.Equal(StatusCodeType.NotFound, result.StatusCode); + Assert.Equal(Resources.UserNotFoundMessage, result.Data.Message); } [Fact] - public async Task UpdateUserAsync_ReturnsBadRequest_WhenUsernameAlreadyExists() + public async Task UpdateUserAsync_ShouldReturnBadRequest_WhenUsernameExists() { // Arrange - var user = await _context.Users.FindAsync(1); - var userUpdateInfoDto = new UserUpdateInfoDto + var dto = new UserUpdateInfoDto { - Username = "NewUserName", - Email = "user@example.com" + Username = "existinguser2" }; - var response = Substitute.For(); + var response = new Mock().Object; // Act - var result = await _sut.UpdateUserAsync(user, userUpdateInfoDto, response); + var result = await _sut.UpdateUserAsync(_user, dto, response); // Assert - Assert.NotNull(result); Assert.Equal(StatusCodeType.BadRequest, result.StatusCode); Assert.Equal(Resources.UsernameExistsMessage, result.Data.Message); } [Fact] - public async Task UpdateUserAsync_ReturnsNotFound_WhenUserIsNull() + public async Task UpdateUserAsync_ShouldReturnBadRequest_WhenEmailExists() { // Arrange - User user = null; - var userUpdateInfoDto = new UserUpdateInfoDto(); - var response = Substitute.For(); + var dto = new UserUpdateInfoDto + { + Email = "existing2@example.com" + }; + var response = new Mock().Object; // Act - var result = await _sut.UpdateUserAsync(user, userUpdateInfoDto, response); + var result = await _sut.UpdateUserAsync(_user, dto, response); // Assert - Assert.NotNull(result); - Assert.Equal(StatusCodeType.NotFound, result.StatusCode); - Assert.Equal(Resources.UserNotFoundMessage, result.Data.Message); + Assert.Equal(StatusCodeType.BadRequest, result.StatusCode); + Assert.Equal(Resources.EmailExistsMessage, result.Data.Message); } [Fact] - public async Task UpdateUserAsync_ReturnsSuccess_WhenUserIsUpdated() + public async Task UpdateUserAsync_ShouldUpdateUserAndReturnSuccess_WhenValidData() { // Arrange - var user = await _context.Users.FindAsync(1); - var userUpdateInfoDto = new UserUpdateInfoDto - { - Username = "UpdatedUserName", - Email = "updated@example.com" - }; - var resultUser = new User() + var dto = new UserUpdateInfoDto { - Id = 1, - Username = "UpdatedUserName", - Email = "updated@example.com", - FirstName = "", - LastName = "", - PasswordHash = "HashedPassword" + Username = "newuser", + Email = "new@example.com", + FirstName = "Jane", + LastName = "Smith" }; - _mapper.Map(userUpdateInfoDto).Returns(resultUser); - - var response = Substitute.For(); - + var response = new Mock().Object; + // Act - var result = await _sut.UpdateUserAsync(user, userUpdateInfoDto, response); + var result = await _sut.UpdateUserAsync(_user, dto, response); // Assert - Assert.NotNull(result); Assert.Equal(StatusCodeType.Success, result.StatusCode); Assert.Equal(Resources.SuccessfulUpdateUserMessage, result.Data.Message); - Assert.Equal("ExistingUser", user.Username); - Assert.Equal("user@example.com", user.Email); + + using (var scope = _serviceProvider.CreateScope()) + { + var context = scope.ServiceProvider.GetRequiredService(); + var updatedUser = context.Users.SingleOrDefault(u => u.Id == _user.Id); + Assert.NotNull(updatedUser); + Assert.Equal("newuser", updatedUser.Username); + Assert.Equal("new@example.com", updatedUser.Email); + Assert.Equal("Jane", updatedUser.FirstName); + Assert.Equal("Smith", updatedUser.LastName); + } } - } } diff --git a/RelationshipAnalysis/Controllers/AuthController.cs b/RelationshipAnalysis/Controllers/AuthController.cs index e017df2..1d5a3f7 100644 --- a/RelationshipAnalysis/Controllers/AuthController.cs +++ b/RelationshipAnalysis/Controllers/AuthController.cs @@ -1,11 +1,8 @@ -using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; using RelationshipAnalysis.Context; using RelationshipAnalysis.Dto; using RelationshipAnalysis.Services.UserPanelServices.Abstraction.AuthServices.Abstraction; -using RelationshipAnalysis.Settings.JWT; namespace RelationshipAnalysis.Controllers; diff --git a/RelationshipAnalysis/Program.cs b/RelationshipAnalysis/Program.cs index 2795e69..c9dba1c 100644 --- a/RelationshipAnalysis/Program.cs +++ b/RelationshipAnalysis/Program.cs @@ -26,22 +26,20 @@ builder.Services.AddSingleton() .AddSingleton() - .AddScoped() - .AddScoped() + .AddSingleton() + .AddSingleton() .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() .AddSingleton() - .AddScoped() - .AddScoped() - .AddScoped() - .AddScoped() - .AddScoped() - .AddScoped() - .AddSingleton() - .AddScoped() + .AddSingleton() .AddSingleton() - .AddScoped() - .AddScoped() - .AddScoped(); + .AddSingleton() + .AddSingleton(); builder.Services.Configure(builder.Configuration.GetSection("Jwt")); diff --git a/RelationshipAnalysis/Services/AccessServices/PermissionService.cs b/RelationshipAnalysis/Services/AccessServices/PermissionService.cs index c7dcb0e..43b487b 100644 --- a/RelationshipAnalysis/Services/AccessServices/PermissionService.cs +++ b/RelationshipAnalysis/Services/AccessServices/PermissionService.cs @@ -7,7 +7,7 @@ namespace RelationshipAnalysis.Services.AccessServices; -public class PermissionService(ApplicationDbContext context) : IPermissionService +public class PermissionService(IServiceProvider serviceProvider) : IPermissionService { public async Task> GetPermissionsAsync(ClaimsPrincipal userClaims) { @@ -32,6 +32,8 @@ public async Task> GetPermissionsAsync(ClaimsPrinc foreach (var roleName in roleNames) { + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); var role = await context.Roles .FirstOrDefaultAsync(r => r.Name == roleName); diff --git a/RelationshipAnalysis/Services/AdminPanelServices/AllUserService.cs b/RelationshipAnalysis/Services/AdminPanelServices/AllUserService.cs index b1e099b..acdf0f9 100644 --- a/RelationshipAnalysis/Services/AdminPanelServices/AllUserService.cs +++ b/RelationshipAnalysis/Services/AdminPanelServices/AllUserService.cs @@ -8,10 +8,12 @@ namespace RelationshipAnalysis.Services.AdminPanelServices; -public class AllUserService(ApplicationDbContext context, IMapper mapper, IRoleReceiver rolesReceiver) : IAllUserService +public class AllUserService(IServiceProvider serviceProvider, IMapper mapper, IRoleReceiver rolesReceiver) : IAllUserService { public int ReceiveAllUserCount() { + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); var users = context.Users.ToList(); return users.Count; } diff --git a/RelationshipAnalysis/Services/AdminPanelServices/RoleReceiver.cs b/RelationshipAnalysis/Services/AdminPanelServices/RoleReceiver.cs index 64d33a4..f133396 100644 --- a/RelationshipAnalysis/Services/AdminPanelServices/RoleReceiver.cs +++ b/RelationshipAnalysis/Services/AdminPanelServices/RoleReceiver.cs @@ -3,16 +3,21 @@ namespace RelationshipAnalysis.Services.AdminPanelServices; -public class RoleReceiver(ApplicationDbContext context) : IRoleReceiver +public class RoleReceiver(IServiceProvider serviceProvider) : IRoleReceiver { public List ReceiveRoles(int userId) { + + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); return context.UserRoles.ToList().FindAll(ur => ur.UserId == userId) .Select(ur => ur.Role.Name).ToList(); } public List ReceiveAllRoles() { + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); return context.Roles.Select(x => x.Name).ToList(); } } \ No newline at end of file diff --git a/RelationshipAnalysis/Services/AdminPanelServices/UserCreateService.cs b/RelationshipAnalysis/Services/AdminPanelServices/UserCreateService.cs index 9db5d17..0027272 100644 --- a/RelationshipAnalysis/Services/AdminPanelServices/UserCreateService.cs +++ b/RelationshipAnalysis/Services/AdminPanelServices/UserCreateService.cs @@ -9,10 +9,13 @@ namespace RelationshipAnalysis.Services.AdminPanelServices; -public class UserCreateService(ApplicationDbContext context, IPasswordHasher passwordHasher) : IUserCreateService +public class UserCreateService(IServiceProvider serviceProvider, IPasswordHasher passwordHasher) : IUserCreateService { public async Task> CreateUser(CreateUserDto createUserDto) { + + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); var isUserExist = context.Users.Select(x => x.Username).ToList().Contains(createUserDto.Username); if (isUserExist) { @@ -56,8 +59,12 @@ private ActionResponse SuccessResult() private async Task AddUserRoles(CreateUserDto createUserDto, User user) { var roles = new List(); + + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); foreach (var roleName in createUserDto.Roles) { + var role = await context.Roles .SingleOrDefaultAsync(r => r.Name == roleName); @@ -87,6 +94,9 @@ private async Task AddUser(CreateUserDto createUserDto) FirstName = createUserDto.FirstName, LastName = createUserDto.LastName, }; + + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); await context.AddAsync(user); await context.SaveChangesAsync(); return user; diff --git a/RelationshipAnalysis/Services/AdminPanelServices/UserDeleteService.cs b/RelationshipAnalysis/Services/AdminPanelServices/UserDeleteService.cs index f7470f6..e4de951 100644 --- a/RelationshipAnalysis/Services/AdminPanelServices/UserDeleteService.cs +++ b/RelationshipAnalysis/Services/AdminPanelServices/UserDeleteService.cs @@ -6,7 +6,7 @@ namespace RelationshipAnalysis.Services.AdminPanelServices; -public class UserDeleteService(ApplicationDbContext context) : IUserDeleteService +public class UserDeleteService(IServiceProvider serviceProvider) : IUserDeleteService { public async Task> DeleteUser(User user) { @@ -15,6 +15,8 @@ public async Task> DeleteUser(User user) return NotFoundResult(); } + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); context.Remove(user); await context.SaveChangesAsync(); return SuccessResult(); diff --git a/RelationshipAnalysis/Services/AdminPanelServices/UserUpdateRolesService.cs b/RelationshipAnalysis/Services/AdminPanelServices/UserUpdateRolesService.cs index 309636c..19aebc4 100644 --- a/RelationshipAnalysis/Services/AdminPanelServices/UserUpdateRolesService.cs +++ b/RelationshipAnalysis/Services/AdminPanelServices/UserUpdateRolesService.cs @@ -8,7 +8,7 @@ namespace RelationshipAnalysis.Services.AdminPanelServices; -public class UserUpdateRolesService(ApplicationDbContext context) : IUserUpdateRolesService +public class UserUpdateRolesService(IServiceProvider serviceProvider) : IUserUpdateRolesService { public async Task> UpdateUserRolesAsync(User user, List newRoles) { @@ -17,6 +17,8 @@ public async Task> UpdateUserRolesAsync(User user, Li return BadRequestResult(Resources.EmptyRolesMessage); } + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); var invalidRoles = newRoles.FindAll(r => !context.Roles.Select(R => R.Name) .Contains(r)); if (invalidRoles.Any()) @@ -32,6 +34,9 @@ public async Task> UpdateUserRolesAsync(User user, Li private async Task RemoveUserRoles(User user) { + + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); var userRoles = context.UserRoles.ToList().FindAll(r => r.UserId == user.Id); context.RemoveRange(userRoles); await context.SaveChangesAsync(); @@ -48,6 +53,9 @@ private ActionResponse SuccessResult() private async Task AddUserRoles(List newRoles, User user) { + + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); var roles = newRoles.Select(r => context.Roles .SingleOrDefaultAsync(R => R.Name == r)); roles.ToList().ForEach(r => context.UserRoles.Add(new UserRole() diff --git a/RelationshipAnalysis/Services/UserPanelServices/Abstraction/AuthServices/Abstraction/ILoginService.cs b/RelationshipAnalysis/Services/UserPanelServices/Abstraction/AuthServices/Abstraction/ILoginService.cs index 2aa6c15..8c182b9 100644 --- a/RelationshipAnalysis/Services/UserPanelServices/Abstraction/AuthServices/Abstraction/ILoginService.cs +++ b/RelationshipAnalysis/Services/UserPanelServices/Abstraction/AuthServices/Abstraction/ILoginService.cs @@ -1,4 +1,6 @@ -using RelationshipAnalysis.Dto; +using Microsoft.AspNetCore.Mvc; +using RelationshipAnalysis.Context; +using RelationshipAnalysis.Dto; namespace RelationshipAnalysis.Services.UserPanelServices.Abstraction.AuthServices.Abstraction; diff --git a/RelationshipAnalysis/Services/UserPanelServices/Abstraction/AuthServices/LoginService.cs b/RelationshipAnalysis/Services/UserPanelServices/Abstraction/AuthServices/LoginService.cs index 9dac462..7cb788e 100644 --- a/RelationshipAnalysis/Services/UserPanelServices/Abstraction/AuthServices/LoginService.cs +++ b/RelationshipAnalysis/Services/UserPanelServices/Abstraction/AuthServices/LoginService.cs @@ -1,4 +1,5 @@ -using Microsoft.EntityFrameworkCore; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; using RelationshipAnalysis.Context; using RelationshipAnalysis.Dto; using RelationshipAnalysis.Enums; @@ -7,7 +8,7 @@ namespace RelationshipAnalysis.Services.UserPanelServices.Abstraction.AuthServices; public class LoginService( - ApplicationDbContext context, + IServiceProvider serviceProvider, ICookieSetter cookieSetter, IJwtTokenGenerator jwtTokenGenerator, IPasswordVerifier passwordVerifier) @@ -16,7 +17,8 @@ public class LoginService( public async Task> LoginAsync(LoginDto loginModel, HttpResponse response) { var result = new ActionResponse(); - + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); var user = await context.Users .SingleOrDefaultAsync(u => u.Username == loginModel.Username); diff --git a/RelationshipAnalysis/Services/UserPanelServices/UserPasswordService.cs b/RelationshipAnalysis/Services/UserPanelServices/UserPasswordService.cs index d4360d6..a689055 100644 --- a/RelationshipAnalysis/Services/UserPanelServices/UserPasswordService.cs +++ b/RelationshipAnalysis/Services/UserPanelServices/UserPasswordService.cs @@ -7,7 +7,7 @@ namespace RelationshipAnalysis.Services.UserPanelServices; -public class UserPasswordService(ApplicationDbContext context, IPasswordVerifier passwordVerifier, IPasswordHasher passwordHasher) : IUserPasswordService +public class UserPasswordService(IServiceProvider serviceProvider, IPasswordVerifier passwordVerifier, IPasswordHasher passwordHasher) : IUserPasswordService { public async Task> UpdatePasswordAsync(User user, UserPasswordInfoDto passwordInfoDto) { @@ -20,6 +20,9 @@ public async Task> UpdatePasswordAsync(User user, Use return WrongPasswordResult(); } user.PasswordHash = passwordHasher.HashPassword(passwordInfoDto.NewPassword); + + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); context.Update(user); await context.SaveChangesAsync(); diff --git a/RelationshipAnalysis/Services/UserPanelServices/UserReceiver.cs b/RelationshipAnalysis/Services/UserPanelServices/UserReceiver.cs index 6f4791d..b34b152 100644 --- a/RelationshipAnalysis/Services/UserPanelServices/UserReceiver.cs +++ b/RelationshipAnalysis/Services/UserPanelServices/UserReceiver.cs @@ -6,23 +6,31 @@ namespace RelationshipAnalysis.Services.UserPanelServices; -public class UserReceiver(ApplicationDbContext context) : IUserReceiver +public class UserReceiver(IServiceProvider serviceProvider) : IUserReceiver { public async Task ReceiveUserAsync(ClaimsPrincipal userClaims) { var currentId = int.Parse(userClaims.FindFirst(ClaimTypes.NameIdentifier)?.Value); + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); var user = await context.Users.SingleOrDefaultAsync(u => u.Id == currentId); return user; } public async Task ReceiveUserAsync(int id) { + + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); var user = await context.Users.SingleOrDefaultAsync(u => u.Id == id); return user; } public List ReceiveAllUser(int page, int size) { + + using var scope = serviceProvider.CreateScope(); + var context = scope.ServiceProvider.GetRequiredService(); var users = context.Users.Skip(page * size).Take(size).ToList(); return users; } diff --git a/RelationshipAnalysis/Services/UserPanelServices/UserUpdateInfoService.cs b/RelationshipAnalysis/Services/UserPanelServices/UserUpdateInfoService.cs index cf81a14..c74c64b 100644 --- a/RelationshipAnalysis/Services/UserPanelServices/UserUpdateInfoService.cs +++ b/RelationshipAnalysis/Services/UserPanelServices/UserUpdateInfoService.cs @@ -7,11 +7,11 @@ namespace RelationshipAnalysis.Services.UserPanelServices; -public class UserUpdateInfoService(ApplicationDbContext context, IMapper mapper) : IUserUpdateInfoService +public class UserUpdateInfoService(IServiceProvider serviceProvider, IMapper mapper) : IUserUpdateInfoService { public async Task> UpdateUserAsync(User user, UserUpdateInfoDto userUpdateInfoDto, HttpResponse response) { - if (user is null) + if (user == null) { return NotFoundResult(); } @@ -25,33 +25,53 @@ public async Task> UpdateUserAsync(User user, UserUpd { return BadRequestResult(Resources.EmailExistsMessage); } + mapper.Map(userUpdateInfoDto, user); - context.Update(user); - await context.SaveChangesAsync(); + + using (var scope = serviceProvider.CreateScope()) + { + var context = scope.ServiceProvider.GetRequiredService(); + context.Update(user); + await context.SaveChangesAsync(); + } + return SuccessResult(); } private bool IsUsernameUnique(string currentValue, string newValue) { if (currentValue == newValue) return true; - return !context.Users.Select(u => u.Username).Contains(newValue); + + using (var scope = serviceProvider.CreateScope()) + { + var context = scope.ServiceProvider.GetRequiredService(); + return !context.Users.Any(u => u.Username == newValue); + } } + private bool IsEmailUnique(string currentValue, string newValue) { if (currentValue == newValue) return true; - return !context.Users.Select(u => u.Email).Contains(newValue); + + using (var scope = serviceProvider.CreateScope()) + { + var context = scope.ServiceProvider.GetRequiredService(); + return !context.Users.Any(u => u.Email == newValue); + } } + private ActionResponse BadRequestResult(string message) { - return new ActionResponse() + return new ActionResponse { Data = new MessageDto(message), StatusCode = StatusCodeType.BadRequest }; } + private ActionResponse NotFoundResult() { - return new ActionResponse() + return new ActionResponse { Data = new MessageDto(Resources.UserNotFoundMessage), StatusCode = StatusCodeType.NotFound @@ -60,7 +80,7 @@ private ActionResponse NotFoundResult() private ActionResponse SuccessResult() { - return new ActionResponse() + return new ActionResponse { Data = new MessageDto(Resources.SuccessfulUpdateUserMessage), StatusCode = StatusCodeType.Success