From 654cd159bc207108a800ec7864c138da05e74b2e Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Thu, 27 Mar 2025 19:05:15 +0100 Subject: [PATCH 01/28] Added RoleController --- .../Controllers/RoleController_Tests.cs | 667 ++++++++++++++++++ .../Controllers/UserController_Tests.cs | 4 +- MainProject/Controllers/RoleController.cs | 162 +++++ .../Middlewares/AutoMapperConfiguration.cs | 2 + MainProject/Models/Api/Common/Role/RoleDto.cs | 14 + .../Api/Request/Role/CreateRoleRequest.cs | 10 + .../Api/Response/Role/GetRoleResponse.cs | 8 + 7 files changed, 865 insertions(+), 2 deletions(-) create mode 100644 MainProject.Tests/Controllers/RoleController_Tests.cs create mode 100644 MainProject/Controllers/RoleController.cs create mode 100644 MainProject/Models/Api/Common/Role/RoleDto.cs create mode 100644 MainProject/Models/Api/Request/Role/CreateRoleRequest.cs create mode 100644 MainProject/Models/Api/Response/Role/GetRoleResponse.cs diff --git a/MainProject.Tests/Controllers/RoleController_Tests.cs b/MainProject.Tests/Controllers/RoleController_Tests.cs new file mode 100644 index 0000000..4c7d6f2 --- /dev/null +++ b/MainProject.Tests/Controllers/RoleController_Tests.cs @@ -0,0 +1,667 @@ +using System; +using System.Reflection; +using System.Net; +using System.Net.Http; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Infrastructure; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.Extensions.Configuration; +using Moq; +using BasicDotnetTemplate.MainProject.Controllers; +using BasicDotnetTemplate.MainProject.Services; +using BasicDotnetTemplate.MainProject.Models.Api.Response; +using BasicDotnetTemplate.MainProject.Models.Api.Common.Role; +using DatabaseSqlServer = BasicDotnetTemplate.MainProject.Models.Database.SqlServer; +using Microsoft.AspNetCore.Http; +using BasicDotnetTemplate.MainProject.Models.Api.Request.Role; +using BasicDotnetTemplate.MainProject.Models.Api.Data.Role; +using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; +using Newtonsoft.Json; + + +namespace BasicDotnetTemplate.MainProject.Tests; + +[TestClass] +public class RoleController_Tests +{ + private Mock? _roleServiceMock; + private RoleController? _roleController; + + [TestInitialize] + public void Setup() + { + IConfiguration configuration = TestUtils.CreateConfiguration(); + _roleServiceMock = new Mock(); + _roleController = new RoleController(configuration, _roleServiceMock?.Object); + } + + [TestMethod] + public void RoleController_NullConfiguration() + { + Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development"); + var exception = true; + try + { + var roleServiceMock = new Mock(); + _ = new RoleController(null, roleServiceMock.Object); + exception = false; + Assert.Fail($"This test should not pass as configuration is null"); + } + catch (Exception) + { + Assert.IsTrue(exception); + } + } + + + [TestMethod] + public async Task GetRoleByGuidAsync_Should_Return_200_When_Successful() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + var guid = Guid.NewGuid().ToString(); + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + ObjectResult response = (ObjectResult)(await _roleController.GetRoleByGuidAsync(guid)); + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status200OK); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status200OK); + Assert.IsInstanceOfType(result.Data, typeof(RoleDto)); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response value is null"); + } + } + + [TestMethod] + public async Task GetRoleByGuidAsync_GuidIsEmpty() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + var guid = String.Empty; + DatabaseSqlServer.Role? role = null; + + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + ObjectResult response = (ObjectResult)(await _roleController.GetRoleByGuidAsync(guid)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status400BadRequest); + Assert.IsTrue(result.Message == "Request is not well formed"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response value is null"); + } + } + + [TestMethod] + public async Task GetRoleByGuidAsync_NotFound() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + var guid = Guid.NewGuid().ToString(); + DatabaseSqlServer.Role? role = null; + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + NotFoundResult response = (NotFoundResult)(await _roleController.GetRoleByGuidAsync(guid)); + + Assert.IsInstanceOfType(response, typeof(NotFoundResult)); + + if (response != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status404NotFound); + } + else + { + Assert.Fail($"Response is null"); + } + } + + [TestMethod] + public async Task GetRoleByGuidAsync_ModelInvalid() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + var guid = Guid.NewGuid().ToString(); + DatabaseSqlServer.Role? role = null; + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + _roleController.ModelState.AddModelError("Data", "Invalid data"); + ObjectResult response = (ObjectResult)(await _roleController.GetRoleByGuidAsync(guid)); + + Assert.IsInstanceOfType(response, typeof(ObjectResult)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status400BadRequest); + Assert.IsTrue(result.Message == "Request is not well formed"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response is null"); + } + } + + [TestMethod] + public async Task GetRoleByGuidAsync_Exception() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + var guid = Guid.NewGuid().ToString(); + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ThrowsAsync(new Exception("Unexpected error")); + ObjectResult response = (ObjectResult)(await _roleController.GetRoleByGuidAsync(guid)); + + Assert.IsInstanceOfType(response, typeof(ObjectResult)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status500InternalServerError); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status500InternalServerError); + Assert.IsTrue(result.Message == "Something went wrong. Unexpected error"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response is null"); + } + } + + [TestMethod] + public async Task CreateRoleAsync_Should_Return_200_When_Successful() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + if (_roleServiceMock == null) + { + Assert.Fail($"_roleServiceMock is null"); + } + + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + + CreateRoleRequest request = new CreateRoleRequest() + { + Data = new CreateRoleRequestData() + { + Name = "RoleTest", + IsNotEditable = true + } + }; + + _roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny(), It.IsAny())).ReturnsAsync(true); + _roleServiceMock?.Setup(s => s.CreateRoleAsync(request.Data)).ReturnsAsync(role); + + ObjectResult response = (ObjectResult)(await _roleController.CreateRoleAsync(request)); + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status200OK); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status200OK); + Assert.IsInstanceOfType(result.Data, typeof(RoleDto)); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response value is null"); + } + } + + [TestMethod] + public async Task CreateRoleAsync_InvalidName() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + CreateRoleRequest request = new CreateRoleRequest() + { + Data = new CreateRoleRequestData() + { + Name = "RoleTest", + IsNotEditable = true + } + }; + + _roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny(), It.IsAny())).ReturnsAsync(false); + + ObjectResult response = (ObjectResult)(await _roleController.CreateRoleAsync(request)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status400BadRequest); + Assert.IsTrue(result.Message == "Invalid name"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response value is null"); + } + } + + [TestMethod] + public async Task CreateRoleAsync_CreateRoleRequestDataNull() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + + CreateRoleRequest request = new CreateRoleRequest() + { + Data = null + }; + + _roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny(), It.IsAny())).ReturnsAsync(true); + + _roleServiceMock?.Setup(s => s.CreateRoleAsync( + It.IsAny() + )).ReturnsAsync(role); + + ObjectResult response = (ObjectResult)(await _roleController.CreateRoleAsync(request)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status400BadRequest); + Assert.IsTrue(result.Message == "Request is not well formed"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response value is null"); + } + } + + [TestMethod] + public async Task CreateRoleAsync_NotCreated() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + if (_roleServiceMock == null) + { + Assert.Fail($"_roleServiceMock is null"); + } + + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + DatabaseSqlServer.Role? expectedRole = null; + + CreateRoleRequest request = new CreateRoleRequest() + { + Data = new CreateRoleRequestData() + { + Name = "RoleTest", + IsNotEditable = true + } + }; + + _roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny(), It.IsAny())).ReturnsAsync(true); + _roleServiceMock?.Setup(s => s.CreateRoleAsync(request.Data)).ReturnsAsync(expectedRole); + + ObjectResult response = (ObjectResult)(await _roleController.CreateRoleAsync(request)); + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status400BadRequest); + Assert.IsTrue(result.Message == "Not created"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response value is null"); + } + } + + [TestMethod] + public async Task CreateRoleAsync_ModelInvalid() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + + CreateRoleRequest request = new CreateRoleRequest() + { + Data = new CreateRoleRequestData() + { + Name = "RoleTest", + IsNotEditable = true + } + }; + + _roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny(), It.IsAny())).ReturnsAsync(true); + + _roleServiceMock?.Setup(s => s.CreateRoleAsync( + It.IsAny() + )).ReturnsAsync(role); + _roleController.ModelState.AddModelError("Data", "Invalid data"); + ObjectResult response = (ObjectResult)(await _roleController.CreateRoleAsync(request)); + + Assert.IsInstanceOfType(response, typeof(ObjectResult)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status400BadRequest); + Assert.IsTrue(result.Message == "Request is not well formed"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response is null"); + } + } + + [TestMethod] + public async Task CreateRoleAsync_Exception() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + if (_roleServiceMock == null) + { + Assert.Fail($"_roleServiceMock is null"); + } + + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + + CreateRoleRequest request = new CreateRoleRequest() + { + Data = new CreateRoleRequestData() + { + Name = "RoleTest", + IsNotEditable = true + } + }; + + _roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny(), It.IsAny())).ReturnsAsync(true); + _roleServiceMock?.Setup(s => s.CreateRoleAsync( + It.IsAny() + )).ThrowsAsync(new Exception("Unexpected error")); + + ObjectResult response = (ObjectResult)(await _roleController.CreateRoleAsync(request)); + Assert.IsInstanceOfType(response, typeof(ObjectResult)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status500InternalServerError); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status500InternalServerError); + Assert.IsTrue(result.Message == "Something went wrong. Unexpected error"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response is null"); + } + } + + + + [TestMethod] + public async Task DeleteRoleByGuidAsync_Success() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + var guid = Guid.NewGuid().ToString(); + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + ObjectResult response = (ObjectResult)(await _roleController.DeleteRoleByGuidAsync(guid)); + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status200OK); + } + else + { + Assert.Fail($"Response value is null"); + } + } + + [TestMethod] + public async Task DeleteRoleByGuidAsync_GuidIsEmpty() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + var guid = String.Empty; + DatabaseSqlServer.Role? role = null; + + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + ObjectResult response = (ObjectResult)(await _roleController.DeleteRoleByGuidAsync(guid)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status400BadRequest); + Assert.IsTrue(result.Message == "Request is not well formed"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response value is null"); + } + } + + [TestMethod] + public async Task DeleteRoleByGuidAsync_NotFound() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + var guid = Guid.NewGuid().ToString(); + DatabaseSqlServer.Role? role = null; + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + NotFoundResult response = (NotFoundResult)(await _roleController.DeleteRoleByGuidAsync(guid)); + + Assert.IsInstanceOfType(response, typeof(NotFoundResult)); + + if (response != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status404NotFound); + } + else + { + Assert.Fail($"Response is null"); + } + } + + [TestMethod] + public async Task DeleteRoleByGuidAsync_ModelInvalid() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + var guid = Guid.NewGuid().ToString(); + DatabaseSqlServer.Role? role = null; + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + _roleController.ModelState.AddModelError("Data", "Invalid data"); + ObjectResult response = (ObjectResult)(await _roleController.DeleteRoleByGuidAsync(guid)); + + Assert.IsInstanceOfType(response, typeof(ObjectResult)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status400BadRequest); + Assert.IsTrue(result.Message == "Request is not well formed"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response is null"); + } + } + + [TestMethod] + public async Task DeleteRoleByGuidAsync_Exception() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + var guid = Guid.NewGuid().ToString(); + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ThrowsAsync(new Exception("Unexpected error")); + ObjectResult response = (ObjectResult)(await _roleController.DeleteRoleByGuidAsync(guid)); + + Assert.IsInstanceOfType(response, typeof(ObjectResult)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status500InternalServerError); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status500InternalServerError); + Assert.IsTrue(result.Message == "Something went wrong. Unexpected error"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response is null"); + } + } + +} diff --git a/MainProject.Tests/Controllers/UserController_Tests.cs b/MainProject.Tests/Controllers/UserController_Tests.cs index 4dfd820..5f35a07 100644 --- a/MainProject.Tests/Controllers/UserController_Tests.cs +++ b/MainProject.Tests/Controllers/UserController_Tests.cs @@ -31,7 +31,7 @@ using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; namespace BasicDotnetTemplate.MainProject.Tests; [TestClass] -public class UserControllerTests +public class UserController_Tests { private Mock? _userServiceMock; private Mock? _roleServiceMock; @@ -100,7 +100,7 @@ public class UserControllerTests } [TestMethod] - public async Task GetUserByGuidAsync_AuthenticateRequestDataNull() + public async Task GetUserByGuidAsync_GuidIsEmpty() { if (_userController == null) { diff --git a/MainProject/Controllers/RoleController.cs b/MainProject/Controllers/RoleController.cs new file mode 100644 index 0000000..9a21b99 --- /dev/null +++ b/MainProject/Controllers/RoleController.cs @@ -0,0 +1,162 @@ +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using BasicDotnetTemplate.MainProject.Core.Attributes; +using BasicDotnetTemplate.MainProject.Services; +using BasicDotnetTemplate.MainProject.Models.Api.Request.Role; +using BasicDotnetTemplate.MainProject.Models.Api.Response; +using BasicDotnetTemplate.MainProject.Models.Api.Response.Role; +using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; +using BasicDotnetTemplate.MainProject.Models.Api.Common.Role; + +namespace BasicDotnetTemplate.MainProject.Controllers +{ + [Route("[controller]")] + public class RoleController : BaseController + { + private readonly IRoleService _roleService; + public RoleController( + IConfiguration configuration, + IRoleService roleService + ) : base(configuration) + { + this._roleService = roleService; + } + + [JwtAuthorization()] + [HttpGet("get/{guid}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType>(StatusCodes.Status404NotFound)] + [ProducesResponseType>(StatusCodes.Status400BadRequest)] + [ProducesResponseType>(StatusCodes.Status500InternalServerError)] + public async Task GetRoleByGuidAsync(string guid) + { + try + { + if (!ModelState.IsValid) + { + return BadRequest(_requestNotWellFormed); + } + + if (String.IsNullOrEmpty(guid)) + { + return BadRequest(_requestNotWellFormed); + } + var role = await this._roleService.GetRoleByGuidAsync(guid); + + if (role == null || String.IsNullOrEmpty(role.Guid)) + { + return NotFound(); + } + + var roleDto = _mapper?.Map(role); + + return Success(String.Empty, roleDto); + } + catch (Exception exception) + { + var message = "Something went wrong"; + if (!String.IsNullOrEmpty(exception.Message)) + { + message += $". {exception.Message}"; + } + return InternalServerError(message); + } + + } + + [JwtAuthorization()] + [HttpPost("create")] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType>(StatusCodes.Status400BadRequest)] + [ProducesResponseType>(StatusCodes.Status500InternalServerError)] + public async Task CreateRoleAsync([FromBody] CreateRoleRequest request) + { + try + { + if (!ModelState.IsValid) + { + return BadRequest(_requestNotWellFormed); + } + + if (request == null || request.Data == null || String.IsNullOrEmpty(request.Data.Name) + ) + { + return BadRequest(_requestNotWellFormed); + } + + if (await this._roleService.CheckIfNameIsValid(request.Data.Name)) + { + var role = await this._roleService.CreateRoleAsync(request.Data); + + if (role == null || String.IsNullOrEmpty(role.Guid)) + { + return BadRequest("Not created"); + } + + var roleDto = _mapper?.Map(role); + + return Success(String.Empty, roleDto); + } + else + { + return BadRequest("Invalid name"); + } + + } + catch (Exception exception) + { + var message = "Something went wrong"; + if (!String.IsNullOrEmpty(exception.Message)) + { + message += $". {exception.Message}"; + } + return InternalServerError(message); + } + + } + + [JwtAuthorization()] + [HttpDelete("{guid}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType>(StatusCodes.Status404NotFound)] + [ProducesResponseType>(StatusCodes.Status400BadRequest)] + [ProducesResponseType>(StatusCodes.Status500InternalServerError)] + public async Task DeleteRoleByGuidAsync(string guid) + { + try + { + if (!ModelState.IsValid) + { + return BadRequest(_requestNotWellFormed); + } + + if (String.IsNullOrEmpty(guid)) + { + return BadRequest(_requestNotWellFormed); + } + var role = await this._roleService.GetRoleByGuidAsync(guid); + + if (role == null || String.IsNullOrEmpty(role.Guid)) + { + return NotFound(); + } + + await this._roleService.DeleteRoleAsync(role); + + return Success(String.Empty); + } + catch (Exception exception) + { + var message = "Something went wrong"; + if (!String.IsNullOrEmpty(exception.Message)) + { + message += $". {exception.Message}"; + } + return InternalServerError(message); + } + + } + + + } +} \ No newline at end of file diff --git a/MainProject/Core/Middlewares/AutoMapperConfiguration.cs b/MainProject/Core/Middlewares/AutoMapperConfiguration.cs index bae74b0..6c0aa63 100644 --- a/MainProject/Core/Middlewares/AutoMapperConfiguration.cs +++ b/MainProject/Core/Middlewares/AutoMapperConfiguration.cs @@ -1,6 +1,7 @@ using BasicDotnetTemplate.MainProject.Models.Api.Common.User; using SqlServerDatabase = BasicDotnetTemplate.MainProject.Models.Database.SqlServer; using AutoMapper; +using BasicDotnetTemplate.MainProject.Models.Api.Common.Role; namespace BasicDotnetTemplate.MainProject.Core.Middlewares; @@ -8,6 +9,7 @@ public class AutoMapperConfiguration : Profile { public AutoMapperConfiguration() { + CreateMap(); CreateMap(); } diff --git a/MainProject/Models/Api/Common/Role/RoleDto.cs b/MainProject/Models/Api/Common/Role/RoleDto.cs new file mode 100644 index 0000000..a173f79 --- /dev/null +++ b/MainProject/Models/Api/Common/Role/RoleDto.cs @@ -0,0 +1,14 @@ +namespace BasicDotnetTemplate.MainProject.Models.Api.Common.Role; + +public class RoleDto +{ +#nullable enable + public string? Guid { get; set; } + public string? Name { get; set; } + public bool? IsNotEditable { get; set; } +#nullable disable +} + + + + diff --git a/MainProject/Models/Api/Request/Role/CreateRoleRequest.cs b/MainProject/Models/Api/Request/Role/CreateRoleRequest.cs new file mode 100644 index 0000000..d83636a --- /dev/null +++ b/MainProject/Models/Api/Request/Role/CreateRoleRequest.cs @@ -0,0 +1,10 @@ +using BasicDotnetTemplate.MainProject.Models.Api.Data.Role; + +namespace BasicDotnetTemplate.MainProject.Models.Api.Request.Role; + +public class CreateRoleRequest +{ +#nullable enable + public CreateRoleRequestData? Data { get; set; } +#nullable disable +} \ No newline at end of file diff --git a/MainProject/Models/Api/Response/Role/GetRoleResponse.cs b/MainProject/Models/Api/Response/Role/GetRoleResponse.cs new file mode 100644 index 0000000..957646c --- /dev/null +++ b/MainProject/Models/Api/Response/Role/GetRoleResponse.cs @@ -0,0 +1,8 @@ +using BasicDotnetTemplate.MainProject.Models.Api.Common.Role; + +namespace BasicDotnetTemplate.MainProject.Models.Api.Response.Role; + +public class GetRoleResponse : BaseResponse +{ + public GetRoleResponse(int status, string? message, RoleDto? data) : base(status, message, data) { } +} \ No newline at end of file -- 2.49.1 From f64e36764575618b21f2b83e9a6dfc57d2d705e2 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Thu, 27 Mar 2025 20:06:38 +0100 Subject: [PATCH 02/28] Added tests --- .../Response/Role/GetRoleResponse_Tests.cs | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 MainProject.Tests/Models/Api/Response/Role/GetRoleResponse_Tests.cs diff --git a/MainProject.Tests/Models/Api/Response/Role/GetRoleResponse_Tests.cs b/MainProject.Tests/Models/Api/Response/Role/GetRoleResponse_Tests.cs new file mode 100644 index 0000000..f7cce33 --- /dev/null +++ b/MainProject.Tests/Models/Api/Response/Role/GetRoleResponse_Tests.cs @@ -0,0 +1,102 @@ +using System; +using System.Reflection; +using System.Net; +using System.Net.Http; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using BasicDotnetTemplate.MainProject; +using BasicDotnetTemplate.MainProject.Models.Api.Response; +using Microsoft.Extensions.DependencyModel.Resolution; +using BasicDotnetTemplate.MainProject.Models.Api.Common.Role; +using BasicDotnetTemplate.MainProject.Models.Api.Response.Role; +using DatabaseSqlServer = BasicDotnetTemplate.MainProject.Models.Database.SqlServer; +using BasicDotnetTemplate.MainProject.Models.Api.Response.Auth; +using BasicDotnetTemplate.MainProject.Core.Middlewares; +using AutoMapper; +using Microsoft.AspNetCore.Http; + + +namespace BasicDotnetTemplate.MainProject.Tests; + +[TestClass] +public class GetRoleResponse_Tests +{ + private IMapper? _mapper; + + [TestInitialize] + public void Setup() + { + var config = new MapperConfiguration(cfg => + { + cfg.AddProfile(); + }); + + _mapper = config.CreateMapper(); + } + + [TestMethod] + public void IstantiateGetRoleResponse_OnlyStatus_Valid() + { + try + { + var getRoleResponse = new GetRoleResponse(200, null, null); + Assert.IsTrue(getRoleResponse.Status == StatusCodes.Status200OK && String.IsNullOrEmpty(getRoleResponse.Message) && getRoleResponse.Data == null); + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public void IstantiateGetRoleResponse_OnlyStatus_IsInvalid() + { + try + { + var getRoleResponse = new GetRoleResponse(201, null, null); + Assert.IsFalse(getRoleResponse.Status == StatusCodes.Status200OK); + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public void IstantiateGetRoleResponse_StatusAndMessage_Valid() + { + try + { + var getRoleResponse = new GetRoleResponse(200, "This is a test message", null); + Assert.IsTrue(getRoleResponse.Status == StatusCodes.Status200OK && getRoleResponse.Message == "This is a test message" && getRoleResponse.Data == null); + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public void IstantiateGetRoleResponse_AllFields_Valid() + { + try + { + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + RoleDto? data = _mapper?.Map(role); + var getRoleResponse = new GetRoleResponse(200, "This is a test message", data); + Assert.IsTrue(getRoleResponse.Status == StatusCodes.Status200OK && getRoleResponse.Message == "This is a test message" && getRoleResponse.Data == data); + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + +} + + + + -- 2.49.1 From d52c385e7cb89481f70a915fd1b0d06d8cd713ab Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Fri, 28 Mar 2025 20:19:26 +0100 Subject: [PATCH 03/28] Added role update endpoint --- .../Controllers/RoleController_Tests.cs | 286 ++++++++++++++++++ MainProject/Controllers/RoleController.cs | 60 ++++ MainProject/Services/RoleService.cs | 25 ++ 3 files changed, 371 insertions(+) diff --git a/MainProject.Tests/Controllers/RoleController_Tests.cs b/MainProject.Tests/Controllers/RoleController_Tests.cs index 4c7d6f2..50ecba3 100644 --- a/MainProject.Tests/Controllers/RoleController_Tests.cs +++ b/MainProject.Tests/Controllers/RoleController_Tests.cs @@ -54,6 +54,7 @@ public class RoleController_Tests } } + #region "GET" [TestMethod] public async Task GetRoleByGuidAsync_Should_Return_200_When_Successful() @@ -220,6 +221,10 @@ public class RoleController_Tests } } + #endregion + + #region "CREATE" + [TestMethod] public async Task CreateRoleAsync_Should_Return_200_When_Successful() { @@ -508,7 +513,9 @@ public class RoleController_Tests } } + #endregion + #region "DELETE" [TestMethod] public async Task DeleteRoleByGuidAsync_Success() @@ -664,4 +671,283 @@ public class RoleController_Tests } } + #endregion + + + + #region "UPDATE" + + [TestMethod] + public async Task UpdateRoleAsync_Should_Return_200_When_Successful() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + if (_roleServiceMock == null) + { + Assert.Fail($"_roleServiceMock is null"); + } + + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + + CreateRoleRequest request = new CreateRoleRequest() + { + Data = new CreateRoleRequestData() + { + Name = "RoleTest", + IsNotEditable = true + } + }; + + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + _roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny(), It.IsAny())).ReturnsAsync(true); + _roleServiceMock?.Setup(s => s.UpdateRoleAsync(It.IsAny(), It.IsAny())).ReturnsAsync(role); + + ObjectResult response = (ObjectResult)(await _roleController.UpdateRoleAsync(request, role.Guid)); + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status200OK); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status200OK); + Assert.IsInstanceOfType(result.Data, typeof(RoleDto)); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response value is null"); + } + } + + [TestMethod] + public async Task UpdateRoleAsync_RoleNotFound() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + DatabaseSqlServer.Role? role = null; + + CreateRoleRequest request = new CreateRoleRequest() + { + Data = new CreateRoleRequestData() + { + Name = "RoleTest", + IsNotEditable = true + } + }; + + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + + NotFoundResult response = (NotFoundResult)(await _roleController.UpdateRoleAsync(request, Guid.NewGuid().ToString())); + + if (response != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status404NotFound); + } + else + { + Assert.Fail($"Response is null"); + } + } + + [TestMethod] + public async Task UpdateRoleAsync_InvalidName() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + + CreateRoleRequest request = new CreateRoleRequest() + { + Data = new CreateRoleRequestData() + { + Name = "RoleTest", + IsNotEditable = true + } + }; + + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + _roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny(), It.IsAny())).ReturnsAsync(false); + + ObjectResult response = (ObjectResult)(await _roleController.UpdateRoleAsync(request, role.Guid)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status400BadRequest); + Assert.IsTrue(result.Message == "Invalid name"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response value is null"); + } + } + + [TestMethod] + public async Task UpdateRoleAsync_CreateRoleRequestDataNull() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + + CreateRoleRequest request = new CreateRoleRequest() + { + Data = null + }; + + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + _roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny(), It.IsAny())).ReturnsAsync(true); + _roleServiceMock?.Setup(s => s.UpdateRoleAsync(It.IsAny(), It.IsAny())).ReturnsAsync(role); + + ObjectResult response = (ObjectResult)(await _roleController.UpdateRoleAsync(request, role.Guid)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status400BadRequest); + Assert.IsTrue(result.Message == "Request is not well formed"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response value is null"); + } + } + + [TestMethod] + public async Task UpdateRoleAsync_ModelInvalid() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + + CreateRoleRequest request = new CreateRoleRequest() + { + Data = new CreateRoleRequestData() + { + Name = "RoleTest", + IsNotEditable = true + } + }; + + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + _roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny(), It.IsAny())).ReturnsAsync(true); + _roleServiceMock?.Setup(s => s.UpdateRoleAsync(It.IsAny(), It.IsAny())).ReturnsAsync(role); + _roleController.ModelState.AddModelError("Data", "Invalid data"); + ObjectResult response = (ObjectResult)(await _roleController.UpdateRoleAsync(request, role.Guid)); + + Assert.IsInstanceOfType(response, typeof(ObjectResult)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status400BadRequest); + Assert.IsTrue(result.Message == "Request is not well formed"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response is null"); + } + } + + [TestMethod] + public async Task UpdateRoleAsync_Exception() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + if (_roleServiceMock == null) + { + Assert.Fail($"_roleServiceMock is null"); + } + + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + + CreateRoleRequest request = new CreateRoleRequest() + { + Data = new CreateRoleRequestData() + { + Name = "RoleTest", + IsNotEditable = true + } + }; + + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + _roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny(), It.IsAny())).ReturnsAsync(true); + _roleServiceMock?.Setup(s => s.UpdateRoleAsync( + It.IsAny(), It.IsAny() + )).ThrowsAsync(new Exception("Unexpected error")); + + ObjectResult response = (ObjectResult)(await _roleController.UpdateRoleAsync(request, role.Guid)); + Assert.IsInstanceOfType(response, typeof(ObjectResult)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status500InternalServerError); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status500InternalServerError); + Assert.IsTrue(result.Message == "Something went wrong. Unexpected error"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response is null"); + } + } + + #endregion } diff --git a/MainProject/Controllers/RoleController.cs b/MainProject/Controllers/RoleController.cs index 9a21b99..e2f64be 100644 --- a/MainProject/Controllers/RoleController.cs +++ b/MainProject/Controllers/RoleController.cs @@ -115,6 +115,66 @@ namespace BasicDotnetTemplate.MainProject.Controllers } + [JwtAuthorization()] + [HttpPut("update/{guid}")] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType>(StatusCodes.Status400BadRequest)] + [ProducesResponseType>(StatusCodes.Status500InternalServerError)] + public async Task UpdateRoleAsync([FromBody] CreateRoleRequest request, string guid) + { + try + { + if (!ModelState.IsValid) + { + return BadRequest(_requestNotWellFormed); + } + + if ( + request == null || + request.Data == null || + String.IsNullOrEmpty(request.Data.Name) || + String.IsNullOrEmpty(guid) + ) + { + return BadRequest(_requestNotWellFormed); + } + + var role = await this._roleService.GetRoleByGuidAsync(guid); + + if (role == null || String.IsNullOrEmpty(role.Guid)) + { + return NotFound(); + } + + if ( + await this._roleService.CheckIfNameIsValid(request.Data.Name) || + await this._roleService.CheckIfNameIsValid(request.Data.Name, guid) + ) + { + role = await this._roleService.UpdateRoleAsync(request.Data, role); + + var roleDto = _mapper?.Map(role); + + return Success(String.Empty, roleDto); + } + else + { + return BadRequest("Invalid name"); + } + + } + catch (Exception exception) + { + var message = "Something went wrong"; + if (!String.IsNullOrEmpty(exception.Message)) + { + message += $". {exception.Message}"; + } + return InternalServerError(message); + } + + } + [JwtAuthorization()] [HttpDelete("{guid}")] [ProducesResponseType(StatusCodes.Status200OK)] diff --git a/MainProject/Services/RoleService.cs b/MainProject/Services/RoleService.cs index 96f127b..713469f 100644 --- a/MainProject/Services/RoleService.cs +++ b/MainProject/Services/RoleService.cs @@ -13,6 +13,7 @@ public interface IRoleService Task GetRoleByGuidAsync(string guid); Task CheckIfNameIsValid(string name, string? guid = ""); Task CreateRoleAsync(CreateRoleRequestData data); + Task UpdateRoleAsync(CreateRoleRequestData data, Role role); Task GetRoleForUser(string? guid); Task DeleteRoleAsync(Role role); } @@ -113,6 +114,30 @@ public class RoleService : BaseService, IRoleService return role; } + public async Task UpdateRoleAsync(CreateRoleRequestData data, Role role) + { + using var transaction = await _sqlServerContext.Database.BeginTransactionAsync(); + + try + { + role.Name = data.Name; + role.IsNotEditable = data.IsNotEditable; + role.UpdateTime = DateTime.UtcNow; + role.UpdateUserId = this.GetCurrentUserId(); + + _sqlServerContext.Roles.Update(role); + await _sqlServerContext.SaveChangesAsync(); + await transaction.CommitAsync(); + } + catch (Exception exception) + { + await transaction.RollbackAsync(); + Logger.Error(exception, $"[RoleService][UpdateRoleAsync]"); + } + + return role; + } + public async Task GetRoleForUser(string? guid) { Role? role = null; -- 2.49.1 From 366962abfafdd2124c88cb3ef3821391382fcb2b Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Fri, 28 Mar 2025 22:15:39 +0100 Subject: [PATCH 04/28] Adding tests --- .../Controllers/RoleController_Tests.cs | 46 ++++++ .../Controllers/RootController_Tests.cs | 1 - .../Controllers/UserController_Tests.cs | 2 +- .../Controllers/VersionController_Tests.cs | 3 - MainProject.Tests/Program_Tests.cs | 1 - .../Services/RoleService_Tests.cs | 143 +++++++++++++++++- .../Services/UserService_Tests.cs | 46 ++++++ MainProject.Tests/TestsUtils/TestUtils.cs | 29 +++- MainProject.Tests/Utils/CryptoUtils_Tests.cs | 2 - MainProject.Tests/Utils/ProgramUtils_Tests.cs | 1 - MainProject/Controllers/RoleController.cs | 5 + MainProject/Services/RoleService.cs | 3 + MainProject/Services/UserService.cs | 5 +- 13 files changed, 271 insertions(+), 16 deletions(-) diff --git a/MainProject.Tests/Controllers/RoleController_Tests.cs b/MainProject.Tests/Controllers/RoleController_Tests.cs index 50ecba3..7bfd290 100644 --- a/MainProject.Tests/Controllers/RoleController_Tests.cs +++ b/MainProject.Tests/Controllers/RoleController_Tests.cs @@ -805,6 +805,52 @@ public class RoleController_Tests } } + [TestMethod] + public async Task UpdateRoleAsync_NotEditable() + { + if (_roleController == null) + { + Assert.Fail($"_roleController is null"); + } + + DatabaseSqlServer.Role role = ModelsInit.CreateRole(); + role.IsNotEditable = true; + + CreateRoleRequest request = new CreateRoleRequest() + { + Data = new CreateRoleRequestData() + { + Name = "RoleTest", + IsNotEditable = true + } + }; + + _roleServiceMock?.Setup(s => s.GetRoleByGuidAsync(It.IsAny())).ReturnsAsync(role); + _roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny(), It.IsAny())).ReturnsAsync(false); + + ObjectResult response = (ObjectResult)(await _roleController.UpdateRoleAsync(request, role.Guid)); + + if (response != null && response.Value != null) + { + Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest); + + var result = (BaseResponse)response.Value; + if (result != null) + { + Assert.IsTrue(result.Status == StatusCodes.Status400BadRequest); + Assert.IsTrue(result.Message == "This role is not editable"); + } + else + { + Assert.Fail($"Result value is null"); + } + } + else + { + Assert.Fail($"Response value is null"); + } + } + [TestMethod] public async Task UpdateRoleAsync_CreateRoleRequestDataNull() { diff --git a/MainProject.Tests/Controllers/RootController_Tests.cs b/MainProject.Tests/Controllers/RootController_Tests.cs index 199c7f6..05ae28f 100644 --- a/MainProject.Tests/Controllers/RootController_Tests.cs +++ b/MainProject.Tests/Controllers/RootController_Tests.cs @@ -39,7 +39,6 @@ public class RootController_Test } catch (Exception ex) { - Console.WriteLine(ex.InnerException); Assert.Fail($"An exception was thrown: {ex}"); } } diff --git a/MainProject.Tests/Controllers/UserController_Tests.cs b/MainProject.Tests/Controllers/UserController_Tests.cs index 5f35a07..1e4c415 100644 --- a/MainProject.Tests/Controllers/UserController_Tests.cs +++ b/MainProject.Tests/Controllers/UserController_Tests.cs @@ -232,7 +232,7 @@ public class UserController_Tests } [TestMethod] - public async Task CreateUserAsync_Should_Return_200_When_Successful() + public async Task CreateUserAsync_Success() { if (_userController == null) { diff --git a/MainProject.Tests/Controllers/VersionController_Tests.cs b/MainProject.Tests/Controllers/VersionController_Tests.cs index 7f38ef7..b19c318 100644 --- a/MainProject.Tests/Controllers/VersionController_Tests.cs +++ b/MainProject.Tests/Controllers/VersionController_Tests.cs @@ -68,7 +68,6 @@ public class VersionController_Tests } catch (Exception ex) { - Console.WriteLine(ex.InnerException); Assert.Fail($"An exception was thrown: {ex}"); } } @@ -80,7 +79,6 @@ public class VersionController_Tests try { - Console.WriteLine(System.AppDomain.CurrentDomain.BaseDirectory); var configuration = TestUtils.CreateEmptyConfiguration(System.AppDomain.CurrentDomain.BaseDirectory + "/JsonData", "emptyAppsettings.json"); VersionController versionController = new VersionController(configuration); var result = versionController.GetVersion(); @@ -97,7 +95,6 @@ public class VersionController_Tests } catch (Exception ex) { - Console.WriteLine(ex.InnerException); Assert.Fail($"An exception was thrown: {ex}"); } } diff --git a/MainProject.Tests/Program_Tests.cs b/MainProject.Tests/Program_Tests.cs index 93588db..f485a02 100644 --- a/MainProject.Tests/Program_Tests.cs +++ b/MainProject.Tests/Program_Tests.cs @@ -69,7 +69,6 @@ public class Program_Tests } catch (Exception ex) { - Console.WriteLine(ex.InnerException); Assert.Fail($"An exception was thrown: {ex}"); } } diff --git a/MainProject.Tests/Services/RoleService_Tests.cs b/MainProject.Tests/Services/RoleService_Tests.cs index dfd172e..027012e 100644 --- a/MainProject.Tests/Services/RoleService_Tests.cs +++ b/MainProject.Tests/Services/RoleService_Tests.cs @@ -62,7 +62,7 @@ public class RoleService_Tests } [TestMethod] - public async Task CreateRoleData() + public async Task CreateRoleAsync_Success() { try { @@ -93,6 +93,42 @@ public class RoleService_Tests } } + [TestMethod] + public async Task CreateRoleAsync_Exception() + { + try + { + CreateRoleRequestData data = new CreateRoleRequestData() + { + Name = "Exception", + IsNotEditable = false + }; + + var exceptionRoleService = TestUtils.CreateRoleServiceException(); + + if (exceptionRoleService != null) + { + try + { + var role = await exceptionRoleService.CreateRoleAsync(data); + Assert.Fail($"Expected exception instead of response: {role?.Guid}"); + } + catch (Exception exception) + { + Assert.IsInstanceOfType(exception, typeof(Exception)); + } + } + else + { + Assert.Fail($"RoleService is null"); + } + } + catch (Exception ex) + { + Assert.Fail($"An exception was thrown: {ex}"); + } + } + [TestMethod] public async Task CheckIfNameIsValid_NameCurrentRole() { @@ -261,6 +297,111 @@ public class RoleService_Tests } } + [TestMethod] + public async Task UpdateRoleAsync_Success() + { + try + { + CreateRoleRequestData data = new CreateRoleRequestData() + { + Name = "ChangedRoleName", + IsNotEditable = false + }; + + if (_roleService != null) + { + Assert.IsNotNull(_role); + var role = await _roleService.UpdateRoleAsync(data, _role!); + Assert.IsInstanceOfType(role, typeof(Role)); + Assert.IsNotNull(role); + Assert.IsTrue(data.Name == role.Name); + Assert.IsTrue(data.IsNotEditable == role.IsNotEditable); + _role = role; + } + else + { + Assert.Fail($"RoleService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task UpdateRoleAsync_NotEditable() + { + try + { + CreateRoleRequestData createRoleData = new CreateRoleRequestData() + { + Name = "NotEditableRole", + IsNotEditable = true + }; + + + if (_roleService != null) + { + var role = await _roleService.CreateRoleAsync(createRoleData); + Assert.IsNotNull(role); + + CreateRoleRequestData updateRoleData = new CreateRoleRequestData() + { + Name = "TryingToEditRole", + IsNotEditable = false + }; + + var roleUpdatedRole = await _roleService.UpdateRoleAsync(updateRoleData, role!); + Assert.IsInstanceOfType(roleUpdatedRole, typeof(Role)); + Assert.IsNotNull(roleUpdatedRole); + Assert.IsTrue(roleUpdatedRole.Name == createRoleData.Name); + Assert.IsTrue(roleUpdatedRole.IsNotEditable == createRoleData.IsNotEditable); + } + else + { + Assert.Fail($"RoleService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task UpdateRoleAsync_Exception() + { + try + { + CreateRoleRequestData data = new CreateRoleRequestData() + { + Name = "Exception", + IsNotEditable = false + }; + + var exceptionRoleService = TestUtils.CreateRoleServiceException(); + + if (exceptionRoleService != null) + { + Assert.IsNotNull(_role); + var role = await exceptionRoleService.UpdateRoleAsync(data, _role!); + Assert.Fail($"Expected exception instead of response: {role?.Guid}"); + + } + else + { + Assert.Fail($"RoleService is null"); + } + } + catch (Exception ex) + { + Assert.IsInstanceOfType(ex, typeof(Exception)); + } + } + [TestMethod] public async Task DeleteRoleAsync() { diff --git a/MainProject.Tests/Services/UserService_Tests.cs b/MainProject.Tests/Services/UserService_Tests.cs index 3af26f7..74b0381 100644 --- a/MainProject.Tests/Services/UserService_Tests.cs +++ b/MainProject.Tests/Services/UserService_Tests.cs @@ -119,6 +119,52 @@ public class UserService_Tests } } + [TestMethod] + public async Task CreateUserAsync_Exception() + { + try + { + var expectedUser = ModelsInit.CreateUser(); + + CreateUserRequestData data = new CreateUserRequestData() + { + FirstName = expectedUser.FirstName ?? String.Empty, + LastName = expectedUser.LastName ?? String.Empty, + Email = expectedUser.Email ?? String.Empty + }; + + Role role = new() + { + Name = expectedUser.Role?.Name ?? String.Empty, + IsNotEditable = expectedUser.Role?.IsNotEditable ?? false, + Guid = expectedUser.Role?.Guid ?? String.Empty + }; + + var exceptionUserService = TestUtils.CreateUserServiceException(); + + if (exceptionUserService != null) + { + try + { + var user = await exceptionUserService.CreateUserAsync(data, role); + Assert.Fail($"Expected exception instead of response: {user?.Guid}"); + } + catch (Exception exception) + { + Assert.IsInstanceOfType(exception, typeof(Exception)); + } + } + else + { + Assert.Fail($"UserService is null"); + } + } + catch (Exception ex) + { + Assert.Fail($"An exception was thrown: {ex}"); + } + } + [TestMethod] public async Task CheckIfEmailIsValid_EmailCurrentUser() { diff --git a/MainProject.Tests/TestsUtils/TestUtils.cs b/MainProject.Tests/TestsUtils/TestUtils.cs index 099777c..aa21c64 100644 --- a/MainProject.Tests/TestsUtils/TestUtils.cs +++ b/MainProject.Tests/TestsUtils/TestUtils.cs @@ -64,6 +64,11 @@ public static class TestUtils return _appSettings.DatabaseSettings?.SqlServerConnectionString ?? String.Empty; } + public static string GetFakeConnectionString() + { + return "Server=127.0.0.1;Initial Catalog=MyFakeDatabase;User Id=MyFakeUser;Password='MyFakePassword';MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30"; + } + public static SqlServerContext CreateInMemorySqlContext() { var options = new DbContextOptionsBuilder() @@ -79,8 +84,6 @@ public static class TestUtils public static BaseService CreateBaseService() { IConfiguration configuration = CreateConfiguration(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(GetSqlConnectionString(configuration)); SqlServerContext sqlServerContext = CreateInMemorySqlContext(); var httpContextAccessor = new Mock(); return new BaseService(httpContextAccessor.Object, configuration, sqlServerContext); @@ -89,8 +92,6 @@ public static class TestUtils public static AuthService CreateAuthService() { IConfiguration configuration = CreateConfiguration(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(GetSqlConnectionString(configuration)); SqlServerContext sqlServerContext = CreateInMemorySqlContext(); var userServiceMock = new Mock(); var httpContextAccessor = new Mock(); @@ -105,6 +106,16 @@ public static class TestUtils return new UserService(httpContextAccessor.Object, configuration, sqlServerContext); } + public static UserService CreateUserServiceException() + { + IConfiguration configuration = CreateConfiguration(); + var optionsBuilder = new DbContextOptionsBuilder(); + optionsBuilder.UseSqlServer(GetFakeConnectionString()); + SqlServerContext sqlServerContext = new SqlServerContext(optionsBuilder.Options); + var httpContextAccessor = new Mock(); + return new UserService(httpContextAccessor.Object, configuration, sqlServerContext); + } + public static JwtService CreateJwtService() { IConfiguration configuration = CreateConfiguration(); @@ -124,6 +135,16 @@ public static class TestUtils var httpContextAccessor = new Mock(); return new RoleService(httpContextAccessor.Object, configuration, sqlServerContext); } + + public static RoleService CreateRoleServiceException() + { + IConfiguration configuration = CreateConfiguration(); + var optionsBuilder = new DbContextOptionsBuilder(); + optionsBuilder.UseSqlServer(GetFakeConnectionString()); + SqlServerContext sqlServerContext = new SqlServerContext(optionsBuilder.Options); + var httpContextAccessor = new Mock(); + return new RoleService(httpContextAccessor.Object, configuration, sqlServerContext); + } } diff --git a/MainProject.Tests/Utils/CryptoUtils_Tests.cs b/MainProject.Tests/Utils/CryptoUtils_Tests.cs index 4d2a7ab..c054658 100644 --- a/MainProject.Tests/Utils/CryptoUtils_Tests.cs +++ b/MainProject.Tests/Utils/CryptoUtils_Tests.cs @@ -151,8 +151,6 @@ public class CryptoUtils_Tests AppSettings appSettings = ProgramUtils.AddConfiguration(ref builder, System.AppDomain.CurrentDomain.BaseDirectory + "/JsonData"); CryptUtils cryptoUtils = new CryptUtils(appSettings); var verified = cryptoUtils.VerifyPassword(password, salt, 0, hashedPassword); - Console.WriteLine(cryptoUtils.GeneratePassword(password, salt, 0)); - Assert.IsTrue(verified); } catch (Exception ex) diff --git a/MainProject.Tests/Utils/ProgramUtils_Tests.cs b/MainProject.Tests/Utils/ProgramUtils_Tests.cs index 261236e..f6de5b9 100644 --- a/MainProject.Tests/Utils/ProgramUtils_Tests.cs +++ b/MainProject.Tests/Utils/ProgramUtils_Tests.cs @@ -299,7 +299,6 @@ public class ProgramUtils_Tests ProgramUtils.AddDbContext(ref builder, realAppSettings); var areEquals = expectedDbSettings.SqlServerConnectionString == realAppSettings.DatabaseSettings?.SqlServerConnectionString; - Console.WriteLine(realAppSettings.DatabaseSettings?.SqlServerConnectionString); Assert.IsTrue(areEquals); } catch (Exception ex) diff --git a/MainProject/Controllers/RoleController.cs b/MainProject/Controllers/RoleController.cs index e2f64be..7aad3c5 100644 --- a/MainProject/Controllers/RoleController.cs +++ b/MainProject/Controllers/RoleController.cs @@ -146,6 +146,11 @@ namespace BasicDotnetTemplate.MainProject.Controllers return NotFound(); } + if(role.IsNotEditable) + { + return BadRequest("This role is not editable"); + } + if ( await this._roleService.CheckIfNameIsValid(request.Data.Name) || await this._roleService.CheckIfNameIsValid(request.Data.Name, guid) diff --git a/MainProject/Services/RoleService.cs b/MainProject/Services/RoleService.cs index 713469f..703a939 100644 --- a/MainProject/Services/RoleService.cs +++ b/MainProject/Services/RoleService.cs @@ -116,6 +116,9 @@ public class RoleService : BaseService, IRoleService public async Task UpdateRoleAsync(CreateRoleRequestData data, Role role) { + if (role.IsNotEditable) + return role; + using var transaction = await _sqlServerContext.Database.BeginTransactionAsync(); try diff --git a/MainProject/Services/UserService.cs b/MainProject/Services/UserService.cs index ba471ab..f4be4e2 100644 --- a/MainProject/Services/UserService.cs +++ b/MainProject/Services/UserService.cs @@ -104,12 +104,13 @@ public class UserService : BaseService, IUserService public async Task CreateUserAsync(CreateUserRequestData data, Role role) { + User? user; + using var transaction = await _sqlServerContext.Database.BeginTransactionAsync(); - User? user; - var tempUser = CreateUserData(data, role); try { + var tempUser = CreateUserData(data, role); await _sqlServerContext.Users.AddAsync(tempUser); await _sqlServerContext.SaveChangesAsync(); await transaction.CommitAsync(); -- 2.49.1 From a648a2ea77878cecdd024b53cb5902cb0ed38446 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Fri, 28 Mar 2025 22:32:24 +0100 Subject: [PATCH 05/28] FIxing issues --- MainProject.Tests/Controllers/RoleController_Tests.cs | 2 +- MainProject/Controllers/AuthController.cs | 2 +- MainProject/Controllers/BaseController.cs | 1 + MainProject/Controllers/RoleController.cs | 10 +++++----- MainProject/Controllers/UserController.cs | 4 ++-- 5 files changed, 10 insertions(+), 9 deletions(-) diff --git a/MainProject.Tests/Controllers/RoleController_Tests.cs b/MainProject.Tests/Controllers/RoleController_Tests.cs index 7bfd290..5fcd784 100644 --- a/MainProject.Tests/Controllers/RoleController_Tests.cs +++ b/MainProject.Tests/Controllers/RoleController_Tests.cs @@ -33,7 +33,7 @@ public class RoleController_Tests { IConfiguration configuration = TestUtils.CreateConfiguration(); _roleServiceMock = new Mock(); - _roleController = new RoleController(configuration, _roleServiceMock?.Object); + _roleController = new RoleController(configuration, _roleServiceMock.Object); } [TestMethod] diff --git a/MainProject/Controllers/AuthController.cs b/MainProject/Controllers/AuthController.cs index 1baf173..6d9cb6f 100644 --- a/MainProject/Controllers/AuthController.cs +++ b/MainProject/Controllers/AuthController.cs @@ -55,7 +55,7 @@ namespace BasicDotnetTemplate.MainProject.Controllers } catch (Exception exception) { - var message = "Something went wrong"; + var message = this._somethingWentWrong; if (!String.IsNullOrEmpty(exception.Message)) { message += $". {exception.Message}"; diff --git a/MainProject/Controllers/BaseController.cs b/MainProject/Controllers/BaseController.cs index b8c8eb4..ec2f51b 100644 --- a/MainProject/Controllers/BaseController.cs +++ b/MainProject/Controllers/BaseController.cs @@ -13,6 +13,7 @@ namespace BasicDotnetTemplate.MainProject.Controllers protected readonly IConfiguration _configuration; protected readonly AppSettings _appSettings; protected readonly string _requestNotWellFormed = "Request is not well formed"; + protected readonly string _somethingWentWrong = "Something went wrong"; protected BaseController( IConfiguration configuration diff --git a/MainProject/Controllers/RoleController.cs b/MainProject/Controllers/RoleController.cs index 7aad3c5..5b369a1 100644 --- a/MainProject/Controllers/RoleController.cs +++ b/MainProject/Controllers/RoleController.cs @@ -54,7 +54,7 @@ namespace BasicDotnetTemplate.MainProject.Controllers } catch (Exception exception) { - var message = "Something went wrong"; + var message = this._somethingWentWrong; if (!String.IsNullOrEmpty(exception.Message)) { message += $". {exception.Message}"; @@ -105,7 +105,7 @@ namespace BasicDotnetTemplate.MainProject.Controllers } catch (Exception exception) { - var message = "Something went wrong"; + var message = this._somethingWentWrong; if (!String.IsNullOrEmpty(exception.Message)) { message += $". {exception.Message}"; @@ -146,7 +146,7 @@ namespace BasicDotnetTemplate.MainProject.Controllers return NotFound(); } - if(role.IsNotEditable) + if (role.IsNotEditable) { return BadRequest("This role is not editable"); } @@ -170,7 +170,7 @@ namespace BasicDotnetTemplate.MainProject.Controllers } catch (Exception exception) { - var message = "Something went wrong"; + var message = this._somethingWentWrong; if (!String.IsNullOrEmpty(exception.Message)) { message += $". {exception.Message}"; @@ -212,7 +212,7 @@ namespace BasicDotnetTemplate.MainProject.Controllers } catch (Exception exception) { - var message = "Something went wrong"; + var message = this._somethingWentWrong; if (!String.IsNullOrEmpty(exception.Message)) { message += $". {exception.Message}"; diff --git a/MainProject/Controllers/UserController.cs b/MainProject/Controllers/UserController.cs index 23ab705..cd9502b 100644 --- a/MainProject/Controllers/UserController.cs +++ b/MainProject/Controllers/UserController.cs @@ -57,7 +57,7 @@ namespace BasicDotnetTemplate.MainProject.Controllers } catch (Exception exception) { - var message = "Something went wrong"; + var message = this._somethingWentWrong; if (!String.IsNullOrEmpty(exception.Message)) { message += $". {exception.Message}"; @@ -118,7 +118,7 @@ namespace BasicDotnetTemplate.MainProject.Controllers } catch (Exception exception) { - var message = "Something went wrong"; + var message = this._somethingWentWrong; if (!String.IsNullOrEmpty(exception.Message)) { message += $". {exception.Message}"; -- 2.49.1 From df428b92014b14664d3aa234048f52c7181bf1e9 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Fri, 28 Mar 2025 22:38:10 +0100 Subject: [PATCH 06/28] Fixing issues --- MainProject.Tests/Controllers/UserController_Tests.cs | 2 +- MainProject/Services/RoleService.cs | 8 +++----- MainProject/Services/UserService.cs | 4 +--- 3 files changed, 5 insertions(+), 9 deletions(-) diff --git a/MainProject.Tests/Controllers/UserController_Tests.cs b/MainProject.Tests/Controllers/UserController_Tests.cs index 1e4c415..cc94f2b 100644 --- a/MainProject.Tests/Controllers/UserController_Tests.cs +++ b/MainProject.Tests/Controllers/UserController_Tests.cs @@ -43,7 +43,7 @@ public class UserController_Tests IConfiguration configuration = TestUtils.CreateConfiguration(); _userServiceMock = new Mock(); _roleServiceMock = new Mock(); - _userController = new UserController(configuration, _userServiceMock?.Object, _roleServiceMock.Object); + _userController = new UserController(configuration, _userServiceMock.Object, _roleServiceMock.Object); } [TestMethod] diff --git a/MainProject/Services/RoleService.cs b/MainProject/Services/RoleService.cs index 703a939..a52b174 100644 --- a/MainProject/Services/RoleService.cs +++ b/MainProject/Services/RoleService.cs @@ -20,7 +20,6 @@ public interface IRoleService public class RoleService : BaseService, IRoleService { - private readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); public RoleService( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, @@ -104,10 +103,9 @@ public class RoleService : BaseService, IRoleService await transaction.CommitAsync(); role = tempRole; } - catch (Exception exception) + catch (Exception) { await transaction.RollbackAsync(); - Logger.Error(exception, $"[RoleService][CreateRoleAsync]"); throw; } @@ -132,10 +130,10 @@ public class RoleService : BaseService, IRoleService await _sqlServerContext.SaveChangesAsync(); await transaction.CommitAsync(); } - catch (Exception exception) + catch (Exception) { await transaction.RollbackAsync(); - Logger.Error(exception, $"[RoleService][UpdateRoleAsync]"); + throw; } return role; diff --git a/MainProject/Services/UserService.cs b/MainProject/Services/UserService.cs index f4be4e2..9fb6253 100644 --- a/MainProject/Services/UserService.cs +++ b/MainProject/Services/UserService.cs @@ -19,7 +19,6 @@ public interface IUserService public class UserService : BaseService, IUserService { - private readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); public UserService( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, @@ -116,10 +115,9 @@ public class UserService : BaseService, IUserService await transaction.CommitAsync(); user = tempUser; } - catch (Exception exception) + catch (Exception) { await transaction.RollbackAsync(); - Logger.Error(exception, $"[UserService][CreateUserAsync]"); throw; } -- 2.49.1 From b778a357ba3edf30cb182f7aa6d1e3dc5b7a5263 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Fri, 28 Mar 2025 23:15:53 +0100 Subject: [PATCH 07/28] Fixing issues and improving coverage --- .../Models/Api/Common/Exceptions/CreateException.cs | 11 +++++++++++ .../Models/Api/Common/Exceptions/UpdateException.cs | 11 +++++++++++ MainProject/Services/RoleService.cs | 12 ++++++++---- MainProject/Services/UserService.cs | 7 +++++-- 4 files changed, 35 insertions(+), 6 deletions(-) create mode 100644 MainProject/Models/Api/Common/Exceptions/CreateException.cs create mode 100644 MainProject/Models/Api/Common/Exceptions/UpdateException.cs diff --git a/MainProject/Models/Api/Common/Exceptions/CreateException.cs b/MainProject/Models/Api/Common/Exceptions/CreateException.cs new file mode 100644 index 0000000..1b9edfa --- /dev/null +++ b/MainProject/Models/Api/Common/Exceptions/CreateException.cs @@ -0,0 +1,11 @@ +using System; + +namespace BasicDotnetTemplate.MainProject.Models.Api.Common.Exceptions; + +public class CreateException : Exception +{ + public CreateException(string message, Exception innerException) + : base(message, innerException) + { + } +} diff --git a/MainProject/Models/Api/Common/Exceptions/UpdateException.cs b/MainProject/Models/Api/Common/Exceptions/UpdateException.cs new file mode 100644 index 0000000..f4e15d4 --- /dev/null +++ b/MainProject/Models/Api/Common/Exceptions/UpdateException.cs @@ -0,0 +1,11 @@ +using System; + +namespace BasicDotnetTemplate.MainProject.Models.Api.Common.Exceptions; + +public class UpdateException : Exception +{ + public UpdateException(string message, Exception innerException) + : base(message, innerException) + { + } +} diff --git a/MainProject/Services/RoleService.cs b/MainProject/Services/RoleService.cs index a52b174..021f0a3 100644 --- a/MainProject/Services/RoleService.cs +++ b/MainProject/Services/RoleService.cs @@ -1,6 +1,7 @@ using System.Collections; using BasicDotnetTemplate.MainProject.Core.Database; +using BasicDotnetTemplate.MainProject.Models.Api.Common.Exceptions; using BasicDotnetTemplate.MainProject.Models.Api.Data.Role; using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; using Microsoft.EntityFrameworkCore; @@ -20,6 +21,7 @@ public interface IRoleService public class RoleService : BaseService, IRoleService { + private readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); public RoleService( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, @@ -103,10 +105,11 @@ public class RoleService : BaseService, IRoleService await transaction.CommitAsync(); role = tempRole; } - catch (Exception) + catch (Exception exception) { await transaction.RollbackAsync(); - throw; + Logger.Error(exception, $"[RoleService][CreateRoleAsync]"); + throw new CreateException($"An error occurred while saving the role for transaction ID {transaction.TransactionId}.", exception); } return role; @@ -130,10 +133,11 @@ public class RoleService : BaseService, IRoleService await _sqlServerContext.SaveChangesAsync(); await transaction.CommitAsync(); } - catch (Exception) + catch (Exception exception) { + Logger.Error(exception, $"[RoleService][UpdateRoleAsync] | {transaction.TransactionId}"); await transaction.RollbackAsync(); - throw; + throw new UpdateException($"An error occurred while updating the role for transaction ID {transaction.TransactionId}.", exception); } return role; diff --git a/MainProject/Services/UserService.cs b/MainProject/Services/UserService.cs index 9fb6253..11b44e4 100644 --- a/MainProject/Services/UserService.cs +++ b/MainProject/Services/UserService.cs @@ -1,6 +1,7 @@ using System.Collections; using BasicDotnetTemplate.MainProject.Core.Database; +using BasicDotnetTemplate.MainProject.Models.Api.Common.Exceptions; using BasicDotnetTemplate.MainProject.Models.Api.Data.User; using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; using Microsoft.EntityFrameworkCore; @@ -19,6 +20,7 @@ public interface IUserService public class UserService : BaseService, IUserService { + private readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); public UserService( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, @@ -115,10 +117,11 @@ public class UserService : BaseService, IUserService await transaction.CommitAsync(); user = tempUser; } - catch (Exception) + catch (Exception exception) { await transaction.RollbackAsync(); - throw; + Logger.Error(exception, $"[UserService][CreateUserAsync]"); + throw new CreateException($"An error occurred while creating the user for transaction ID {transaction.TransactionId}.", exception); } -- 2.49.1 From 2a5d7ff5f656a30e8e2d1725a3d6bb4f21252be7 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sat, 26 Apr 2025 23:40:07 +0200 Subject: [PATCH 08/28] Adding permissions' methods --- .../Services/RoleService_Tests.cs | 2 + MainProject/Core/Database/SqlServerContext.cs | 54 +- ...183010_AddingPermissionsTables.Designer.cs | 543 +++++++++++++++ .../20250426183010_AddingPermissionsTables.cs | 283 ++++++++ .../SqlServerContextModelSnapshot.cs | 373 ++++++++++ .../Database/SqlServer/PermissionModule.cs | 11 + .../Database/SqlServer/PermissionOperation.cs | 10 + .../Database/SqlServer/PermissionSystem.cs | 11 + .../SqlServer/PermissionSystemModule.cs | 13 + .../PermissionSystemModuleOperation.cs | 13 + .../RolePermissionSystemModuleOperation.cs | 13 + MainProject/Services/PermissionService.cs | 637 ++++++++++++++++++ 12 files changed, 1959 insertions(+), 4 deletions(-) create mode 100644 MainProject/Migrations/20250426183010_AddingPermissionsTables.Designer.cs create mode 100644 MainProject/Migrations/20250426183010_AddingPermissionsTables.cs create mode 100644 MainProject/Models/Database/SqlServer/PermissionModule.cs create mode 100644 MainProject/Models/Database/SqlServer/PermissionOperation.cs create mode 100644 MainProject/Models/Database/SqlServer/PermissionSystem.cs create mode 100644 MainProject/Models/Database/SqlServer/PermissionSystemModule.cs create mode 100644 MainProject/Models/Database/SqlServer/PermissionSystemModuleOperation.cs create mode 100644 MainProject/Models/Database/SqlServer/RolePermissionSystemModuleOperation.cs create mode 100644 MainProject/Services/PermissionService.cs diff --git a/MainProject.Tests/Services/RoleService_Tests.cs b/MainProject.Tests/Services/RoleService_Tests.cs index 027012e..188cf34 100644 --- a/MainProject.Tests/Services/RoleService_Tests.cs +++ b/MainProject.Tests/Services/RoleService_Tests.cs @@ -2,6 +2,8 @@ using BasicDotnetTemplate.MainProject.Services; using BasicDotnetTemplate.MainProject.Models.Api.Data.Role; using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; +using Newtonsoft.Json; +using BasicDotnetTemplate.MainProject.Models.Api.Common.Exceptions; diff --git a/MainProject/Core/Database/SqlServerContext.cs b/MainProject/Core/Database/SqlServerContext.cs index 68ccab1..f36d364 100644 --- a/MainProject/Core/Database/SqlServerContext.cs +++ b/MainProject/Core/Database/SqlServerContext.cs @@ -6,29 +6,75 @@ namespace BasicDotnetTemplate.MainProject.Core.Database { public class SqlServerContext : DbContext { + private const string _isDeletedFalse = "[IsDeleted] = 0"; + private const string _isEnabled = "[Enabled] = 1"; public SqlServerContext(DbContextOptions options) : base(options) { } - public DbSet Users { get; set; } + public DbSet PermissionModules { get; set; } + public DbSet PermissionOperations { get; set; } + public DbSet PermissionSystems { get; set; } + public DbSet PermissionSystemModules { get; set; } + public DbSet PermissionSystemModuleOperations { get; set; } + public DbSet RolePermissionSystemModuleOperations { get; set; } public DbSet Roles { get; set; } + public DbSet Users { get; set; } + protected override void OnModelCreating(ModelBuilder modelBuilder) { + #region "INDEXES" + // Indexes + modelBuilder.Entity() .HasIndex(x => x.Email, "IX_Email"); modelBuilder.Entity() .HasIndex(x => new { x.IsDeleted, x.Guid }, "IX_IsDeleted_Guid") - .HasFilter("[IsDeleted] = 0"); - + .HasFilter(_isDeletedFalse); modelBuilder.Entity() .HasIndex(x => new { x.IsDeleted, x.Guid }, "IX_IsDeleted_Guid") - .HasFilter("[IsDeleted] = 0"); + .HasFilter(_isDeletedFalse); + + modelBuilder.Entity() + .HasIndex(x => new { x.IsDeleted }, "IX_IsDeleted") + .HasFilter(_isDeletedFalse); + + modelBuilder.Entity() + .HasIndex(x => new { x.Enabled }, "IX_Enabled") + .HasFilter(_isEnabled); + + modelBuilder.Entity() + .HasIndex(x => new { x.IsDeleted, x.Name, x.Enabled }, "IX_IsDeleted_Name_Enabled") + .HasFilter(_isEnabled) + .HasFilter(_isDeletedFalse); + + modelBuilder.Entity() + .HasIndex(x => new { x.IsDeleted }, "IX_IsDeleted") + .HasFilter(_isDeletedFalse); + + modelBuilder.Entity() + .HasIndex(x => new { x.Enabled }, "IX_Enabled") + .HasFilter(_isEnabled); + + modelBuilder.Entity() + .HasIndex(x => new { x.IsDeleted, x.Name, x.Enabled }, "IX_IsDeleted_Name_Enabled") + .HasFilter(_isEnabled) + .HasFilter(_isDeletedFalse); + + modelBuilder.Entity() + .HasIndex(x => new { x.IsDeleted, x.Name }, "IX_IsDeleted_Name"); + + modelBuilder.Entity() + .HasIndex(x => new { x.IsDeleted, x.Enabled, x.Guid }, "IX_IsDeleted_Enabled_Guid"); + + #endregion + } } } diff --git a/MainProject/Migrations/20250426183010_AddingPermissionsTables.Designer.cs b/MainProject/Migrations/20250426183010_AddingPermissionsTables.Designer.cs new file mode 100644 index 0000000..6ee1838 --- /dev/null +++ b/MainProject/Migrations/20250426183010_AddingPermissionsTables.Designer.cs @@ -0,0 +1,543 @@ +// +using System; +using BasicDotnetTemplate.MainProject.Core.Database; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace MainProject.Migrations +{ + [DbContext(typeof(SqlServerContext))] + [Migration("20250426183010_AddingPermissionsTables")] + partial class AddingPermissionsTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionModule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex(new[] { "Enabled" }, "IX_Enabled") + .HasFilter("[Enabled] = 1"); + + b.HasIndex(new[] { "IsDeleted" }, "IX_IsDeleted") + .HasFilter("[IsDeleted] = 0"); + + b.HasIndex(new[] { "IsDeleted", "Name", "Enabled" }, "IX_IsDeleted_Name_Enabled") + .HasFilter("[IsDeleted] = 0"); + + b.ToTable("PermissionModules"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionOperation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex(new[] { "IsDeleted", "Name" }, "IX_IsDeleted_Name"); + + b.ToTable("PermissionOperations"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex(new[] { "Enabled" }, "IX_Enabled") + .HasFilter("[Enabled] = 1"); + + b.HasIndex(new[] { "IsDeleted" }, "IX_IsDeleted") + .HasFilter("[IsDeleted] = 0"); + + b.HasIndex(new[] { "IsDeleted", "Name", "Enabled" }, "IX_IsDeleted_Name_Enabled") + .HasFilter("[IsDeleted] = 0"); + + b.ToTable("PermissionSystems"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystemModule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("PermissionModuleId") + .HasColumnType("int"); + + b.Property("PermissionSystemId") + .HasColumnType("int"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("PermissionModuleId"); + + b.HasIndex("PermissionSystemId"); + + b.ToTable("PermissionSystemModules"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystemModuleOperation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("PermissionOperationId") + .HasColumnType("int"); + + b.Property("PermissionSystemModuleId") + .HasColumnType("int"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("PermissionOperationId"); + + b.HasIndex("PermissionSystemModuleId"); + + b.HasIndex(new[] { "IsDeleted", "Enabled", "Guid" }, "IX_IsDeleted_Enabled_Guid"); + + b.ToTable("PermissionSystemModuleOperations"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.Role", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("IsNotEditable") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex(new[] { "IsDeleted", "Guid" }, "IX_IsDeleted_Guid") + .HasFilter("[IsDeleted] = 0"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.RolePermissionSystemModuleOperation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("PermissionSystemModuleOperationId") + .HasColumnType("int"); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("PermissionSystemModuleOperationId"); + + b.HasIndex("RoleId"); + + b.ToTable("RolePermissionSystemModuleOperations"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("FirstName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("IsTestUser") + .HasColumnType("bit"); + + b.Property("LastName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("PasswordSalt") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex(new[] { "Email" }, "IX_Email"); + + b.HasIndex(new[] { "IsDeleted", "Guid" }, "IX_IsDeleted_Guid") + .HasFilter("[IsDeleted] = 0"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystemModule", b => + { + b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionModule", "PermissionModule") + .WithMany() + .HasForeignKey("PermissionModuleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystem", "PermissionSystem") + .WithMany() + .HasForeignKey("PermissionSystemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PermissionModule"); + + b.Navigation("PermissionSystem"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystemModuleOperation", b => + { + b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionOperation", "PermissionOperation") + .WithMany() + .HasForeignKey("PermissionOperationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystemModule", "PermissionSystemModule") + .WithMany() + .HasForeignKey("PermissionSystemModuleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PermissionOperation"); + + b.Navigation("PermissionSystemModule"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.RolePermissionSystemModuleOperation", b => + { + b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystemModuleOperation", "PermissionSystemModuleOperation") + .WithMany() + .HasForeignKey("PermissionSystemModuleOperationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.Role", "Role") + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PermissionSystemModuleOperation"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.User", b => + { + b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.Role", "Role") + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/MainProject/Migrations/20250426183010_AddingPermissionsTables.cs b/MainProject/Migrations/20250426183010_AddingPermissionsTables.cs new file mode 100644 index 0000000..3390e0d --- /dev/null +++ b/MainProject/Migrations/20250426183010_AddingPermissionsTables.cs @@ -0,0 +1,283 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace MainProject.Migrations +{ + /// + public partial class AddingPermissionsTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PermissionModules", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false), + Enabled = table.Column(type: "bit", nullable: false), + Guid = table.Column(type: "nvarchar(45)", maxLength: 45, nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreationTime = table.Column(type: "datetime2", nullable: false), + CreationUserId = table.Column(type: "int", nullable: true), + UpdateTime = table.Column(type: "datetime2", nullable: true), + UpdateUserId = table.Column(type: "int", nullable: true), + DeletionTime = table.Column(type: "datetime2", nullable: true), + DeletionUserId = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PermissionModules", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "PermissionOperations", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false), + Guid = table.Column(type: "nvarchar(45)", maxLength: 45, nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreationTime = table.Column(type: "datetime2", nullable: false), + CreationUserId = table.Column(type: "int", nullable: true), + UpdateTime = table.Column(type: "datetime2", nullable: true), + UpdateUserId = table.Column(type: "int", nullable: true), + DeletionTime = table.Column(type: "datetime2", nullable: true), + DeletionUserId = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PermissionOperations", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "PermissionSystems", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false), + Enabled = table.Column(type: "bit", nullable: false), + Guid = table.Column(type: "nvarchar(45)", maxLength: 45, nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreationTime = table.Column(type: "datetime2", nullable: false), + CreationUserId = table.Column(type: "int", nullable: true), + UpdateTime = table.Column(type: "datetime2", nullable: true), + UpdateUserId = table.Column(type: "int", nullable: true), + DeletionTime = table.Column(type: "datetime2", nullable: true), + DeletionUserId = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PermissionSystems", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "PermissionSystemModules", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + PermissionSystemId = table.Column(type: "int", nullable: false), + PermissionModuleId = table.Column(type: "int", nullable: false), + Enabled = table.Column(type: "bit", nullable: false), + Guid = table.Column(type: "nvarchar(45)", maxLength: 45, nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreationTime = table.Column(type: "datetime2", nullable: false), + CreationUserId = table.Column(type: "int", nullable: true), + UpdateTime = table.Column(type: "datetime2", nullable: true), + UpdateUserId = table.Column(type: "int", nullable: true), + DeletionTime = table.Column(type: "datetime2", nullable: true), + DeletionUserId = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PermissionSystemModules", x => x.Id); + table.ForeignKey( + name: "FK_PermissionSystemModules_PermissionModules_PermissionModuleId", + column: x => x.PermissionModuleId, + principalTable: "PermissionModules", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_PermissionSystemModules_PermissionSystems_PermissionSystemId", + column: x => x.PermissionSystemId, + principalTable: "PermissionSystems", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "PermissionSystemModuleOperations", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + PermissionSystemModuleId = table.Column(type: "int", nullable: false), + PermissionOperationId = table.Column(type: "int", nullable: false), + Enabled = table.Column(type: "bit", nullable: false), + Guid = table.Column(type: "nvarchar(45)", maxLength: 45, nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreationTime = table.Column(type: "datetime2", nullable: false), + CreationUserId = table.Column(type: "int", nullable: true), + UpdateTime = table.Column(type: "datetime2", nullable: true), + UpdateUserId = table.Column(type: "int", nullable: true), + DeletionTime = table.Column(type: "datetime2", nullable: true), + DeletionUserId = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PermissionSystemModuleOperations", x => x.Id); + table.ForeignKey( + name: "FK_PermissionSystemModuleOperations_PermissionOperations_PermissionOperationId", + column: x => x.PermissionOperationId, + principalTable: "PermissionOperations", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_PermissionSystemModuleOperations_PermissionSystemModules_PermissionSystemModuleId", + column: x => x.PermissionSystemModuleId, + principalTable: "PermissionSystemModules", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "RolePermissionSystemModuleOperations", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + RoleId = table.Column(type: "int", nullable: false), + PermissionSystemModuleOperationId = table.Column(type: "int", nullable: false), + Active = table.Column(type: "bit", nullable: false), + Guid = table.Column(type: "nvarchar(45)", maxLength: 45, nullable: false), + IsDeleted = table.Column(type: "bit", nullable: false), + CreationTime = table.Column(type: "datetime2", nullable: false), + CreationUserId = table.Column(type: "int", nullable: true), + UpdateTime = table.Column(type: "datetime2", nullable: true), + UpdateUserId = table.Column(type: "int", nullable: true), + DeletionTime = table.Column(type: "datetime2", nullable: true), + DeletionUserId = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_RolePermissionSystemModuleOperations", x => x.Id); + table.ForeignKey( + name: "FK_RolePermissionSystemModuleOperations_PermissionSystemModuleOperations_PermissionSystemModuleOperationId", + column: x => x.PermissionSystemModuleOperationId, + principalTable: "PermissionSystemModuleOperations", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_RolePermissionSystemModuleOperations_Roles_RoleId", + column: x => x.RoleId, + principalTable: "Roles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Enabled", + table: "PermissionModules", + column: "Enabled", + filter: "[Enabled] = 1"); + + migrationBuilder.CreateIndex( + name: "IX_IsDeleted", + table: "PermissionModules", + column: "IsDeleted", + filter: "[IsDeleted] = 0"); + + migrationBuilder.CreateIndex( + name: "IX_IsDeleted_Name_Enabled", + table: "PermissionModules", + columns: new[] { "IsDeleted", "Name", "Enabled" }, + filter: "[IsDeleted] = 0"); + + migrationBuilder.CreateIndex( + name: "IX_IsDeleted_Name", + table: "PermissionOperations", + columns: new[] { "IsDeleted", "Name" }); + + migrationBuilder.CreateIndex( + name: "IX_IsDeleted_Enabled_Guid", + table: "PermissionSystemModuleOperations", + columns: new[] { "IsDeleted", "Enabled", "Guid" }); + + migrationBuilder.CreateIndex( + name: "IX_PermissionSystemModuleOperations_PermissionOperationId", + table: "PermissionSystemModuleOperations", + column: "PermissionOperationId"); + + migrationBuilder.CreateIndex( + name: "IX_PermissionSystemModuleOperations_PermissionSystemModuleId", + table: "PermissionSystemModuleOperations", + column: "PermissionSystemModuleId"); + + migrationBuilder.CreateIndex( + name: "IX_PermissionSystemModules_PermissionModuleId", + table: "PermissionSystemModules", + column: "PermissionModuleId"); + + migrationBuilder.CreateIndex( + name: "IX_PermissionSystemModules_PermissionSystemId", + table: "PermissionSystemModules", + column: "PermissionSystemId"); + + migrationBuilder.CreateIndex( + name: "IX_Enabled", + table: "PermissionSystems", + column: "Enabled", + filter: "[Enabled] = 1"); + + migrationBuilder.CreateIndex( + name: "IX_IsDeleted", + table: "PermissionSystems", + column: "IsDeleted", + filter: "[IsDeleted] = 0"); + + migrationBuilder.CreateIndex( + name: "IX_IsDeleted_Name_Enabled", + table: "PermissionSystems", + columns: new[] { "IsDeleted", "Name", "Enabled" }, + filter: "[IsDeleted] = 0"); + + migrationBuilder.CreateIndex( + name: "IX_RolePermissionSystemModuleOperations_PermissionSystemModuleOperationId", + table: "RolePermissionSystemModuleOperations", + column: "PermissionSystemModuleOperationId"); + + migrationBuilder.CreateIndex( + name: "IX_RolePermissionSystemModuleOperations_RoleId", + table: "RolePermissionSystemModuleOperations", + column: "RoleId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "RolePermissionSystemModuleOperations"); + + migrationBuilder.DropTable( + name: "PermissionSystemModuleOperations"); + + migrationBuilder.DropTable( + name: "PermissionOperations"); + + migrationBuilder.DropTable( + name: "PermissionSystemModules"); + + migrationBuilder.DropTable( + name: "PermissionModules"); + + migrationBuilder.DropTable( + name: "PermissionSystems"); + } + } +} diff --git a/MainProject/Migrations/SqlServerContextModelSnapshot.cs b/MainProject/Migrations/SqlServerContextModelSnapshot.cs index 293a846..d32f3cb 100644 --- a/MainProject/Migrations/SqlServerContextModelSnapshot.cs +++ b/MainProject/Migrations/SqlServerContextModelSnapshot.cs @@ -22,6 +22,270 @@ namespace MainProject.Migrations SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionModule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex(new[] { "Enabled" }, "IX_Enabled") + .HasFilter("[Enabled] = 1"); + + b.HasIndex(new[] { "IsDeleted" }, "IX_IsDeleted") + .HasFilter("[IsDeleted] = 0"); + + b.HasIndex(new[] { "IsDeleted", "Name", "Enabled" }, "IX_IsDeleted_Name_Enabled") + .HasFilter("[IsDeleted] = 0"); + + b.ToTable("PermissionModules"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionOperation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex(new[] { "IsDeleted", "Name" }, "IX_IsDeleted_Name"); + + b.ToTable("PermissionOperations"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex(new[] { "Enabled" }, "IX_Enabled") + .HasFilter("[Enabled] = 1"); + + b.HasIndex(new[] { "IsDeleted" }, "IX_IsDeleted") + .HasFilter("[IsDeleted] = 0"); + + b.HasIndex(new[] { "IsDeleted", "Name", "Enabled" }, "IX_IsDeleted_Name_Enabled") + .HasFilter("[IsDeleted] = 0"); + + b.ToTable("PermissionSystems"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystemModule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("PermissionModuleId") + .HasColumnType("int"); + + b.Property("PermissionSystemId") + .HasColumnType("int"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("PermissionModuleId"); + + b.HasIndex("PermissionSystemId"); + + b.ToTable("PermissionSystemModules"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystemModuleOperation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("PermissionOperationId") + .HasColumnType("int"); + + b.Property("PermissionSystemModuleId") + .HasColumnType("int"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("PermissionOperationId"); + + b.HasIndex("PermissionSystemModuleId"); + + b.HasIndex(new[] { "IsDeleted", "Enabled", "Guid" }, "IX_IsDeleted_Enabled_Guid"); + + b.ToTable("PermissionSystemModuleOperations"); + }); + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.Role", b => { b.Property("Id") @@ -72,6 +336,58 @@ namespace MainProject.Migrations b.ToTable("Roles"); }); + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.RolePermissionSystemModuleOperation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Active") + .HasColumnType("bit"); + + b.Property("CreationTime") + .HasColumnType("datetime2"); + + b.Property("CreationUserId") + .HasColumnType("int"); + + b.Property("DeletionTime") + .HasColumnType("datetime2"); + + b.Property("DeletionUserId") + .HasColumnType("int"); + + b.Property("Guid") + .IsRequired() + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("PermissionSystemModuleOperationId") + .HasColumnType("int"); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("UpdateTime") + .HasColumnType("datetime2"); + + b.Property("UpdateUserId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("PermissionSystemModuleOperationId"); + + b.HasIndex("RoleId"); + + b.ToTable("RolePermissionSystemModuleOperations"); + }); + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.User", b => { b.Property("Id") @@ -151,6 +467,63 @@ namespace MainProject.Migrations b.ToTable("Users"); }); + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystemModule", b => + { + b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionModule", "PermissionModule") + .WithMany() + .HasForeignKey("PermissionModuleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystem", "PermissionSystem") + .WithMany() + .HasForeignKey("PermissionSystemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PermissionModule"); + + b.Navigation("PermissionSystem"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystemModuleOperation", b => + { + b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionOperation", "PermissionOperation") + .WithMany() + .HasForeignKey("PermissionOperationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystemModule", "PermissionSystemModule") + .WithMany() + .HasForeignKey("PermissionSystemModuleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PermissionOperation"); + + b.Navigation("PermissionSystemModule"); + }); + + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.RolePermissionSystemModuleOperation", b => + { + b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionSystemModuleOperation", "PermissionSystemModuleOperation") + .WithMany() + .HasForeignKey("PermissionSystemModuleOperationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.Role", "Role") + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("PermissionSystemModuleOperation"); + + b.Navigation("Role"); + }); + modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.User", b => { b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.Role", "Role") diff --git a/MainProject/Models/Database/SqlServer/PermissionModule.cs b/MainProject/Models/Database/SqlServer/PermissionModule.cs new file mode 100644 index 0000000..dba3a92 --- /dev/null +++ b/MainProject/Models/Database/SqlServer/PermissionModule.cs @@ -0,0 +1,11 @@ +using System.ComponentModel.DataAnnotations; + +namespace BasicDotnetTemplate.MainProject.Models.Database.SqlServer +{ + public class PermissionModule : Base + { + [MaxLength(100)] + public required string Name { get; set; } + public required bool Enabled { get; set; } + } +} \ No newline at end of file diff --git a/MainProject/Models/Database/SqlServer/PermissionOperation.cs b/MainProject/Models/Database/SqlServer/PermissionOperation.cs new file mode 100644 index 0000000..4080277 --- /dev/null +++ b/MainProject/Models/Database/SqlServer/PermissionOperation.cs @@ -0,0 +1,10 @@ +using System.ComponentModel.DataAnnotations; + +namespace BasicDotnetTemplate.MainProject.Models.Database.SqlServer +{ + public class PermissionOperation : Base + { + [MaxLength(100)] + public required string Name { get; set; } + } +} \ No newline at end of file diff --git a/MainProject/Models/Database/SqlServer/PermissionSystem.cs b/MainProject/Models/Database/SqlServer/PermissionSystem.cs new file mode 100644 index 0000000..7b28d33 --- /dev/null +++ b/MainProject/Models/Database/SqlServer/PermissionSystem.cs @@ -0,0 +1,11 @@ +using System.ComponentModel.DataAnnotations; + +namespace BasicDotnetTemplate.MainProject.Models.Database.SqlServer +{ + public class PermissionSystem : Base + { + [MaxLength(100)] + public required string Name { get; set; } + public required bool Enabled { get; set; } + } +} \ No newline at end of file diff --git a/MainProject/Models/Database/SqlServer/PermissionSystemModule.cs b/MainProject/Models/Database/SqlServer/PermissionSystemModule.cs new file mode 100644 index 0000000..84eef1f --- /dev/null +++ b/MainProject/Models/Database/SqlServer/PermissionSystemModule.cs @@ -0,0 +1,13 @@ +using System.ComponentModel.DataAnnotations; + +namespace BasicDotnetTemplate.MainProject.Models.Database.SqlServer +{ + public class PermissionSystemModule : Base + { + public required int PermissionSystemId { get; set; } + public required int PermissionModuleId { get; set; } + public required PermissionSystem PermissionSystem { get; set; } + public required PermissionModule PermissionModule { get; set; } + public required bool Enabled { get; set; } + } +} \ No newline at end of file diff --git a/MainProject/Models/Database/SqlServer/PermissionSystemModuleOperation.cs b/MainProject/Models/Database/SqlServer/PermissionSystemModuleOperation.cs new file mode 100644 index 0000000..deb5d8b --- /dev/null +++ b/MainProject/Models/Database/SqlServer/PermissionSystemModuleOperation.cs @@ -0,0 +1,13 @@ +using System.ComponentModel.DataAnnotations; + +namespace BasicDotnetTemplate.MainProject.Models.Database.SqlServer +{ + public class PermissionSystemModuleOperation : Base + { + public required int PermissionSystemModuleId { get; set; } + public required int PermissionOperationId { get; set; } + public required bool Enabled { get; set; } + public required PermissionSystemModule PermissionSystemModule { get; set; } + public required PermissionOperation PermissionOperation { get; set; } + } +} \ No newline at end of file diff --git a/MainProject/Models/Database/SqlServer/RolePermissionSystemModuleOperation.cs b/MainProject/Models/Database/SqlServer/RolePermissionSystemModuleOperation.cs new file mode 100644 index 0000000..d42be00 --- /dev/null +++ b/MainProject/Models/Database/SqlServer/RolePermissionSystemModuleOperation.cs @@ -0,0 +1,13 @@ +using System.ComponentModel.DataAnnotations; + +namespace BasicDotnetTemplate.MainProject.Models.Database.SqlServer +{ + public class RolePermissionSystemModuleOperation : Base + { + public required int RoleId { get; set; } + public required int PermissionSystemModuleOperationId { get; set; } + public required bool Active { get; set; } + public required Role Role { get; set; } + public required PermissionSystemModuleOperation PermissionSystemModuleOperation { get; set; } + } +} \ No newline at end of file diff --git a/MainProject/Services/PermissionService.cs b/MainProject/Services/PermissionService.cs new file mode 100644 index 0000000..ee7449a --- /dev/null +++ b/MainProject/Services/PermissionService.cs @@ -0,0 +1,637 @@ + +using System.Collections; +using BasicDotnetTemplate.MainProject.Core.Database; +using BasicDotnetTemplate.MainProject.Models.Api.Common.Exceptions; +using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; +using Microsoft.EntityFrameworkCore; + +namespace BasicDotnetTemplate.MainProject.Services; + +public interface IPermissionService +{ + Task GetPermissionSystemByGuidAsync(string guid); + Task GetPermissionSystemByNameAsync(string name); + Task HandleEnabledPermissionSystem(PermissionSystem permission, bool enabled); + Task CreatePermissionSystemAsync(string name, bool enabled); + Task DeletePermissionSystemAsync(PermissionSystem permission); + + + Task GetPermissionModuleByGuidAsync(string guid); + Task GetPermissionModuleByNameAsync(string name); + Task HandleEnabledPermissionModuleAsync(PermissionModule permission, bool enabled); + Task CreatePermissionModuleAsync(string name, bool enabled); + Task DeletePermissionModuleAsync(PermissionModule permission); + + + Task GetPermissionOperationByGuidAsync(string guid); + Task GetPermissionOperationByNameAsync(string name); + Task CreatePermissionOperationAsync(string name); + Task DeletePermissionOperationAsync(PermissionOperation permission); + + + Task GetPermissionSystemModuleByGuidAsync(string guid); + Task HandleEnabledPermissionSystemModuleAsync(PermissionSystemModule permission, bool enabled); + Task CreatePermissionSystemModuleAsync( + PermissionSystem permissionSystem, + PermissionModule permissionModule, + bool enabled + ); + Task DeletePermissionSystemModuleAsync(PermissionSystemModule permission); + + + Task GetPermissionSystemModuleOperationByGuidAsync(string guid); + Task HandleEnabledPermissionSystemModuleOperationAsync(PermissionSystemModuleOperation permission, bool enabled); + Task CreatePermissionSystemModuleOperationAsync( + PermissionSystemModule permissionSystemModule, + PermissionOperation permissionOperation, + bool enabled + ); + Task DeletePermissionSystemModuleOperationAsync(PermissionSystemModuleOperation permission); + + + Task GetRolePermissionSystemModuleOperationByGuidAsync(string guid); + Task HandleEnabledRolePermissionSystemModuleOperationAsync(RolePermissionSystemModuleOperation permission, bool active); + Task CreateRolePermissionSystemModuleOperationAsync( + Role role, + PermissionSystemModuleOperation permissionSystemModuleOperation, + bool enabled + ); + Task DeleteRolePermissionSystemModuleOperationAsync(RolePermissionSystemModuleOperation permission); +} + +public class PermissionService : BaseService, IPermissionService +{ + private readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); + public PermissionService( + IHttpContextAccessor httpContextAccessor, + IConfiguration configuration, + SqlServerContext sqlServerContext + ) : base(httpContextAccessor, configuration, sqlServerContext) + { } + + private IQueryable GetPermissionSystemsQueryable() + { + return this._sqlServerContext.PermissionSystems + .Where(x => !x.IsDeleted); + } + + private IQueryable GetPermissionModulesQueryable() + { + return this._sqlServerContext.PermissionModules + .Where(x => !x.IsDeleted); + } + + private IQueryable GetPermissionOperationsQueryable() + { + return this._sqlServerContext.PermissionOperations + .Where(x => !x.IsDeleted); + } + + private IQueryable GetPermissionSystemModulesQueryable() + { + return this._sqlServerContext.PermissionSystemModules + .Where(x => !x.IsDeleted); + } + + private IQueryable GetPermissionSystemModuleOperationsQueryable() + { + return this._sqlServerContext.PermissionSystemModuleOperations + .Include(x => x.PermissionOperation) + .Include(x => x.PermissionSystemModule) + .ThenInclude(x => x.PermissionSystem) + .Where(x => !x.IsDeleted); + } + + private IQueryable GetRolePermissionSystemModuleOperationsQueryable() + { + return this._sqlServerContext.RolePermissionSystemModuleOperations + .Include(x => x.Role) + .Include(x => x.PermissionSystemModuleOperation) + .ThenInclude(x => x.PermissionSystemModule) + .ThenInclude(x => x.PermissionSystem) + .Include(x => x.PermissionSystemModuleOperation) + .ThenInclude(x => x.PermissionSystemModule) + .ThenInclude(x => x.PermissionModule) + .Include(x => x.PermissionSystemModuleOperation) + .ThenInclude(x => x.PermissionOperation) + .Where(x => !x.IsDeleted); + } + + private PermissionOperation CreatePermissionOperationData(string name) + { + PermissionOperation permission = new() + { + CreationTime = DateTime.UtcNow, + Name = name, + IsDeleted = false, + Guid = Guid.NewGuid().ToString() + }; + + return permission; + } + + private PermissionSystem CreatePermissionSystemData(string name, bool enabled) + { + PermissionSystem permission = new() + { + CreationTime = DateTime.UtcNow, + Name = name, + Enabled = enabled, + IsDeleted = false, + Guid = Guid.NewGuid().ToString() + }; + + return permission; + } + + private PermissionModule CreatePermissionModuleData(string name, bool enabled) + { + PermissionModule permission = new() + { + CreationTime = DateTime.UtcNow, + Name = name, + Enabled = enabled, + IsDeleted = false, + Guid = Guid.NewGuid().ToString() + }; + + return permission; + } + + private PermissionSystemModule CreatePermissionSystemModuleData( + PermissionSystem permissionSystem, + PermissionModule permissionModule, + bool enabled + ) + { + PermissionSystemModule permission = new() + { + CreationTime = DateTime.UtcNow, + PermissionSystemId = permissionSystem.Id, + PermissionSystem = permissionSystem, + PermissionModuleId = permissionModule.Id, + PermissionModule = permissionModule, + Enabled = enabled, + IsDeleted = false, + Guid = Guid.NewGuid().ToString() + }; + + return permission; + } + + private PermissionSystemModuleOperation CreatePermissionSystemModuleOperationData( + PermissionSystemModule permissionSystemModule, + PermissionOperation permissionOperation, + bool enabled + ) + { + PermissionSystemModuleOperation permission = new() + { + CreationTime = DateTime.UtcNow, + PermissionOperationId = permissionOperation.Id, + PermissionOperation = permissionOperation, + PermissionSystemModuleId = permissionSystemModule.Id, + PermissionSystemModule = permissionSystemModule, + Enabled = enabled, + IsDeleted = false, + Guid = Guid.NewGuid().ToString() + }; + + return permission; + } + + private RolePermissionSystemModuleOperation CreateRolePermissionSystemModuleOperationData( + Role role, + PermissionSystemModuleOperation permissionModuleOperation, + bool active + ) + { + RolePermissionSystemModuleOperation permission = new() + { + CreationTime = DateTime.UtcNow, + PermissionSystemModuleOperationId = permissionModuleOperation.Id, + PermissionSystemModuleOperation = permissionModuleOperation, + RoleId = role.Id, + Role = role, + Active = active, + IsDeleted = false, + Guid = Guid.NewGuid().ToString() + }; + + return permission; + } + +#region "PermissionSystem" + + public async Task GetPermissionSystemByGuidAsync(string guid) + { + return await this.GetPermissionSystemsQueryable().Where(x => x.Guid == guid).FirstOrDefaultAsync(); + } + + public async Task GetPermissionSystemByNameAsync(string name) + { + return await this.GetPermissionSystemsQueryable().Where(x => x.Name == name).FirstOrDefaultAsync(); + } + + public async Task CreatePermissionSystemAsync(string name, bool enabled) + { + PermissionSystem? permission; + + using var transaction = await _sqlServerContext.Database.BeginTransactionAsync(); + + try + { + var tempPermission = CreatePermissionSystemData(name, enabled); + await _sqlServerContext.PermissionSystems.AddAsync(tempPermission); + await _sqlServerContext.SaveChangesAsync(); + await transaction.CommitAsync(); + permission = tempPermission; + } + catch (Exception exception) + { + await transaction.RollbackAsync(); + Logger.Error(exception, $"[PermissionService][CreatePermissionSystemAsync]"); + throw new CreateException($"An error occurred while creating the permission for transaction ID {transaction.TransactionId}.", exception); + } + return permission; + } + + public async Task HandleEnabledPermissionSystem(PermissionSystem permission, bool enabled) + { + bool? updated = false; + + using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) + { + permission.Enabled = enabled; + permission.UpdateTime = DateTime.UtcNow; + _sqlServerContext.Update(permission); + await _sqlServerContext.SaveChangesAsync(); + await (await transaction).CommitAsync(); + updated = true; + } + + return updated; + } + + public async Task DeletePermissionSystemAsync(PermissionSystem permission) + { + bool? deleted = false; + + using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) + { + permission.IsDeleted = true; + permission.DeletionTime = DateTime.UtcNow; + _sqlServerContext.Update(permission); + await _sqlServerContext.SaveChangesAsync(); + await (await transaction).CommitAsync(); + deleted = true; + } + + return deleted; + } + +#endregion + + +#region "PermissionModule" + + + public async Task GetPermissionModuleByGuidAsync(string guid) + { + return await this.GetPermissionModulesQueryable().Where(x => x.Guid == guid).FirstOrDefaultAsync(); + } + + public async Task GetPermissionModuleByNameAsync(string name) + { + return await this.GetPermissionModulesQueryable().Where(x => x.Name == name).FirstOrDefaultAsync(); + } + + public async Task CreatePermissionModuleAsync(string name, bool enabled) + { + PermissionModule? permission; + + using var transaction = await _sqlServerContext.Database.BeginTransactionAsync(); + + try + { + var tempPermission = CreatePermissionModuleData(name, enabled); + await _sqlServerContext.PermissionModules.AddAsync(tempPermission); + await _sqlServerContext.SaveChangesAsync(); + await transaction.CommitAsync(); + permission = tempPermission; + } + catch (Exception exception) + { + await transaction.RollbackAsync(); + Logger.Error(exception, $"[PermissionService][CreatePermissionModuleAsync]"); + throw new CreateException($"An error occurred while creating the permission for transaction ID {transaction.TransactionId}.", exception); + } + return permission; + } + + public async Task HandleEnabledPermissionModuleAsync(PermissionModule permission, bool enabled) + { + bool? updated = false; + + using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) + { + permission.Enabled = enabled; + permission.UpdateTime = DateTime.UtcNow; + _sqlServerContext.Update(permission); + await _sqlServerContext.SaveChangesAsync(); + await (await transaction).CommitAsync(); + updated = true; + } + + return updated; + } + + public async Task DeletePermissionModuleAsync(PermissionModule permission) + { + bool? deleted = false; + + using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) + { + permission.IsDeleted = true; + permission.DeletionTime = DateTime.UtcNow; + _sqlServerContext.Update(permission); + await _sqlServerContext.SaveChangesAsync(); + await (await transaction).CommitAsync(); + deleted = true; + } + + return deleted; + } + +#endregion + + +#region "PermissionOperation" + + public async Task GetPermissionOperationByGuidAsync(string guid) + { + return await this.GetPermissionOperationsQueryable().Where(x => x.Guid == guid).FirstOrDefaultAsync(); + } + + public async Task GetPermissionOperationByNameAsync(string name) + { + return await this.GetPermissionOperationsQueryable().Where(x => x.Name == name).FirstOrDefaultAsync(); + } + + public async Task CreatePermissionOperationAsync(string name) + { + PermissionOperation? permission; + + using var transaction = await _sqlServerContext.Database.BeginTransactionAsync(); + + try + { + var tempPermission = CreatePermissionOperationData(name); + await _sqlServerContext.PermissionOperations.AddAsync(tempPermission); + await _sqlServerContext.SaveChangesAsync(); + await transaction.CommitAsync(); + permission = tempPermission; + } + catch (Exception exception) + { + await transaction.RollbackAsync(); + Logger.Error(exception, $"[PermissionService][CreatePermissionOperationAsync]"); + throw new CreateException($"An error occurred while creating the permission for transaction ID {transaction.TransactionId}.", exception); + } + return permission; + } + + public async Task DeletePermissionOperationAsync(PermissionOperation permission) + { + bool? deleted = false; + + using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) + { + permission.IsDeleted = true; + permission.DeletionTime = DateTime.UtcNow; + _sqlServerContext.Update(permission); + await _sqlServerContext.SaveChangesAsync(); + await (await transaction).CommitAsync(); + deleted = true; + } + + return deleted; + } + +#endregion + + +#region "PermissionSystemModule" + + public async Task GetPermissionSystemModuleByGuidAsync(string guid) + { + return await this.GetPermissionSystemModulesQueryable().Where(x => x.Guid == guid).FirstOrDefaultAsync(); + } + + public async Task CreatePermissionSystemModuleAsync( + PermissionSystem permissionSystem, + PermissionModule permissionModule, + bool enabled + ) + { + PermissionSystemModule? permission; + + using var transaction = await _sqlServerContext.Database.BeginTransactionAsync(); + + try + { + var tempPermission = CreatePermissionSystemModuleData(permissionSystem, permissionModule, enabled); + await _sqlServerContext.PermissionSystemModules.AddAsync(tempPermission); + await _sqlServerContext.SaveChangesAsync(); + await transaction.CommitAsync(); + permission = tempPermission; + } + catch (Exception exception) + { + await transaction.RollbackAsync(); + Logger.Error(exception, $"[PermissionService][CreatePermissionSystemModuleAsync]"); + throw new CreateException($"An error occurred while creating the permission for transaction ID {transaction.TransactionId}.", exception); + } + return permission; + } + + public async Task HandleEnabledPermissionSystemModuleAsync(PermissionSystemModule permission, bool enabled) + { + bool? updated = false; + + using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) + { + permission.Enabled = enabled; + permission.UpdateTime = DateTime.UtcNow; + _sqlServerContext.Update(permission); + await _sqlServerContext.SaveChangesAsync(); + await (await transaction).CommitAsync(); + updated = true; + } + + return updated; + } + + public async Task DeletePermissionSystemModuleAsync(PermissionSystemModule permission) + { + bool? deleted = false; + + using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) + { + permission.IsDeleted = true; + permission.DeletionTime = DateTime.UtcNow; + _sqlServerContext.Update(permission); + await _sqlServerContext.SaveChangesAsync(); + await (await transaction).CommitAsync(); + deleted = true; + } + + return deleted; + } + +#endregion + + +#region "PermissionSystemModuleOperation" + + public async Task GetPermissionSystemModuleOperationByGuidAsync(string guid) + { + return await this.GetPermissionSystemModuleOperationsQueryable().Where(x => x.Guid == guid).FirstOrDefaultAsync(); + } + + public async Task CreatePermissionSystemModuleOperationAsync( + PermissionSystemModule permissionSystemModule, + PermissionOperation permissionOperation, + bool enabled + ) + { + PermissionSystemModuleOperation? permission; + + using var transaction = await _sqlServerContext.Database.BeginTransactionAsync(); + + try + { + var tempPermission = CreatePermissionSystemModuleOperationData(permissionSystemModule, permissionOperation, enabled); + await _sqlServerContext.PermissionSystemModuleOperations.AddAsync(tempPermission); + await _sqlServerContext.SaveChangesAsync(); + await transaction.CommitAsync(); + permission = tempPermission; + } + catch (Exception exception) + { + await transaction.RollbackAsync(); + Logger.Error(exception, $"[PermissionService][CreatePermissionSystemModuleOperationAsync]"); + throw new CreateException($"An error occurred while creating the permission for transaction ID {transaction.TransactionId}.", exception); + } + return permission; + } + + public async Task HandleEnabledPermissionSystemModuleOperationAsync(PermissionSystemModuleOperation permission, bool enabled) + { + bool? updated = false; + + using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) + { + permission.Enabled = enabled; + permission.UpdateTime = DateTime.UtcNow; + _sqlServerContext.Update(permission); + await _sqlServerContext.SaveChangesAsync(); + await (await transaction).CommitAsync(); + updated = true; + } + + return updated; + } + + public async Task DeletePermissionSystemModuleOperationAsync(PermissionSystemModuleOperation permission) + { + bool? deleted = false; + + using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) + { + permission.IsDeleted = true; + permission.DeletionTime = DateTime.UtcNow; + _sqlServerContext.Update(permission); + await _sqlServerContext.SaveChangesAsync(); + await (await transaction).CommitAsync(); + deleted = true; + } + + return deleted; + } + +#endregion + + +#region "RolePermissionSystemModuleOperation" + + public async Task GetRolePermissionSystemModuleOperationByGuidAsync(string guid) + { + return await this.GetRolePermissionSystemModuleOperationsQueryable().Where(x => x.Guid == guid).FirstOrDefaultAsync(); + } + + public async Task CreateRolePermissionSystemModuleOperationAsync( + Role role, + PermissionSystemModuleOperation permissionSystemModuleOperation, + bool enabled + ) + { + RolePermissionSystemModuleOperation? permission; + + using var transaction = await _sqlServerContext.Database.BeginTransactionAsync(); + + try + { + var tempPermission = CreateRolePermissionSystemModuleOperationData(role, permissionSystemModuleOperation, enabled); + await _sqlServerContext.RolePermissionSystemModuleOperations.AddAsync(tempPermission); + await _sqlServerContext.SaveChangesAsync(); + await transaction.CommitAsync(); + permission = tempPermission; + } + catch (Exception exception) + { + await transaction.RollbackAsync(); + Logger.Error(exception, $"[PermissionService][RolePermissionSystemModuleOperation]"); + throw new CreateException($"An error occurred while creating the permission for transaction ID {transaction.TransactionId}.", exception); + } + return permission; + } + + public async Task HandleEnabledRolePermissionSystemModuleOperationAsync(RolePermissionSystemModuleOperation permission, bool active) + { + bool? updated = false; + + using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) + { + permission.Active = active; + permission.UpdateTime = DateTime.UtcNow; + _sqlServerContext.Update(permission); + await _sqlServerContext.SaveChangesAsync(); + await (await transaction).CommitAsync(); + updated = true; + } + + return updated; + } + + public async Task DeleteRolePermissionSystemModuleOperationAsync(RolePermissionSystemModuleOperation permission) + { + bool? deleted = false; + + using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) + { + permission.IsDeleted = true; + permission.DeletionTime = DateTime.UtcNow; + _sqlServerContext.Update(permission); + await _sqlServerContext.SaveChangesAsync(); + await (await transaction).CommitAsync(); + deleted = true; + } + + return deleted; + } + +#endregion + +} + -- 2.49.1 From a5c3c5cbd083ac038727b5ced362ea215d0c428b Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sun, 27 Apr 2025 18:24:44 +0200 Subject: [PATCH 09/28] Adding tests for PermissionService --- .../Services/PermissionService_Tests.cs | 377 ++++++++++++++++++ MainProject.Tests/TestsUtils/TestUtils.cs | 18 + MainProject/Services/PermissionService.cs | 12 +- 3 files changed, 401 insertions(+), 6 deletions(-) create mode 100644 MainProject.Tests/Services/PermissionService_Tests.cs diff --git a/MainProject.Tests/Services/PermissionService_Tests.cs b/MainProject.Tests/Services/PermissionService_Tests.cs new file mode 100644 index 0000000..70885bb --- /dev/null +++ b/MainProject.Tests/Services/PermissionService_Tests.cs @@ -0,0 +1,377 @@ +using BasicDotnetTemplate.MainProject.Services; +using BasicDotnetTemplate.MainProject.Models.Api.Data.User; +using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; +using Newtonsoft.Json; + + + +namespace BasicDotnetTemplate.MainProject.Tests; + +[TestClass] +public class PermissionService_Tests +{ + private static PermissionService _permissionService = TestUtils.CreatePermissionService(); + private static string _name = "TEST"; + private static PermissionSystem _permissionSystem = new PermissionSystem() + { + Name = _name, + Enabled = false + }; + + [TestMethod] + public void Inizialize() + { + try + { + var permissionService = TestUtils.CreatePermissionService(); + if (permissionService != null) + { + Assert.IsInstanceOfType(permissionService, typeof(PermissionService)); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex.Message}"); + } + } + +#region "PermissionSystem" + + [TestMethod] + public async Task GetPermissionSystemByGuidAsync_Null() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionSystemByGuidAsync(Guid.NewGuid().ToString()); + Assert.IsTrue(permission == null); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task GetPermissionSystemByNameAsync_Null() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionSystemByNameAsync(Guid.NewGuid().ToString()); + Assert.IsTrue(permission == null); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task CreatePermissionSystemAsync_Success() + { + try + { + var permission = await _permissionService.CreatePermissionSystemAsync(_name, true); + Assert.IsInstanceOfType(permission, typeof(PermissionSystem)); + Assert.IsNotNull(permission); + Assert.IsTrue(permission.Name == _name); + Assert.IsTrue(permission.Enabled); + _permissionSystem = permission; + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task CreatePermissionSystemAsync_Exception() + { + try + { + var exceptionPermissionService = TestUtils.CreatePermissionServiceException(); + + if (exceptionPermissionService != null) + { + try + { + var user = await exceptionPermissionService.CreatePermissionSystemAsync(_name, true); + Assert.Fail($"Expected exception instead of response: {user?.Guid}"); + } + catch (Exception exception) + { + Assert.IsInstanceOfType(exception, typeof(Exception)); + } + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task HandleEnabledPermissionSystem() + { + try + { + var updated = await _permissionService.HandleEnabledPermissionSystem(_permissionSystem, false); + Assert.IsTrue(updated); + Assert.IsTrue(!_permissionSystem.Enabled); + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task GetPermissionSystemByGuidAsync_Success() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionSystemByGuidAsync(_permissionSystem.Guid); + Assert.IsNotNull(permission); + Assert.IsInstanceOfType(permission, typeof(PermissionSystem)); + Assert.IsTrue(permission.Name == _permissionSystem.Name); + Assert.IsTrue(permission.Enabled == _permissionSystem.Enabled); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task GetPermissionSystemByNameAsync_Success() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionSystemByNameAsync(_permissionSystem.Name); + Assert.IsNotNull(permission); + Assert.IsInstanceOfType(permission, typeof(PermissionSystem)); + Assert.IsTrue(permission.Guid == _permissionSystem.Guid); + Assert.IsTrue(permission.Enabled == _permissionSystem.Enabled); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + +#endregion + // [TestMethod] + // public async Task GetUserByUsernameAndPassword_Null() + // { + // try + // { + // var testString = "test"; + // if (_userService != null) + // { + // var user = await _userService.GetUserByUsernameAndPassword(testString, testString); + // Assert.IsTrue(user == null); + // } + // else + // { + // Assert.Fail($"PermissionService is null"); + // } + // } + // catch (Exception ex) + // { + // Console.WriteLine(ex.InnerException); + // Assert.Fail($"An exception was thrown: {ex}"); + // } + // } + + // [TestMethod] + // public async Task CheckIfEmailIsValid_EmailNotExists() + // { + // try + // { + // if (_userService != null) + // { + // var valid = await _userService.CheckIfEmailIsValid(_user.Email ?? String.Empty); + // Assert.IsTrue(valid); + // } + // else + // { + // Assert.Fail($"PermissionService is null"); + // } + // } + // catch (Exception ex) + // { + // Console.WriteLine(ex.InnerException); + // Assert.Fail($"An exception was thrown: {ex}"); + // } + // } + + + + // [TestMethod] + // public async Task CheckIfEmailIsValid_EmailCurrentUser() + // { + // try + // { + + // if (_userService != null) + // { + // var valid = await _userService.CheckIfEmailIsValid(_user.Email ?? String.Empty, _user.Guid ?? String.Empty); + // Assert.IsTrue(valid); + // } + // else + // { + // Assert.Fail($"PermissionService is null"); + // } + // } + // catch (Exception ex) + // { + // Console.WriteLine(ex.InnerException); + // Assert.Fail($"An exception was thrown: {ex}"); + // } + // } + + // [TestMethod] + // public async Task CheckIfEmailIsValid_EmailAlreadyExists() + // { + // try + // { + + // if (_userService != null) + // { + // var valid = await _userService.CheckIfEmailIsValid(_user.Email ?? String.Empty); + // Assert.IsFalse(valid); + // } + // else + // { + // Assert.Fail($"PermissionService is null"); + // } + // } + // catch (Exception ex) + // { + // Console.WriteLine(ex.InnerException); + // Assert.Fail($"An exception was thrown: {ex}"); + // } + // } + + + + // [TestMethod] + // public async Task GetUserByGuidAsync() + // { + // try + // { + + // if (_userService != null) + // { + // var user = await _userService.GetUserByGuidAsync(_user.Guid ?? String.Empty); + // Assert.IsNotNull(user); + // Assert.IsTrue(user.Guid == _user?.Guid); + // } + // else + // { + // Assert.Fail($"PermissionService is null"); + // } + // } + // catch (Exception ex) + // { + // Console.WriteLine(ex.InnerException); + // Assert.Fail($"An exception was thrown: {ex}"); + // } + // } + + // [TestMethod] + // public async Task DeleteUser() + // { + // try + // { + + // if (_userService != null) + // { + // var user = await _userService.GetUserByGuidAsync(_user.Guid ?? String.Empty); + // Assert.IsNotNull(user); + // var deleted = await _userService.DeleteUserAsync(user); + // Assert.IsTrue(deleted); + // } + // else + // { + // Assert.Fail($"PermissionService is null"); + // } + // } + // catch (Exception ex) + // { + // Console.WriteLine(ex.InnerException); + // Assert.Fail($"An exception was thrown: {ex}"); + // } + // } + + +#region "DeletePermissions" + [TestMethod] + public async Task DeletePermissionSystemAsync() + { + try + { + var deleted = await _permissionService.DeletePermissionSystemAsync(_permissionSystem); + Assert.IsTrue(deleted); + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } +#endregion + +} + + + diff --git a/MainProject.Tests/TestsUtils/TestUtils.cs b/MainProject.Tests/TestsUtils/TestUtils.cs index aa21c64..e6f1bb8 100644 --- a/MainProject.Tests/TestsUtils/TestUtils.cs +++ b/MainProject.Tests/TestsUtils/TestUtils.cs @@ -145,6 +145,24 @@ public static class TestUtils var httpContextAccessor = new Mock(); return new RoleService(httpContextAccessor.Object, configuration, sqlServerContext); } + + public static PermissionService CreatePermissionService() + { + IConfiguration configuration = CreateConfiguration(); + SqlServerContext sqlServerContext = CreateInMemorySqlContext(); + var httpContextAccessor = new Mock(); + return new PermissionService(httpContextAccessor.Object, configuration, sqlServerContext); + } + + public static PermissionService CreatePermissionServiceException() + { + IConfiguration configuration = CreateConfiguration(); + var optionsBuilder = new DbContextOptionsBuilder(); + optionsBuilder.UseSqlServer(GetFakeConnectionString()); + SqlServerContext sqlServerContext = new SqlServerContext(optionsBuilder.Options); + var httpContextAccessor = new Mock(); + return new PermissionService(httpContextAccessor.Object, configuration, sqlServerContext); + } } diff --git a/MainProject/Services/PermissionService.cs b/MainProject/Services/PermissionService.cs index ee7449a..5af03be 100644 --- a/MainProject/Services/PermissionService.cs +++ b/MainProject/Services/PermissionService.cs @@ -117,7 +117,7 @@ public class PermissionService : BaseService, IPermissionService .Where(x => !x.IsDeleted); } - private PermissionOperation CreatePermissionOperationData(string name) + private static PermissionOperation CreatePermissionOperationData(string name) { PermissionOperation permission = new() { @@ -130,7 +130,7 @@ public class PermissionService : BaseService, IPermissionService return permission; } - private PermissionSystem CreatePermissionSystemData(string name, bool enabled) + private static PermissionSystem CreatePermissionSystemData(string name, bool enabled) { PermissionSystem permission = new() { @@ -144,7 +144,7 @@ public class PermissionService : BaseService, IPermissionService return permission; } - private PermissionModule CreatePermissionModuleData(string name, bool enabled) + private static PermissionModule CreatePermissionModuleData(string name, bool enabled) { PermissionModule permission = new() { @@ -158,7 +158,7 @@ public class PermissionService : BaseService, IPermissionService return permission; } - private PermissionSystemModule CreatePermissionSystemModuleData( + private static PermissionSystemModule CreatePermissionSystemModuleData( PermissionSystem permissionSystem, PermissionModule permissionModule, bool enabled @@ -179,7 +179,7 @@ public class PermissionService : BaseService, IPermissionService return permission; } - private PermissionSystemModuleOperation CreatePermissionSystemModuleOperationData( + private static PermissionSystemModuleOperation CreatePermissionSystemModuleOperationData( PermissionSystemModule permissionSystemModule, PermissionOperation permissionOperation, bool enabled @@ -200,7 +200,7 @@ public class PermissionService : BaseService, IPermissionService return permission; } - private RolePermissionSystemModuleOperation CreateRolePermissionSystemModuleOperationData( + private static RolePermissionSystemModuleOperation CreateRolePermissionSystemModuleOperationData( Role role, PermissionSystemModuleOperation permissionModuleOperation, bool active -- 2.49.1 From c5fa25ceeb553c0c958775e101b943efa8ba71d4 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sun, 27 Apr 2025 18:37:09 +0200 Subject: [PATCH 10/28] Adding PermissionModule tests --- .../Services/PermissionService_Tests.cs | 343 ++++++++++-------- MainProject/Services/PermissionService.cs | 4 +- 2 files changed, 201 insertions(+), 146 deletions(-) diff --git a/MainProject.Tests/Services/PermissionService_Tests.cs b/MainProject.Tests/Services/PermissionService_Tests.cs index 70885bb..160817e 100644 --- a/MainProject.Tests/Services/PermissionService_Tests.cs +++ b/MainProject.Tests/Services/PermissionService_Tests.cs @@ -14,7 +14,13 @@ public class PermissionService_Tests private static string _name = "TEST"; private static PermissionSystem _permissionSystem = new PermissionSystem() { - Name = _name, + Name = _name + "-SYSTEM", + Enabled = false + }; + + private static PermissionModule _permissionModule = new PermissionModule() + { + Name = _name + "-MODULE", Enabled = false }; @@ -93,10 +99,10 @@ public class PermissionService_Tests { try { - var permission = await _permissionService.CreatePermissionSystemAsync(_name, true); + var permission = await _permissionService.CreatePermissionSystemAsync(_permissionSystem.Name, true); Assert.IsInstanceOfType(permission, typeof(PermissionSystem)); Assert.IsNotNull(permission); - Assert.IsTrue(permission.Name == _name); + Assert.IsTrue(permission.Name == _permissionSystem.Name); Assert.IsTrue(permission.Enabled); _permissionSystem = permission; @@ -119,7 +125,7 @@ public class PermissionService_Tests { try { - var user = await exceptionPermissionService.CreatePermissionSystemAsync(_name, true); + var user = await exceptionPermissionService.CreatePermissionSystemAsync(_permissionSystem.Name, true); Assert.Fail($"Expected exception instead of response: {user?.Guid}"); } catch (Exception exception) @@ -139,11 +145,11 @@ public class PermissionService_Tests } [TestMethod] - public async Task HandleEnabledPermissionSystem() + public async Task HandleEnabledPermissionSystemAsync() { try { - var updated = await _permissionService.HandleEnabledPermissionSystem(_permissionSystem, false); + var updated = await _permissionService.HandleEnabledPermissionSystemAsync(_permissionSystem, false); Assert.IsTrue(updated); Assert.IsTrue(!_permissionSystem.Enabled); @@ -208,152 +214,184 @@ public class PermissionService_Tests } #endregion - // [TestMethod] - // public async Task GetUserByUsernameAndPassword_Null() - // { - // try - // { - // var testString = "test"; - // if (_userService != null) - // { - // var user = await _userService.GetUserByUsernameAndPassword(testString, testString); - // Assert.IsTrue(user == null); - // } - // else - // { - // Assert.Fail($"PermissionService is null"); - // } - // } - // catch (Exception ex) - // { - // Console.WriteLine(ex.InnerException); - // Assert.Fail($"An exception was thrown: {ex}"); - // } - // } + - // [TestMethod] - // public async Task CheckIfEmailIsValid_EmailNotExists() - // { - // try - // { - // if (_userService != null) - // { - // var valid = await _userService.CheckIfEmailIsValid(_user.Email ?? String.Empty); - // Assert.IsTrue(valid); - // } - // else - // { - // Assert.Fail($"PermissionService is null"); - // } - // } - // catch (Exception ex) - // { - // Console.WriteLine(ex.InnerException); - // Assert.Fail($"An exception was thrown: {ex}"); - // } - // } +#region "PermissionModule" + + [TestMethod] + public async Task GetPermissionModuleByGuidAsync_Null() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionModuleByGuidAsync(Guid.NewGuid().ToString()); + Assert.IsTrue(permission == null); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task GetPermissionModuleByNameAsync_Null() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionModuleByNameAsync(Guid.NewGuid().ToString()); + Assert.IsTrue(permission == null); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task CreatePermissionModuleAsync_Success() + { + try + { + var permission = await _permissionService.CreatePermissionModuleAsync(_permissionModule.Name, true); + Assert.IsInstanceOfType(permission, typeof(PermissionModule)); + Assert.IsNotNull(permission); + Assert.IsTrue(permission.Name == _permissionModule.Name); + Assert.IsTrue(permission.Enabled); + _permissionModule = permission; + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task CreatePermissionModuleAsync_Exception() + { + try + { + var exceptionPermissionService = TestUtils.CreatePermissionServiceException(); + + if (exceptionPermissionService != null) + { + try + { + var user = await exceptionPermissionService.CreatePermissionModuleAsync(_permissionModule.Name, true); + Assert.Fail($"Expected exception instead of response: {user?.Guid}"); + } + catch (Exception exception) + { + Assert.IsInstanceOfType(exception, typeof(Exception)); + } + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task HandleEnabledPermissionModuleAsync() + { + try + { + var updated = await _permissionService.HandleEnabledPermissionModuleAsync(_permissionModule, false); + Assert.IsTrue(updated); + Assert.IsTrue(!_permissionModule.Enabled); + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task GetPermissionModuleByGuidAsync_Success() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionModuleByGuidAsync(_permissionModule.Guid); + Assert.IsNotNull(permission); + Assert.IsInstanceOfType(permission, typeof(PermissionModule)); + Assert.IsTrue(permission.Name == _permissionModule.Name); + Assert.IsTrue(permission.Enabled == _permissionModule.Enabled); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task GetPermissionModuleByNameAsync_Success() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionModuleByNameAsync(_permissionModule.Name); + Assert.IsNotNull(permission); + Assert.IsInstanceOfType(permission, typeof(PermissionModule)); + Assert.IsTrue(permission.Guid == _permissionModule.Guid); + Assert.IsTrue(permission.Enabled == _permissionModule.Enabled); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + +#endregion - // [TestMethod] - // public async Task CheckIfEmailIsValid_EmailCurrentUser() - // { - // try - // { - // if (_userService != null) - // { - // var valid = await _userService.CheckIfEmailIsValid(_user.Email ?? String.Empty, _user.Guid ?? String.Empty); - // Assert.IsTrue(valid); - // } - // else - // { - // Assert.Fail($"PermissionService is null"); - // } - // } - // catch (Exception ex) - // { - // Console.WriteLine(ex.InnerException); - // Assert.Fail($"An exception was thrown: {ex}"); - // } - // } - - // [TestMethod] - // public async Task CheckIfEmailIsValid_EmailAlreadyExists() - // { - // try - // { - - // if (_userService != null) - // { - // var valid = await _userService.CheckIfEmailIsValid(_user.Email ?? String.Empty); - // Assert.IsFalse(valid); - // } - // else - // { - // Assert.Fail($"PermissionService is null"); - // } - // } - // catch (Exception ex) - // { - // Console.WriteLine(ex.InnerException); - // Assert.Fail($"An exception was thrown: {ex}"); - // } - // } - - - - // [TestMethod] - // public async Task GetUserByGuidAsync() - // { - // try - // { - - // if (_userService != null) - // { - // var user = await _userService.GetUserByGuidAsync(_user.Guid ?? String.Empty); - // Assert.IsNotNull(user); - // Assert.IsTrue(user.Guid == _user?.Guid); - // } - // else - // { - // Assert.Fail($"PermissionService is null"); - // } - // } - // catch (Exception ex) - // { - // Console.WriteLine(ex.InnerException); - // Assert.Fail($"An exception was thrown: {ex}"); - // } - // } - - // [TestMethod] - // public async Task DeleteUser() - // { - // try - // { - - // if (_userService != null) - // { - // var user = await _userService.GetUserByGuidAsync(_user.Guid ?? String.Empty); - // Assert.IsNotNull(user); - // var deleted = await _userService.DeleteUserAsync(user); - // Assert.IsTrue(deleted); - // } - // else - // { - // Assert.Fail($"PermissionService is null"); - // } - // } - // catch (Exception ex) - // { - // Console.WriteLine(ex.InnerException); - // Assert.Fail($"An exception was thrown: {ex}"); - // } - // } #region "DeletePermissions" + [TestMethod] public async Task DeletePermissionSystemAsync() { @@ -369,6 +407,23 @@ public class PermissionService_Tests Assert.Fail($"An exception was thrown: {ex}"); } } + + [TestMethod] + public async Task DeletePermissionModuleAsync() + { + try + { + var deleted = await _permissionService.DeletePermissionModuleAsync(_permissionModule); + Assert.IsTrue(deleted); + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + #endregion } diff --git a/MainProject/Services/PermissionService.cs b/MainProject/Services/PermissionService.cs index 5af03be..170e8ad 100644 --- a/MainProject/Services/PermissionService.cs +++ b/MainProject/Services/PermissionService.cs @@ -11,7 +11,7 @@ public interface IPermissionService { Task GetPermissionSystemByGuidAsync(string guid); Task GetPermissionSystemByNameAsync(string name); - Task HandleEnabledPermissionSystem(PermissionSystem permission, bool enabled); + Task HandleEnabledPermissionSystemAsync(PermissionSystem permission, bool enabled); Task CreatePermissionSystemAsync(string name, bool enabled); Task DeletePermissionSystemAsync(PermissionSystem permission); @@ -256,7 +256,7 @@ public class PermissionService : BaseService, IPermissionService return permission; } - public async Task HandleEnabledPermissionSystem(PermissionSystem permission, bool enabled) + public async Task HandleEnabledPermissionSystemAsync(PermissionSystem permission, bool enabled) { bool? updated = false; -- 2.49.1 From 74a5ae5548aa123422c62bebd962d8df6c91506b Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sun, 27 Apr 2025 19:54:55 +0200 Subject: [PATCH 11/28] Adding PermissionOperation tests + minor fixes --- .../Services/PermissionService_Tests.cs | 183 +++++++++++++++++- .../Services/RoleService_Tests.cs | 1 + .../Services/UserService_Tests.cs | 2 + .../TestsUtils/ExceptionSqlServerContext.cs | 24 +++ MainProject.Tests/TestsUtils/TestUtils.cs | 24 +-- MainProject/Services/UserService.cs | 1 - 6 files changed, 218 insertions(+), 17 deletions(-) create mode 100644 MainProject.Tests/TestsUtils/ExceptionSqlServerContext.cs diff --git a/MainProject.Tests/Services/PermissionService_Tests.cs b/MainProject.Tests/Services/PermissionService_Tests.cs index 160817e..088629c 100644 --- a/MainProject.Tests/Services/PermissionService_Tests.cs +++ b/MainProject.Tests/Services/PermissionService_Tests.cs @@ -2,7 +2,7 @@ using BasicDotnetTemplate.MainProject.Services; using BasicDotnetTemplate.MainProject.Models.Api.Data.User; using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; using Newtonsoft.Json; - +using BasicDotnetTemplate.MainProject.Models.Api.Common.Exceptions; namespace BasicDotnetTemplate.MainProject.Tests; @@ -24,6 +24,11 @@ public class PermissionService_Tests Enabled = false }; + private static PermissionOperation _permissionOperation = new PermissionOperation() + { + Name = _name + "-OPERATION" + }; + [TestMethod] public void Inizialize() { @@ -125,12 +130,13 @@ public class PermissionService_Tests { try { - var user = await exceptionPermissionService.CreatePermissionSystemAsync(_permissionSystem.Name, true); - Assert.Fail($"Expected exception instead of response: {user?.Guid}"); + var permission = await exceptionPermissionService.CreatePermissionSystemAsync(_permissionSystem.Name, true); + Assert.Fail($"Expected exception instead of response: {permission?.Guid}"); } catch (Exception exception) { Assert.IsInstanceOfType(exception, typeof(Exception)); + Assert.IsInstanceOfType(exception, typeof(CreateException)); } } else @@ -289,18 +295,21 @@ public class PermissionService_Tests { try { + var exceptionPermissionService = TestUtils.CreatePermissionServiceException(); if (exceptionPermissionService != null) { try { - var user = await exceptionPermissionService.CreatePermissionModuleAsync(_permissionModule.Name, true); - Assert.Fail($"Expected exception instead of response: {user?.Guid}"); + var permission = await exceptionPermissionService.CreatePermissionModuleAsync(_permissionModule.Name, true); + Assert.Fail($"Expected exception instead of response: {permission?.Guid}"); } catch (Exception exception) { + Console.WriteLine(exception); Assert.IsInstanceOfType(exception, typeof(Exception)); + Assert.IsInstanceOfType(exception, typeof(CreateException)); } } else @@ -386,7 +395,155 @@ public class PermissionService_Tests #endregion +#region "PermissionOperation" + [TestMethod] + public async Task GetPermissionOperationByGuidAsync_Null() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionOperationByGuidAsync(Guid.NewGuid().ToString()); + Assert.IsTrue(permission == null); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task GetPermissionOperationByNameAsync_Null() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionOperationByNameAsync(Guid.NewGuid().ToString()); + Assert.IsTrue(permission == null); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task CreatePermissionOperationAsync_Success() + { + try + { + var permission = await _permissionService.CreatePermissionOperationAsync(_permissionOperation.Name); + Assert.IsInstanceOfType(permission, typeof(PermissionOperation)); + Assert.IsNotNull(permission); + Assert.IsTrue(permission.Name == _permissionOperation.Name); + _permissionOperation = permission; + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task CreatePermissionOperationAsync_Exception() + { + try + { + var exceptionPermissionService = TestUtils.CreatePermissionServiceException(); + + if (exceptionPermissionService != null) + { + try + { + var permission = await exceptionPermissionService.CreatePermissionOperationAsync(_permissionOperation.Name); + Assert.Fail($"Expected exception instead of response: {permission?.Guid}"); + } + catch (Exception exception) + { + Assert.IsInstanceOfType(exception, typeof(Exception)); + Assert.IsInstanceOfType(exception, typeof(CreateException)); + } + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task GetPermissionOperationByGuidAsync_Success() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionOperationByGuidAsync(_permissionOperation.Guid); + Assert.IsNotNull(permission); + Assert.IsInstanceOfType(permission, typeof(PermissionOperation)); + Assert.IsTrue(permission.Name == _permissionOperation.Name); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task GetPermissionOperationByNameAsync_Success() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionOperationByNameAsync(_permissionOperation.Name); + Assert.IsNotNull(permission); + Assert.IsInstanceOfType(permission, typeof(PermissionOperation)); + Assert.IsTrue(permission.Guid == _permissionOperation.Guid); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + +#endregion @@ -424,6 +581,22 @@ public class PermissionService_Tests } } + [TestMethod] + public async Task DeletePermissionOperationAsync() + { + try + { + var deleted = await _permissionService.DeletePermissionOperationAsync(_permissionOperation); + Assert.IsTrue(deleted); + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + #endregion } diff --git a/MainProject.Tests/Services/RoleService_Tests.cs b/MainProject.Tests/Services/RoleService_Tests.cs index 188cf34..03cf382 100644 --- a/MainProject.Tests/Services/RoleService_Tests.cs +++ b/MainProject.Tests/Services/RoleService_Tests.cs @@ -118,6 +118,7 @@ public class RoleService_Tests catch (Exception exception) { Assert.IsInstanceOfType(exception, typeof(Exception)); + Assert.IsInstanceOfType(exception, typeof(CreateException)); } } else diff --git a/MainProject.Tests/Services/UserService_Tests.cs b/MainProject.Tests/Services/UserService_Tests.cs index 74b0381..c3bc21f 100644 --- a/MainProject.Tests/Services/UserService_Tests.cs +++ b/MainProject.Tests/Services/UserService_Tests.cs @@ -2,6 +2,7 @@ using BasicDotnetTemplate.MainProject.Services; using BasicDotnetTemplate.MainProject.Models.Api.Data.User; using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; using Newtonsoft.Json; +using BasicDotnetTemplate.MainProject.Models.Api.Common.Exceptions; @@ -152,6 +153,7 @@ public class UserService_Tests catch (Exception exception) { Assert.IsInstanceOfType(exception, typeof(Exception)); + Assert.IsInstanceOfType(exception, typeof(CreateException)); } } else diff --git a/MainProject.Tests/TestsUtils/ExceptionSqlServerContext.cs b/MainProject.Tests/TestsUtils/ExceptionSqlServerContext.cs new file mode 100644 index 0000000..7587a75 --- /dev/null +++ b/MainProject.Tests/TestsUtils/ExceptionSqlServerContext.cs @@ -0,0 +1,24 @@ +using BasicDotnetTemplate.MainProject.Core.Database; +using Microsoft.EntityFrameworkCore; +using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; +using Newtonsoft.Json; + +namespace BasicDotnetTemplate.MainProject.Tests; + +public class ExceptionSqlServerContext : SqlServerContext +{ + public bool ThrowExceptionOnSave { get; set; } + + public ExceptionSqlServerContext() : base(TestUtils.CreateInMemorySqlContextOptions()) + { + } + + public override Task SaveChangesAsync(CancellationToken cancellationToken = default) + { + if (ThrowExceptionOnSave) + { + throw new Exception("Database error"); + } + return base.SaveChangesAsync(cancellationToken); + } +} \ No newline at end of file diff --git a/MainProject.Tests/TestsUtils/TestUtils.cs b/MainProject.Tests/TestsUtils/TestUtils.cs index e6f1bb8..ab74ca0 100644 --- a/MainProject.Tests/TestsUtils/TestUtils.cs +++ b/MainProject.Tests/TestsUtils/TestUtils.cs @@ -69,11 +69,16 @@ public static class TestUtils return "Server=127.0.0.1;Initial Catalog=MyFakeDatabase;User Id=MyFakeUser;Password='MyFakePassword';MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30"; } - public static SqlServerContext CreateInMemorySqlContext() + public static DbContextOptions CreateInMemorySqlContextOptions() { - var options = new DbContextOptionsBuilder() + return new DbContextOptionsBuilder() .UseSqlite("DataSource=:memory:") // Database in-memory .Options; + } + + public static SqlServerContext CreateInMemorySqlContext() + { + var options = CreateInMemorySqlContextOptions(); var context = new SqlServerContext(options); context.Database.OpenConnection(); @@ -108,10 +113,9 @@ public static class TestUtils public static UserService CreateUserServiceException() { + var sqlServerContext = new ExceptionSqlServerContext(); + sqlServerContext.ThrowExceptionOnSave = true; IConfiguration configuration = CreateConfiguration(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(GetFakeConnectionString()); - SqlServerContext sqlServerContext = new SqlServerContext(optionsBuilder.Options); var httpContextAccessor = new Mock(); return new UserService(httpContextAccessor.Object, configuration, sqlServerContext); } @@ -138,10 +142,9 @@ public static class TestUtils public static RoleService CreateRoleServiceException() { + var sqlServerContext = new ExceptionSqlServerContext(); + sqlServerContext.ThrowExceptionOnSave = true; IConfiguration configuration = CreateConfiguration(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(GetFakeConnectionString()); - SqlServerContext sqlServerContext = new SqlServerContext(optionsBuilder.Options); var httpContextAccessor = new Mock(); return new RoleService(httpContextAccessor.Object, configuration, sqlServerContext); } @@ -156,10 +159,9 @@ public static class TestUtils public static PermissionService CreatePermissionServiceException() { + var sqlServerContext = new ExceptionSqlServerContext(); + sqlServerContext.ThrowExceptionOnSave = true; IConfiguration configuration = CreateConfiguration(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(GetFakeConnectionString()); - SqlServerContext sqlServerContext = new SqlServerContext(optionsBuilder.Options); var httpContextAccessor = new Mock(); return new PermissionService(httpContextAccessor.Object, configuration, sqlServerContext); } diff --git a/MainProject/Services/UserService.cs b/MainProject/Services/UserService.cs index 11b44e4..3fe1314 100644 --- a/MainProject/Services/UserService.cs +++ b/MainProject/Services/UserService.cs @@ -78,7 +78,6 @@ public class UserService : BaseService, IUserService if (user != null) { var encryptedPassword = user.PasswordHash; - Console.WriteLine(encryptedPassword); } return user; -- 2.49.1 From dfadde441631e6d0ea035dde0bc514576c163878 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sun, 27 Apr 2025 20:11:08 +0200 Subject: [PATCH 12/28] Adding PermissionSystemModule tests --- .../Services/PermissionService_Tests.cs | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) diff --git a/MainProject.Tests/Services/PermissionService_Tests.cs b/MainProject.Tests/Services/PermissionService_Tests.cs index 088629c..ef5df74 100644 --- a/MainProject.Tests/Services/PermissionService_Tests.cs +++ b/MainProject.Tests/Services/PermissionService_Tests.cs @@ -29,6 +29,15 @@ public class PermissionService_Tests Name = _name + "-OPERATION" }; + private static PermissionSystemModule _permissionSystemModule = new PermissionSystemModule() + { + PermissionSystem = _permissionSystem, + PermissionSystemId = 0, + PermissionModule = _permissionModule, + PermissionModuleId = 0, + Enabled = false + }; + [TestMethod] public void Inizialize() { @@ -546,9 +555,145 @@ public class PermissionService_Tests #endregion +#region "PermissionSystemModule" + + [TestMethod] + public async Task GetPermissionSystemModuleByGuidAsync_Null() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionSystemModuleByGuidAsync(Guid.NewGuid().ToString()); + Assert.IsTrue(permission == null); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task CreatePermissionSystemModuleAsync_Success() + { + try + { + var permission = await _permissionService.CreatePermissionSystemModuleAsync(_permissionSystem, _permissionModule, true); + Assert.IsInstanceOfType(permission, typeof(PermissionSystemModule)); + Assert.IsNotNull(permission); + Assert.IsTrue(permission.Enabled); + _permissionSystemModule = permission; + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task CreatePermissionSystemModuleAsync_Exception() + { + try + { + var exceptionPermissionService = TestUtils.CreatePermissionServiceException(); + + if (exceptionPermissionService != null) + { + try + { + var user = await exceptionPermissionService.CreatePermissionSystemModuleAsync(_permissionSystem, _permissionModule, true); + Assert.Fail($"Expected exception instead of response: {user?.Guid}"); + } + catch (Exception exception) + { + Assert.IsInstanceOfType(exception, typeof(Exception)); + Assert.IsInstanceOfType(exception, typeof(CreateException)); + } + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task HandleEnabledPermissionSystemModuleAsync() + { + try + { + var updated = await _permissionService.HandleEnabledPermissionSystemModuleAsync(_permissionSystemModule, false); + Assert.IsTrue(updated); + Assert.IsTrue(!_permissionSystemModule.Enabled); + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task GetPermissionSystemModuleByGuidAsync_Success() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionSystemModuleByGuidAsync(_permissionSystemModule.Guid); + Assert.IsNotNull(permission); + Assert.IsInstanceOfType(permission, typeof(PermissionSystemModule)); + Assert.IsTrue(permission.Enabled == _permissionSystemModule.Enabled); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + +#endregion + + #region "DeletePermissions" + [TestMethod] + public async Task DeletePermissionSystemModuleAsync() + { + try + { + var deleted = await _permissionService.DeletePermissionSystemModuleAsync(_permissionSystemModule); + Assert.IsTrue(deleted); + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + [TestMethod] public async Task DeletePermissionSystemAsync() { -- 2.49.1 From e578102289c1f97e0ceef506649443d45a7b3da5 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sun, 27 Apr 2025 20:27:45 +0200 Subject: [PATCH 13/28] Adding PermissionSystemModuleOperation tests --- .../Services/PermissionService_Tests.cs | 144 ++++++++++++++++++ 1 file changed, 144 insertions(+) diff --git a/MainProject.Tests/Services/PermissionService_Tests.cs b/MainProject.Tests/Services/PermissionService_Tests.cs index ef5df74..f872180 100644 --- a/MainProject.Tests/Services/PermissionService_Tests.cs +++ b/MainProject.Tests/Services/PermissionService_Tests.cs @@ -38,6 +38,15 @@ public class PermissionService_Tests Enabled = false }; + private static PermissionSystemModuleOperation _permissionSystemModuleOperation = new PermissionSystemModuleOperation() + { + PermissionSystemModule = _permissionSystemModule, + PermissionSystemModuleId = 0, + PermissionOperation = _permissionOperation, + PermissionOperationId = 0, + Enabled = false + }; + [TestMethod] public void Inizialize() { @@ -675,9 +684,144 @@ public class PermissionService_Tests #endregion +#region "PermissionSystemModuleOperation" + + [TestMethod] + public async Task GetPermissionSystemModuleOperationByGuidAsync_Null() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionSystemModuleOperationByGuidAsync(Guid.NewGuid().ToString()); + Assert.IsTrue(permission == null); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task CreatePermissionSystemModuleOperationAsync_Success() + { + try + { + var permission = await _permissionService.CreatePermissionSystemModuleOperationAsync(_permissionSystemModule, _permissionOperation, true); + Assert.IsInstanceOfType(permission, typeof(PermissionSystemModuleOperation)); + Assert.IsNotNull(permission); + Assert.IsTrue(permission.Enabled); + _permissionSystemModuleOperation = permission; + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task CreatePermissionSystemModuleOperationAsync_Exception() + { + try + { + var exceptionPermissionService = TestUtils.CreatePermissionServiceException(); + + if (exceptionPermissionService != null) + { + try + { + var user = await exceptionPermissionService.CreatePermissionSystemModuleOperationAsync(_permissionSystemModule, _permissionOperation, true); + Assert.Fail($"Expected exception instead of response: {user?.Guid}"); + } + catch (Exception exception) + { + Assert.IsInstanceOfType(exception, typeof(Exception)); + Assert.IsInstanceOfType(exception, typeof(CreateException)); + } + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task HandleEnabledPermissionSystemModuleOperationAsync() + { + try + { + var updated = await _permissionService.HandleEnabledPermissionSystemModuleOperationAsync(_permissionSystemModuleOperation, false); + Assert.IsTrue(updated); + Assert.IsTrue(!_permissionSystemModuleOperation.Enabled); + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task GetPermissionSystemModuleOperationByGuidAsync_Success() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetPermissionSystemModuleOperationByGuidAsync(_permissionSystemModuleOperation.Guid); + Assert.IsNotNull(permission); + Assert.IsInstanceOfType(permission, typeof(PermissionSystemModuleOperation)); + Assert.IsTrue(permission.Enabled == _permissionSystemModuleOperation.Enabled); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + +#endregion + #region "DeletePermissions" + [TestMethod] + public async Task DeletePermissionSystemModuleOperationAsync() + { + try + { + var deleted = await _permissionService.DeletePermissionSystemModuleOperationAsync(_permissionSystemModuleOperation); + Assert.IsTrue(deleted); + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + [TestMethod] public async Task DeletePermissionSystemModuleAsync() { -- 2.49.1 From 8a2f038185f01e5d6601df0ad83947894f4d4731 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sun, 27 Apr 2025 20:39:50 +0200 Subject: [PATCH 14/28] Adding RolePermissionSystemModuleOperation tests --- .../Services/PermissionService_Tests.cs | 174 +++++++++++++++++- 1 file changed, 170 insertions(+), 4 deletions(-) diff --git a/MainProject.Tests/Services/PermissionService_Tests.cs b/MainProject.Tests/Services/PermissionService_Tests.cs index f872180..413572b 100644 --- a/MainProject.Tests/Services/PermissionService_Tests.cs +++ b/MainProject.Tests/Services/PermissionService_Tests.cs @@ -47,6 +47,19 @@ public class PermissionService_Tests Enabled = false }; + private static RolePermissionSystemModuleOperation _rolePermissionSystemModuleOperation = new RolePermissionSystemModuleOperation() + { + PermissionSystemModuleOperation = _permissionSystemModuleOperation, + PermissionSystemModuleOperationId = 0, + Role = new Role() + { + Name = _name + "-ROLE", + IsNotEditable = false + }, + RoleId = 0, + Active = false + }; + [TestMethod] public void Inizialize() { @@ -619,8 +632,8 @@ public class PermissionService_Tests { try { - var user = await exceptionPermissionService.CreatePermissionSystemModuleAsync(_permissionSystem, _permissionModule, true); - Assert.Fail($"Expected exception instead of response: {user?.Guid}"); + var permission = await exceptionPermissionService.CreatePermissionSystemModuleAsync(_permissionSystem, _permissionModule, true); + Assert.Fail($"Expected exception instead of response: {permission?.Guid}"); } catch (Exception exception) { @@ -739,8 +752,8 @@ public class PermissionService_Tests { try { - var user = await exceptionPermissionService.CreatePermissionSystemModuleOperationAsync(_permissionSystemModule, _permissionOperation, true); - Assert.Fail($"Expected exception instead of response: {user?.Guid}"); + var permission = await exceptionPermissionService.CreatePermissionSystemModuleOperationAsync(_permissionSystemModule, _permissionOperation, true); + Assert.Fail($"Expected exception instead of response: {permission?.Guid}"); } catch (Exception exception) { @@ -804,8 +817,161 @@ public class PermissionService_Tests #endregion +#region "RolePermissionSystemModuleOperation" + + [TestMethod] + public async Task GetRolePermissionSystemModuleOperationByGuidAsync_Null() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetRolePermissionSystemModuleOperationByGuidAsync(Guid.NewGuid().ToString()); + Assert.IsTrue(permission == null); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task CreateRolePermissionSystemModuleOperationAsync_Success() + { + try + { + var expectedUser = ModelsInit.CreateUser(); + Role role = new() + { + Name = expectedUser.Role?.Name ?? String.Empty, + IsNotEditable = expectedUser.Role?.IsNotEditable ?? false, + Guid = expectedUser.Role?.Guid ?? String.Empty + }; + + var permission = await _permissionService.CreateRolePermissionSystemModuleOperationAsync(role, _permissionSystemModuleOperation, true); + Assert.IsInstanceOfType(permission, typeof(RolePermissionSystemModuleOperation)); + Assert.IsNotNull(permission); + Assert.IsTrue(permission.Active); + _rolePermissionSystemModuleOperation = permission; + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task CreateRolePermissionSystemModuleOperationAsync_Exception() + { + try + { + var exceptionPermissionService = TestUtils.CreatePermissionServiceException(); + + if (exceptionPermissionService != null) + { + try + { + var expectedUser = ModelsInit.CreateUser(); + Role role = new() + { + Name = expectedUser.Role?.Name ?? String.Empty, + IsNotEditable = expectedUser.Role?.IsNotEditable ?? false, + Guid = expectedUser.Role?.Guid ?? String.Empty + }; + + var permission = await exceptionPermissionService.CreateRolePermissionSystemModuleOperationAsync(role, _permissionSystemModuleOperation, true); + Assert.Fail($"Expected exception instead of response: {permission?.Guid}"); + } + catch (Exception exception) + { + Assert.IsInstanceOfType(exception, typeof(Exception)); + Assert.IsInstanceOfType(exception, typeof(CreateException)); + } + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task HandleEnabledRolePermissionSystemModuleOperationAsync() + { + try + { + var updated = await _permissionService.HandleEnabledRolePermissionSystemModuleOperationAsync(_rolePermissionSystemModuleOperation, false); + Assert.IsTrue(updated); + Assert.IsTrue(!_rolePermissionSystemModuleOperation.Active); + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task GetRolePermissionSystemModuleOperationByGuidAsync_Success() + { + try + { + + if (_permissionService != null) + { + var permission = await _permissionService.GetRolePermissionSystemModuleOperationByGuidAsync(_rolePermissionSystemModuleOperation.Guid); + Assert.IsNotNull(permission); + Assert.IsInstanceOfType(permission, typeof(RolePermissionSystemModuleOperation)); + Assert.IsTrue(permission.Active == _rolePermissionSystemModuleOperation.Active); + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + +#endregion + + + #region "DeletePermissions" + [TestMethod] + public async Task DeleteRolePermissionSystemModuleOperationAsync() + { + try + { + var deleted = await _permissionService.DeleteRolePermissionSystemModuleOperationAsync(_rolePermissionSystemModuleOperation); + Assert.IsTrue(deleted); + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + [TestMethod] public async Task DeletePermissionSystemModuleOperationAsync() { -- 2.49.1 From c639f86068ecc143b21307a2a23114ada7e94d8e Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sun, 27 Apr 2025 22:29:35 +0200 Subject: [PATCH 15/28] Adding permissions during startup --- MainProject/Config/permissions.json | 32 ++++++++++ MainProject/Models/Common/OperationInfo.cs | 9 +++ MainProject/Models/Common/PermissionInfo.cs | 9 +++ MainProject/Models/Common/PermissionsFile.cs | 8 +++ .../Common/RolePermissionModuleOperation.cs | 9 +++ MainProject/Models/Settings/AppSettings.cs | 2 +- .../Models/Settings/PermissionsSettings.cs | 8 +++ MainProject/Program.cs | 1 + MainProject/Services/PermissionService.cs | 62 +++++++++++++------ MainProject/Utils/FileUtils.cs.cs | 52 ++++++++++++++++ MainProject/Utils/ProgramUtils.cs | 22 +++++++ MainProject/appsettings.json | 3 + 12 files changed, 196 insertions(+), 21 deletions(-) create mode 100644 MainProject/Config/permissions.json create mode 100644 MainProject/Models/Common/OperationInfo.cs create mode 100644 MainProject/Models/Common/PermissionInfo.cs create mode 100644 MainProject/Models/Common/PermissionsFile.cs create mode 100644 MainProject/Models/Common/RolePermissionModuleOperation.cs create mode 100644 MainProject/Models/Settings/PermissionsSettings.cs create mode 100644 MainProject/Utils/FileUtils.cs.cs diff --git a/MainProject/Config/permissions.json b/MainProject/Config/permissions.json new file mode 100644 index 0000000..57248b8 --- /dev/null +++ b/MainProject/Config/permissions.json @@ -0,0 +1,32 @@ +{ + "PermissionInfos": [ + { + "System": "base", + "RolePermissionModuleOperations": [ + { + "Module": "role", + "Operations": [ + { "Operation": "create", "Roles": [] }, + { "Operation": "read", "Roles": [] }, + { "Operation": "update", "Roles": [] }, + { "Operation": "delete", "Roles": [] }, + { "Operation": "list", "Roles": [] }, + { "Operation": "use", "Roles": [] } + ] + }, + { + "Module": "user", + "Operations": [ + { "Operation": "create", "Roles": [] }, + { "Operation": "read", "Roles": [] }, + { "Operation": "update", "Roles": [] }, + { "Operation": "delete", "Roles": [] }, + { "Operation": "list", "Roles": [] }, + { "Operation": "use", "Roles": [] } + ] + } + ] + } + + ] +} \ No newline at end of file diff --git a/MainProject/Models/Common/OperationInfo.cs b/MainProject/Models/Common/OperationInfo.cs new file mode 100644 index 0000000..7e9a9a8 --- /dev/null +++ b/MainProject/Models/Common/OperationInfo.cs @@ -0,0 +1,9 @@ +namespace BasicDotnetTemplate.MainProject.Models.Common; + +public class OperationInfo +{ +#nullable enable + public string? Operation { get; set; } + public List? Roles {get; set; } +#nullable disable +} \ No newline at end of file diff --git a/MainProject/Models/Common/PermissionInfo.cs b/MainProject/Models/Common/PermissionInfo.cs new file mode 100644 index 0000000..558fc5d --- /dev/null +++ b/MainProject/Models/Common/PermissionInfo.cs @@ -0,0 +1,9 @@ +namespace BasicDotnetTemplate.MainProject.Models.Common; + +public class PermissionInfo +{ +#nullable enable + public string? System { get; set; } + public List? RolePermissionModuleOperations {get; set; } +#nullable disable +} \ No newline at end of file diff --git a/MainProject/Models/Common/PermissionsFile.cs b/MainProject/Models/Common/PermissionsFile.cs new file mode 100644 index 0000000..f5a4d7b --- /dev/null +++ b/MainProject/Models/Common/PermissionsFile.cs @@ -0,0 +1,8 @@ +namespace BasicDotnetTemplate.MainProject.Models.Common; + +public class PermissionsFile +{ +#nullable enable + public List? PermissionInfos { get; set; } +#nullable disable +} \ No newline at end of file diff --git a/MainProject/Models/Common/RolePermissionModuleOperation.cs b/MainProject/Models/Common/RolePermissionModuleOperation.cs new file mode 100644 index 0000000..6d132e5 --- /dev/null +++ b/MainProject/Models/Common/RolePermissionModuleOperation.cs @@ -0,0 +1,9 @@ +namespace BasicDotnetTemplate.MainProject.Models.Common; + +public class RolePermissionModuleOperation +{ +#nullable enable + public string? Module { get; set; } + public List? Operations { get; set; } +#nullable disable +} \ No newline at end of file diff --git a/MainProject/Models/Settings/AppSettings.cs b/MainProject/Models/Settings/AppSettings.cs index b92311f..3df03e9 100644 --- a/MainProject/Models/Settings/AppSettings.cs +++ b/MainProject/Models/Settings/AppSettings.cs @@ -9,6 +9,6 @@ public class AppSettings public DatabaseSettings? DatabaseSettings { get; set; } public JwtSettings? JwtSettings { get; set; } public EncryptionSettings? EncryptionSettings { get; set; } - + public PermissionsSettings? PermissionsSettings { get; set; } #nullable disable } \ No newline at end of file diff --git a/MainProject/Models/Settings/PermissionsSettings.cs b/MainProject/Models/Settings/PermissionsSettings.cs new file mode 100644 index 0000000..495dc9a --- /dev/null +++ b/MainProject/Models/Settings/PermissionsSettings.cs @@ -0,0 +1,8 @@ +namespace BasicDotnetTemplate.MainProject.Models.Settings; + +public class PermissionsSettings +{ +#nullable enable + public string? FilePath { get; set; } +#nullable disable +} \ No newline at end of file diff --git a/MainProject/Program.cs b/MainProject/Program.cs index 732a39e..e6213b2 100644 --- a/MainProject/Program.cs +++ b/MainProject/Program.cs @@ -45,6 +45,7 @@ internal static class Program WebApplication app = builder.Build(); ProgramUtils.AddMiddlewares(ref app); ProgramUtils.CreateRoles(ref app); + ProgramUtils.CreatePermissions(ref app); Logger.Info("[Program][Initialize] End building"); return app; diff --git a/MainProject/Services/PermissionService.cs b/MainProject/Services/PermissionService.cs index 170e8ad..f56f7bb 100644 --- a/MainProject/Services/PermissionService.cs +++ b/MainProject/Services/PermissionService.cs @@ -4,6 +4,8 @@ using BasicDotnetTemplate.MainProject.Core.Database; using BasicDotnetTemplate.MainProject.Models.Api.Common.Exceptions; using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; using Microsoft.EntityFrameworkCore; +using BasicDotnetTemplate.MainProject.Models.Common; +using BasicDotnetTemplate.MainProject.Utils; namespace BasicDotnetTemplate.MainProject.Services; @@ -32,7 +34,7 @@ public interface IPermissionService Task GetPermissionSystemModuleByGuidAsync(string guid); Task HandleEnabledPermissionSystemModuleAsync(PermissionSystemModule permission, bool enabled); Task CreatePermissionSystemModuleAsync( - PermissionSystem permissionSystem, + PermissionSystem permissionSystem, PermissionModule permissionModule, bool enabled ); @@ -42,7 +44,7 @@ public interface IPermissionService Task GetPermissionSystemModuleOperationByGuidAsync(string guid); Task HandleEnabledPermissionSystemModuleOperationAsync(PermissionSystemModuleOperation permission, bool enabled); Task CreatePermissionSystemModuleOperationAsync( - PermissionSystemModule permissionSystemModule, + PermissionSystemModule permissionSystemModule, PermissionOperation permissionOperation, bool enabled ); @@ -52,11 +54,14 @@ public interface IPermissionService Task GetRolePermissionSystemModuleOperationByGuidAsync(string guid); Task HandleEnabledRolePermissionSystemModuleOperationAsync(RolePermissionSystemModuleOperation permission, bool active); Task CreateRolePermissionSystemModuleOperationAsync( - Role role, + Role role, PermissionSystemModuleOperation permissionSystemModuleOperation, bool enabled ); Task DeleteRolePermissionSystemModuleOperationAsync(RolePermissionSystemModuleOperation permission); + + Task?> CreatePermissionsOnStartupAsync(); + } public class PermissionService : BaseService, IPermissionService @@ -201,8 +206,8 @@ public class PermissionService : BaseService, IPermissionService } private static RolePermissionSystemModuleOperation CreateRolePermissionSystemModuleOperationData( - Role role, - PermissionSystemModuleOperation permissionModuleOperation, + Role role, + PermissionSystemModuleOperation permissionModuleOperation, bool active ) { @@ -221,7 +226,7 @@ public class PermissionService : BaseService, IPermissionService return permission; } -#region "PermissionSystem" + #region "PermissionSystem" public async Task GetPermissionSystemByGuidAsync(string guid) { @@ -290,10 +295,10 @@ public class PermissionService : BaseService, IPermissionService return deleted; } -#endregion + #endregion -#region "PermissionModule" + #region "PermissionModule" public async Task GetPermissionModuleByGuidAsync(string guid) @@ -363,10 +368,10 @@ public class PermissionService : BaseService, IPermissionService return deleted; } -#endregion + #endregion -#region "PermissionOperation" + #region "PermissionOperation" public async Task GetPermissionOperationByGuidAsync(string guid) { @@ -418,10 +423,10 @@ public class PermissionService : BaseService, IPermissionService return deleted; } -#endregion + #endregion -#region "PermissionSystemModule" + #region "PermissionSystemModule" public async Task GetPermissionSystemModuleByGuidAsync(string guid) { @@ -429,7 +434,7 @@ public class PermissionService : BaseService, IPermissionService } public async Task CreatePermissionSystemModuleAsync( - PermissionSystem permissionSystem, + PermissionSystem permissionSystem, PermissionModule permissionModule, bool enabled ) @@ -489,10 +494,10 @@ public class PermissionService : BaseService, IPermissionService return deleted; } -#endregion + #endregion -#region "PermissionSystemModuleOperation" + #region "PermissionSystemModuleOperation" public async Task GetPermissionSystemModuleOperationByGuidAsync(string guid) { @@ -500,7 +505,7 @@ public class PermissionService : BaseService, IPermissionService } public async Task CreatePermissionSystemModuleOperationAsync( - PermissionSystemModule permissionSystemModule, + PermissionSystemModule permissionSystemModule, PermissionOperation permissionOperation, bool enabled ) @@ -560,10 +565,10 @@ public class PermissionService : BaseService, IPermissionService return deleted; } -#endregion + #endregion -#region "RolePermissionSystemModuleOperation" + #region "RolePermissionSystemModuleOperation" public async Task GetRolePermissionSystemModuleOperationByGuidAsync(string guid) { @@ -571,7 +576,7 @@ public class PermissionService : BaseService, IPermissionService } public async Task CreateRolePermissionSystemModuleOperationAsync( - Role role, + Role role, PermissionSystemModuleOperation permissionSystemModuleOperation, bool enabled ) @@ -631,7 +636,24 @@ public class PermissionService : BaseService, IPermissionService return deleted; } -#endregion + #endregion + + + public async Task?> CreatePermissionsOnStartupAsync() + { + try + { + List? newPermissions = null; + PermissionsFile? permissionsFile = FileUtils.ConvertFileToObject(System.AppDomain.CurrentDomain.BaseDirectory + this._appSettings.PermissionsSettings.FilePath); + return newPermissions; + } + catch (Exception exception) + { + Logger.Error(exception, $"[PermissionService][CreatePermissionsOnStartupAsync]"); + throw new CreateException($"An error occurred while adding permissions during startup", exception); + } + + } } diff --git a/MainProject/Utils/FileUtils.cs.cs b/MainProject/Utils/FileUtils.cs.cs new file mode 100644 index 0000000..be3ed4e --- /dev/null +++ b/MainProject/Utils/FileUtils.cs.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.OpenApi.Models; +using MongoDB.Driver; +using NLog; +using BasicDotnetTemplate.MainProject.Core.Database; +using BasicDotnetTemplate.MainProject.Core.Middlewares; +using BasicDotnetTemplate.MainProject.Models.Settings; +using BasicDotnetTemplate.MainProject.Services; +using BasicDotnetTemplate.MainProject.Models.Api.Data.Role; +using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; + + + +namespace BasicDotnetTemplate.MainProject.Utils; + +public static class FileUtils +{ + private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); + + public static T? ConvertFileToObject(string? filePath = "") + { + Logger.Info("[FileUtils][ReadJson] Reading file"); + + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentException("filePath cannot be null or empty", nameof(filePath)); + } + + if (!File.Exists(filePath)) + { + throw new FileNotFoundException("The specified file does not exists", filePath); + } + + try + { + string fileContent = File.ReadAllText(filePath); + + return JsonSerializer.Deserialize(fileContent, new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }); + } + catch (JsonException ex) + { + throw new InvalidOperationException("Error during file deserialization", ex); + } + } + +} \ No newline at end of file diff --git a/MainProject/Utils/ProgramUtils.cs b/MainProject/Utils/ProgramUtils.cs index 7b55858..9e69376 100644 --- a/MainProject/Utils/ProgramUtils.cs +++ b/MainProject/Utils/ProgramUtils.cs @@ -218,6 +218,7 @@ public static class ProgramUtils builder.Services.AddHttpContextAccessor(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); Logger.Info("[ProgramUtils][AddScopes] Done scopes"); @@ -271,4 +272,25 @@ public static class ProgramUtils } + public static void CreatePermissions(ref WebApplication app) + { + Logger.Info("[ProgramUtils][CreatePermissions] Adding permissions..."); + using (var scope = app.Services.CreateScope()) + { + var permissionService = scope.ServiceProvider.GetRequiredService; + if (permissionService != null) + { + var isValidThread = Task.Run(() => permissionService!.Invoke()?.CreatePermissionsOnStartupAsync()); + if (isValidThread.Result != null) + { + Logger.Info("[ProgramUtils][CreatePermissions] Done permissions"); + } + else + { + Logger.Error("[ProgramUtils][CreatePermissions] Something went wrong"); + } + } + } + } + } \ No newline at end of file diff --git a/MainProject/appsettings.json b/MainProject/appsettings.json index 86a85b8..8893bf2 100644 --- a/MainProject/appsettings.json +++ b/MainProject/appsettings.json @@ -37,6 +37,9 @@ "EncryptionSettings": { "Salt": "S7VIidfXQf1tOQYX", "Pepper": "" + }, + "PermissionsSettings": { + "FilePath": "Config/permissions.json" } } } \ No newline at end of file -- 2.49.1 From 9936e857819ee1a7d3ce29133c53b192e324b5ce Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sat, 17 May 2025 22:47:22 +0200 Subject: [PATCH 16/28] Added permissions creation during startup --- MainProject/Config/permissions.json | 4 +- MainProject/Services/PermissionService.cs | 623 +++++++++++++++++++++- MainProject/Services/RoleService.cs | 13 +- MainProject/Utils/CommonDbMethodsUtils.cs | 32 ++ MainProject/Utils/FileUtils.cs.cs | 20 +- MainProject/Utils/ProgramUtils.cs | 8 +- 6 files changed, 670 insertions(+), 30 deletions(-) create mode 100644 MainProject/Utils/CommonDbMethodsUtils.cs diff --git a/MainProject/Config/permissions.json b/MainProject/Config/permissions.json index 57248b8..aeabb85 100644 --- a/MainProject/Config/permissions.json +++ b/MainProject/Config/permissions.json @@ -4,7 +4,7 @@ "System": "base", "RolePermissionModuleOperations": [ { - "Module": "role", + "Module": "roles", "Operations": [ { "Operation": "create", "Roles": [] }, { "Operation": "read", "Roles": [] }, @@ -15,7 +15,7 @@ ] }, { - "Module": "user", + "Module": "users", "Operations": [ { "Operation": "create", "Roles": [] }, { "Operation": "read", "Roles": [] }, diff --git a/MainProject/Services/PermissionService.cs b/MainProject/Services/PermissionService.cs index f56f7bb..5a45384 100644 --- a/MainProject/Services/PermissionService.cs +++ b/MainProject/Services/PermissionService.cs @@ -60,19 +60,28 @@ public interface IPermissionService ); Task DeleteRolePermissionSystemModuleOperationAsync(RolePermissionSystemModuleOperation permission); - Task?> CreatePermissionsOnStartupAsync(); + List CreatePermissionsOnStartupAsync(); } public class PermissionService : BaseService, IPermissionService { private readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); + private readonly CommonDbMethodsUtils _commonDbMethodsUtils; + public PermissionService( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, SqlServerContext sqlServerContext ) : base(httpContextAccessor, configuration, sqlServerContext) - { } + { + _commonDbMethodsUtils = new CommonDbMethodsUtils(sqlServerContext); + } + + private IQueryable GetRoleByNameQueryable(string name) + { + return _commonDbMethodsUtils.GetRoleByNameQueryable(name); + } private IQueryable GetPermissionSystemsQueryable() { @@ -640,12 +649,608 @@ public class PermissionService : BaseService, IPermissionService - public async Task?> CreatePermissionsOnStartupAsync() + #region "CreatePermissionOnStartup" + + private static List? GetSystemNamesFromFile(PermissionsFile permissionsFile) + { + return permissionsFile?.PermissionInfos?.Where(x => x.System != null).Select(x => x.System)?.ToList(); + } + + private static List? GetModulesNamesFromFile(PermissionsFile permissionsFile) + { + return permissionsFile?.PermissionInfos? + .Where(x => x.RolePermissionModuleOperations != null) + .SelectMany(x => x.RolePermissionModuleOperations!) + .Select(y => y.Module) + .Distinct() + .ToList(); + } + + private static List? GetModulesNamesFromPermissionInfo(PermissionInfo permissionInfo) + { + return permissionInfo.RolePermissionModuleOperations? + .Select(y => y.Module) + .Distinct() + .ToList(); + } + + private static List? GetOperationsNamesFromFile(PermissionInfo permissionInfo) + { + return permissionInfo?.RolePermissionModuleOperations? + .Where(x => x != null) + .Where(x => x.Operations != null) + .SelectMany(y => y.Operations!) + .Select(z => z.Operation) + .Distinct() + .ToList(); + } + + private (List, List) HandlePermissionSystemOnStartup(PermissionsFile permissionsFile) + { + List newPermissions = []; + List systemNames = []; + List permissionSystemList = []; + + List? systems = GetSystemNamesFromFile(permissionsFile); + if (systems != null && systems.Count > 0) + { + foreach (var system in systems) + { + if (!String.IsNullOrEmpty(system)) + { + systemNames.Add(system); + } + } + } + + foreach (var system in systemNames) + { + PermissionSystem? permissionSystem = this.GetPermissionSystemByNameAsync(system).Result; + if (permissionSystem == null) + { + permissionSystem = this.CreatePermissionSystemAsync(system, true).Result; + newPermissions.Add($"Added new PermissionSystem => {permissionSystem?.Name}"); + } + if (permissionSystem != null) + { + permissionSystemList.Add(permissionSystem); + } + } + + return (permissionSystemList, newPermissions); + } + + private (List, List) HandlePermissionModuleOnStartup(PermissionsFile permissionsFile) + { + List newPermissions = []; + List moduleNames = []; + List permissionModuleList = []; + + List? modules = GetModulesNamesFromFile(permissionsFile); + + if (modules != null && modules.Count > 0) + { + foreach (var module in modules) + { + if (!String.IsNullOrEmpty(module)) + { + moduleNames.Add(module); + } + } + } + + foreach (var module in moduleNames) + { + PermissionModule? permissionModule = this.GetPermissionModuleByNameAsync(module).Result; + if (permissionModule == null) + { + permissionModule = this.CreatePermissionModuleAsync(module, true).Result; + newPermissions.Add($"Added new PermissionModule => {permissionModule?.Name}"); + } + if (permissionModule != null) + { + permissionModuleList.Add(permissionModule); + } + } + + return (permissionModuleList, newPermissions); + } + + private (List, List) HandlePermissionOperationOnStartup(PermissionsFile permissionsFile) + { + List newPermissions = []; + List operationNames = []; + List permissionOperationList = []; + + List? operations = permissionsFile.PermissionInfos? + .Where(x => x.RolePermissionModuleOperations != null) + .SelectMany(x => x.RolePermissionModuleOperations!) + .Where(x => x.Operations != null) + .SelectMany(y => y.Operations!) + .Select(z => z.Operation) + .Distinct() + .ToList(); + + if (operations != null && operations.Count > 0) + { + foreach (var operation in operations) + { + if (!String.IsNullOrEmpty(operation)) + { + operationNames.Add(operation); + } + } + } + + foreach (var operation in operationNames) + { + PermissionOperation? permissionOperation = this.GetPermissionOperationByNameAsync(operation).Result; + if (permissionOperation == null) + { + permissionOperation = this.CreatePermissionOperationAsync(operation).Result; + newPermissions.Add($"Added new PermissionOperation => {permissionOperation?.Name}"); + } + if (permissionOperation != null) + { + permissionOperationList.Add(permissionOperation); + } + } + + return (permissionOperationList, newPermissions); + } + + private async Task> HandleRolesOnStartup(PermissionsFile permissionsFile) + { + List roleNames = []; + List rolesList = []; + + List? roles = permissionsFile.PermissionInfos? + .Where(x => x.RolePermissionModuleOperations != null)? + .SelectMany(x => x.RolePermissionModuleOperations!)? + .Where(x => x.Operations != null)? + .SelectMany(y => y.Operations!)? + .Where(z => z.Roles != null)? + .SelectMany(z => z.Roles!)? + .Where(z => z != null)? + .Distinct()? + .ToList(); + + if (roles != null && roles.Count > 0) + { + foreach (var role in roles) + { + if (!String.IsNullOrEmpty(role)) + { + roleNames.Add(role); + } + } + } + + foreach (var roleName in roleNames) + { + Role? role = await this.GetRoleByNameQueryable(roleName).FirstOrDefaultAsync(); + if (role == null) + { + Role tempRole = new() + { + CreationTime = DateTime.UtcNow, + IsDeleted = false, + Guid = Guid.NewGuid().ToString(), + Name = roleName, + IsNotEditable = false + }; + using var transaction = await _sqlServerContext.Database.BeginTransactionAsync(); + try + { + await _sqlServerContext.Roles.AddAsync(tempRole); + await _sqlServerContext.SaveChangesAsync(); + await transaction.CommitAsync(); + role = tempRole; + } + catch (Exception exception) + { + await transaction.RollbackAsync(); + Logger.Error(exception, $"[RoleService][CreateRoleAsync]"); + throw new CreateException($"An error occurred while saving the role for transaction ID {transaction.TransactionId}.", exception); + } + + Logger.Info($"Added new Role => {role?.Name}"); + } + if (role != null) + { + rolesList.Add(role); + } + } + + return rolesList; + } + + private (List, List) HandlePermissionSystemModulesOnStartup(PermissionSystem permissionSystem, List permissionModules) + { + List newPermissions = []; + List permissionSystemModuleList = []; + + foreach (var permissionModule in permissionModules) + { + PermissionSystemModule? permissionSystemModule = this.GetPermissionSystemModulesQueryable()? + .Where(x => + x.PermissionSystemId == permissionSystem!.Id && + x.PermissionModuleId == permissionModule.Id + )?.FirstOrDefault(); + if (permissionSystemModule == null) + { + permissionSystemModule = this.CreatePermissionSystemModuleAsync(permissionSystem!, permissionModule, true).Result; + newPermissions.Add($"Added new PermissionSystemModule => {permissionSystem?.Name}.{permissionModule?.Name}"); + } + if (permissionSystemModule != null) + { + permissionSystemModuleList.Add(permissionSystemModule); + } + } + + return (permissionSystemModuleList, newPermissions); + } + + private (List, List) HandlePermissionSystemModuleOnStartup + ( + PermissionsFile permissionsFile, + List permissionSystems, + List allPermissionModules, + PermissionInfo permissionInfo + ) + { + List newPermissions = []; + List permissionSystemModuleList = []; + + PermissionSystem? permissionSystem = permissionSystems.FirstOrDefault(x => x.Name == permissionInfo.System); + if (permissionSystem != null) + { + List? modules = GetModulesNamesFromFile(permissionsFile); + if (modules != null && modules.Count > 0) + { + List permissionModules = allPermissionModules.Where(x => modules.Contains(x.Name)).ToList(); + if (permissionModules != null && permissionModules.Count > 0) + { + (permissionSystemModuleList, newPermissions) = this.HandlePermissionSystemModulesOnStartup(permissionSystem, permissionModules); + } + } + } + + return (permissionSystemModuleList, newPermissions); + } + private (List, List) HandlePermissionSystemModuleOnStartup( + PermissionsFile permissionsFile, + List permissionSystems, + List allPermissionModules + ) + { + List newPermissions = []; + List permissionSystemModuleList = []; + + if (permissionsFile?.PermissionInfos != null) + { + foreach (var permissionInfo in permissionsFile!.PermissionInfos!) + { + if (!String.IsNullOrEmpty(permissionInfo.System)) + { + var modulesNames = GetModulesNamesFromPermissionInfo(permissionInfo); + if (modulesNames != null && modulesNames.Count > 0) + { + List permissionModules = allPermissionModules.Where(x => modulesNames.Contains(x.Name)).ToList() ?? []; + (permissionSystemModuleList, newPermissions) = this.HandlePermissionSystemModuleOnStartup(permissionsFile, permissionSystems, permissionModules, permissionInfo); + } + } + } + } + + return (permissionSystemModuleList, newPermissions); + } + + private (List, List) HandlePermissionSystemModuleOperationOnStartup + ( + PermissionSystemModule permissionSystemModule, + List permissionOperations + ) + { + List newPermissions = []; + List permissionSystemModuleOperationList = []; + + foreach (var permissionOperation in permissionOperations) + { + PermissionSystemModuleOperation? permissionSystemModuleOperation = this.GetPermissionSystemModuleOperationsQueryable()? + .FirstOrDefault(x => + x.PermissionSystemModuleId == permissionSystemModule!.Id && + x.PermissionOperationId == permissionOperation.Id + ); + if (permissionSystemModuleOperation == null) + { + permissionSystemModuleOperation = this.CreatePermissionSystemModuleOperationAsync(permissionSystemModule!, permissionOperation, true).Result; + newPermissions.Add($"Added new PermissionSystemModuleOperation => {permissionSystemModuleOperation?.PermissionSystemModule?.PermissionSystem?.Name}.{permissionSystemModuleOperation?.PermissionSystemModule?.PermissionModule?.Name}.{permissionSystemModuleOperation?.PermissionOperation?.Name}"); + } + if (permissionSystemModuleOperation != null) + { + permissionSystemModuleOperationList.Add(permissionSystemModuleOperation!); + } + } + + return (permissionSystemModuleOperationList, newPermissions); + } + + private (List, List) HandlePermissionSystemModuleOperationOnStartup + ( + List permissionSystemModulesList, + List allPermissionOperations, + PermissionInfo permissionInfo + ) + { + List newPermissions = []; + List tmpPermissions = []; + List permissionSystemModuleOperationList = []; + List tmpPermissionSystemModuleOperationList = []; + + if (permissionInfo != null && permissionInfo.RolePermissionModuleOperations != null) + { + foreach (var rolePermissionModuleOperation in permissionInfo.RolePermissionModuleOperations) + { + PermissionSystemModule? permissionSystemModule = permissionSystemModulesList.FirstOrDefault(x => x.PermissionModule.Name == rolePermissionModuleOperation.Module); + if (permissionSystemModule != null) + { + var operationsNames = rolePermissionModuleOperation.Operations?.Select(x => x.Operation).ToList(); + if (operationsNames != null && operationsNames.Count > 0) + { + List permissionOperations = allPermissionOperations.Where(x => operationsNames.Contains(x.Name)).ToList(); + (tmpPermissionSystemModuleOperationList, tmpPermissions) = this.HandlePermissionSystemModuleOperationOnStartup(permissionSystemModule, permissionOperations); + newPermissions.AddRange(tmpPermissions); + permissionSystemModuleOperationList.AddRange(tmpPermissionSystemModuleOperationList); + } + } + } + } + + return (permissionSystemModuleOperationList, newPermissions); + } + + private (List, List) HandlePermissionSystemModuleOperationOnStartup + ( + PermissionsFile permissionsFile, + List permissionSystemModules, + List allPermissionOperation + ) + { + List newPermissions = []; + List tmpPermissions = []; + List permissionSystemModuleOperationList = []; + List tmpPermissionSystemModuleOperationList = []; + + if (permissionsFile.PermissionInfos != null) + { + foreach (var permissionInfo in permissionsFile.PermissionInfos!) + { + if (!String.IsNullOrEmpty(permissionInfo.System)) + { + // Get all PermissionSystemModules by System.Name + List permissionSystemModulesList = permissionSystemModules + .Where(x => x.PermissionSystem.Name == permissionInfo.System).ToList(); + + if (permissionSystemModulesList != null && permissionSystemModulesList.Count > 0) + { + (tmpPermissionSystemModuleOperationList, tmpPermissions) = this.HandlePermissionSystemModuleOperationOnStartup + ( + permissionSystemModulesList, + allPermissionOperation, + permissionInfo + ); + newPermissions.AddRange(tmpPermissions); + permissionSystemModuleOperationList.AddRange(tmpPermissionSystemModuleOperationList); + } + } + } + } + + return (permissionSystemModuleOperationList, newPermissions); + } + + private (List, List) HandleRolePermissionSystemModuleOperationOnStartup + ( + List allPermissionSystemModuleOperationsBySystem, + List allRoles, + PermissionInfo permissionInfo + ) + { + List newPermissions = []; + List tmpPermissions = []; + List rolePermissionSystemModuleOperationList = []; + List tmpRolePermissionSystemModuleOperationList = []; + + if (permissionInfo != null && permissionInfo.RolePermissionModuleOperations != null) + { + foreach (var rolePermissionModuleOperation in permissionInfo.RolePermissionModuleOperations) + { + List? allPermissionSystemModuleOperationsBySystemModule = allPermissionSystemModuleOperationsBySystem + .Where(x => x.PermissionSystemModule.PermissionModule.Name == rolePermissionModuleOperation.Module) + .ToList(); + if (allPermissionSystemModuleOperationsBySystemModule != null && allPermissionSystemModuleOperationsBySystemModule.Count > 0) + { + var operationsNames = rolePermissionModuleOperation.Operations?.Select(x => x.Operation).ToList(); + if (operationsNames != null && operationsNames.Count > 0) + { + List permissionSystemModuleOperations = allPermissionSystemModuleOperationsBySystemModule + .Where(x => operationsNames.Contains(x.PermissionOperation.Name)).ToList(); + (tmpRolePermissionSystemModuleOperationList, tmpPermissions) = this.HandleRolePermissionSystemModuleOperationOnStartup( + permissionSystemModuleOperations, + allRoles, + rolePermissionModuleOperation + ); + newPermissions.AddRange(tmpPermissions); + rolePermissionSystemModuleOperationList.AddRange(tmpRolePermissionSystemModuleOperationList); + } + } + } + } + + return (rolePermissionSystemModuleOperationList, newPermissions); + } + + private (List, List) HandleRolePermissionSystemModuleOperationOnStartup + ( + List permissionSystemModuleOperations, + List allRoles, + RolePermissionModuleOperation rolePermissionModuleOperation + ) + { + List newPermissions = []; + List tmpPermissions = []; + List rolePermissionSystemModuleOperationList = []; + List tmpRolePermissionSystemModuleOperationList = []; + + if (permissionSystemModuleOperations != null && permissionSystemModuleOperations.Count > 0 && + allRoles != null && allRoles.Count > 0 && rolePermissionModuleOperation?.Operations != null && + rolePermissionModuleOperation.Operations.Count > 0 + ) + { + foreach (var operationInfo in rolePermissionModuleOperation.Operations) + { + PermissionSystemModuleOperation? permissionSystemModuleOperation = permissionSystemModuleOperations + .FirstOrDefault(x => x.PermissionOperation.Name == operationInfo.Operation); + if (permissionSystemModuleOperation != null && operationInfo.Roles != null && operationInfo.Roles.Count > 0) + { + var roles = allRoles.Where(x => operationInfo.Roles.Contains(x.Name)).ToList(); + if (roles != null && roles.Count > 0) + { + foreach (var roleName in operationInfo.Roles) + { + (tmpRolePermissionSystemModuleOperationList, tmpPermissions) = this.HandleRolePermissionSystemModuleOperationOnStartup + ( + roles, roleName, permissionSystemModuleOperation + ); + newPermissions.AddRange(tmpPermissions); + rolePermissionSystemModuleOperationList.AddRange(tmpRolePermissionSystemModuleOperationList); + } + + } + } + } + } + + return (rolePermissionSystemModuleOperationList, newPermissions); + } + + private (List, List) HandleRolePermissionSystemModuleOperationOnStartup + ( + List roles, string roleName, PermissionSystemModuleOperation permissionSystemModuleOperation + ) + { + List newPermissions = []; + List rolePermissionSystemModuleOperationList = []; + + Role? role = roles.FirstOrDefault(x => x.Name == roleName); + if (role != null) + { + RolePermissionSystemModuleOperation? rolePermissionSystemModuleOperation = this._sqlServerContext.RolePermissionSystemModuleOperations? + .FirstOrDefault(x => x.RoleId == role.Id && x.PermissionSystemModuleOperationId == permissionSystemModuleOperation!.Id); + if (rolePermissionSystemModuleOperation == null) + { + rolePermissionSystemModuleOperation = this.CreateRolePermissionSystemModuleOperationAsync(role, permissionSystemModuleOperation!, true).Result; + if (rolePermissionSystemModuleOperation != null) + { + newPermissions.Add($"Added new RolePermissionSystemModuleOperation => " + + $"{permissionSystemModuleOperation?.PermissionSystemModule?.PermissionSystem?.Name}." + + $"{permissionSystemModuleOperation?.PermissionSystemModule?.PermissionModule?.Name}." + + $"{permissionSystemModuleOperation?.PermissionOperation?.Name} for role {role.Name}"); + } + if (rolePermissionSystemModuleOperation != null) + { + rolePermissionSystemModuleOperationList.Add(rolePermissionSystemModuleOperation!); + } + } + } + + return (rolePermissionSystemModuleOperationList, newPermissions); + } + + private (List, List) HandleRolePermissionSystemModuleOperationOnStartup + ( + PermissionsFile permissionsFile, + List allPermissionSystemModuleOperations, + List allRoles + ) + { + List newPermissions = []; + List tmpPermissions = []; + List rolePermissionSystemModuleOperationList = []; + List tmpRolePermissionSystemModuleOperationList = []; + + if (permissionsFile.PermissionInfos != null) + { + foreach (var permissionInfo in permissionsFile.PermissionInfos!) + { + if (!String.IsNullOrEmpty(permissionInfo.System)) + { + // Get all PermissionSystemModuleOperations by System.Name + List allPermissionSystemModuleOperationsBySystem = allPermissionSystemModuleOperations + .Where(x => x.PermissionSystemModule.PermissionSystem.Name == permissionInfo.System).ToList(); + + if (allPermissionSystemModuleOperationsBySystem != null && allPermissionSystemModuleOperationsBySystem.Count > 0) + { + (tmpRolePermissionSystemModuleOperationList, tmpPermissions) = this.HandleRolePermissionSystemModuleOperationOnStartup + ( + allPermissionSystemModuleOperationsBySystem, + allRoles, + permissionInfo + ); + newPermissions.AddRange(tmpPermissions); + rolePermissionSystemModuleOperationList.AddRange(tmpRolePermissionSystemModuleOperationList); + } + } + } + } + + return (rolePermissionSystemModuleOperationList, newPermissions); + + } + + public List CreatePermissionsOnStartupAsync() { try { - List? newPermissions = null; - PermissionsFile? permissionsFile = FileUtils.ConvertFileToObject(System.AppDomain.CurrentDomain.BaseDirectory + this._appSettings.PermissionsSettings.FilePath); + List tmpPermissions = []; + List newPermissions = []; + PermissionsFile? permissionsFile = FileUtils.ConvertFileToObject(System.AppDomain.CurrentDomain.BaseDirectory + this._appSettings?.PermissionsSettings?.FilePath); + + List permissionSystemList = []; + List permissionModuleList = []; + List permissionOperationList = []; + List permissionSystemModuleList = []; + List permissionSystemModuleOperationList = []; + List rolePermissionSystemModuleOperationList = []; + + if (permissionsFile != null && permissionsFile.PermissionInfos != null && permissionsFile.PermissionInfos.Count > 0) + { + (permissionSystemList, tmpPermissions) = this.HandlePermissionSystemOnStartup(permissionsFile); + newPermissions.AddRange(tmpPermissions); + + (permissionModuleList, tmpPermissions) = this.HandlePermissionModuleOnStartup(permissionsFile); + newPermissions.AddRange(tmpPermissions); + + (permissionOperationList, tmpPermissions) = this.HandlePermissionOperationOnStartup(permissionsFile); + newPermissions.AddRange(tmpPermissions); + + (permissionSystemModuleList, tmpPermissions) = this.HandlePermissionSystemModuleOnStartup(permissionsFile, permissionSystemList, permissionModuleList); + newPermissions.AddRange(tmpPermissions); + + (permissionSystemModuleOperationList, tmpPermissions) = this.HandlePermissionSystemModuleOperationOnStartup(permissionsFile, permissionSystemModuleList, permissionOperationList); + newPermissions.AddRange(tmpPermissions); + + List roles = this.HandleRolesOnStartup(permissionsFile).Result; + + (rolePermissionSystemModuleOperationList, tmpPermissions) = this.HandleRolePermissionSystemModuleOperationOnStartup( + permissionsFile, + permissionSystemModuleOperationList, + roles + ); + newPermissions.AddRange(tmpPermissions); + } + return newPermissions; } catch (Exception exception) @@ -655,5 +1260,11 @@ public class PermissionService : BaseService, IPermissionService } } -} + + + #endregion + + + +} \ No newline at end of file diff --git a/MainProject/Services/RoleService.cs b/MainProject/Services/RoleService.cs index 021f0a3..d10f0e4 100644 --- a/MainProject/Services/RoleService.cs +++ b/MainProject/Services/RoleService.cs @@ -5,6 +5,7 @@ using BasicDotnetTemplate.MainProject.Models.Api.Common.Exceptions; using BasicDotnetTemplate.MainProject.Models.Api.Data.Role; using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; using Microsoft.EntityFrameworkCore; +using BasicDotnetTemplate.MainProject.Utils; namespace BasicDotnetTemplate.MainProject.Services; @@ -22,22 +23,24 @@ public interface IRoleService public class RoleService : BaseService, IRoleService { private readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); + private readonly CommonDbMethodsUtils _commonDbMethodsUtils; + public RoleService( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, SqlServerContext sqlServerContext ) : base(httpContextAccessor, configuration, sqlServerContext) - { } + { + _commonDbMethodsUtils = new CommonDbMethodsUtils(sqlServerContext); + } private IQueryable GetRolesQueryable() { - return this._sqlServerContext.Roles.Where(x => !x.IsDeleted); + return _commonDbMethodsUtils.GetRolesQueryable(); } private IQueryable GetRoleByNameQueryable(string name) { - return this.GetRolesQueryable().Where(x => - x.Name.ToString() == name.ToString() - ); + return _commonDbMethodsUtils.GetRoleByNameQueryable(name); } diff --git a/MainProject/Utils/CommonDbMethodsUtils.cs b/MainProject/Utils/CommonDbMethodsUtils.cs new file mode 100644 index 0000000..f971edf --- /dev/null +++ b/MainProject/Utils/CommonDbMethodsUtils.cs @@ -0,0 +1,32 @@ +using System; +using System.Security.Cryptography; +using System.Text; +using BasicDotnetTemplate.MainProject.Core.Database; +using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; + +namespace BasicDotnetTemplate.MainProject.Utils; +public class CommonDbMethodsUtils +{ + private readonly SqlServerContext _sqlServerContext; + + public CommonDbMethodsUtils(SqlServerContext sqlServerContext) + { + _sqlServerContext = sqlServerContext; + } + + + public IQueryable GetRolesQueryable() + { + return this._sqlServerContext.Roles.Where(x => !x.IsDeleted); + } + + public IQueryable GetRoleByNameQueryable(string name) + { + return this.GetRolesQueryable().Where(x => + x.Name.ToString() == name.ToString() + ); + } + + +} + diff --git a/MainProject/Utils/FileUtils.cs.cs b/MainProject/Utils/FileUtils.cs.cs index be3ed4e..5c7be6e 100644 --- a/MainProject/Utils/FileUtils.cs.cs +++ b/MainProject/Utils/FileUtils.cs.cs @@ -1,16 +1,5 @@ -using System; -using System.IO; using System.Text.Json; -using Microsoft.EntityFrameworkCore; -using Microsoft.OpenApi.Models; -using MongoDB.Driver; using NLog; -using BasicDotnetTemplate.MainProject.Core.Database; -using BasicDotnetTemplate.MainProject.Core.Middlewares; -using BasicDotnetTemplate.MainProject.Models.Settings; -using BasicDotnetTemplate.MainProject.Services; -using BasicDotnetTemplate.MainProject.Models.Api.Data.Role; -using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; @@ -19,6 +8,10 @@ namespace BasicDotnetTemplate.MainProject.Utils; public static class FileUtils { private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); + private static readonly JsonSerializerOptions jsonSerializerOptions = new() + { + PropertyNameCaseInsensitive = true + }; public static T? ConvertFileToObject(string? filePath = "") { @@ -38,10 +31,7 @@ public static class FileUtils { string fileContent = File.ReadAllText(filePath); - return JsonSerializer.Deserialize(fileContent, new JsonSerializerOptions - { - PropertyNameCaseInsensitive = true - }); + return JsonSerializer.Deserialize(fileContent, jsonSerializerOptions); } catch (JsonException ex) { diff --git a/MainProject/Utils/ProgramUtils.cs b/MainProject/Utils/ProgramUtils.cs index 9e69376..52b1b33 100644 --- a/MainProject/Utils/ProgramUtils.cs +++ b/MainProject/Utils/ProgramUtils.cs @@ -277,13 +277,17 @@ public static class ProgramUtils Logger.Info("[ProgramUtils][CreatePermissions] Adding permissions..."); using (var scope = app.Services.CreateScope()) { - var permissionService = scope.ServiceProvider.GetRequiredService; + Func permissionService = scope.ServiceProvider.GetRequiredService; if (permissionService != null) { var isValidThread = Task.Run(() => permissionService!.Invoke()?.CreatePermissionsOnStartupAsync()); if (isValidThread.Result != null) { - Logger.Info("[ProgramUtils][CreatePermissions] Done permissions"); + foreach (var result in isValidThread.Result) + { + var currentResult = String.IsNullOrEmpty(result) ? "No permission tracked" : result; + Logger.Info($"[ProgramUtils][CreatePermissions] => {currentResult}"); + } } else { -- 2.49.1 From 448afad655f7d40f5bf8a61f31e623e554be9d8c Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sat, 17 May 2025 22:57:53 +0200 Subject: [PATCH 17/28] Fixing issues - 1 --- MainProject/Services/PermissionService.cs | 33 ++++++++--------------- 1 file changed, 11 insertions(+), 22 deletions(-) diff --git a/MainProject/Services/PermissionService.cs b/MainProject/Services/PermissionService.cs index 5a45384..ea0bf62 100644 --- a/MainProject/Services/PermissionService.cs +++ b/MainProject/Services/PermissionService.cs @@ -674,17 +674,6 @@ public class PermissionService : BaseService, IPermissionService .ToList(); } - private static List? GetOperationsNamesFromFile(PermissionInfo permissionInfo) - { - return permissionInfo?.RolePermissionModuleOperations? - .Where(x => x != null) - .Where(x => x.Operations != null) - .SelectMany(y => y.Operations!) - .Select(z => z.Operation) - .Distinct() - .ToList(); - } - private (List, List) HandlePermissionSystemOnStartup(PermissionsFile permissionsFile) { List newPermissions = []; @@ -805,14 +794,14 @@ public class PermissionService : BaseService, IPermissionService List rolesList = []; List? roles = permissionsFile.PermissionInfos? - .Where(x => x.RolePermissionModuleOperations != null)? - .SelectMany(x => x.RolePermissionModuleOperations!)? - .Where(x => x.Operations != null)? - .SelectMany(y => y.Operations!)? - .Where(z => z.Roles != null)? - .SelectMany(z => z.Roles!)? - .Where(z => z != null)? - .Distinct()? + .Where(x => x.RolePermissionModuleOperations != null) + .SelectMany(x => x.RolePermissionModuleOperations!) + .Where(x => x.Operations != null) + .SelectMany(y => y.Operations!) + .Where(z => z.Roles != null) + .SelectMany(z => z.Roles!) + .Where(z => z != null) + .Distinct() .ToList(); if (roles != null && roles.Count > 0) @@ -936,7 +925,7 @@ public class PermissionService : BaseService, IPermissionService var modulesNames = GetModulesNamesFromPermissionInfo(permissionInfo); if (modulesNames != null && modulesNames.Count > 0) { - List permissionModules = allPermissionModules.Where(x => modulesNames.Contains(x.Name)).ToList() ?? []; + List permissionModules = allPermissionModules.Where(x => modulesNames.Contains(x.Name))?.ToList() ?? []; (permissionSystemModuleList, newPermissions) = this.HandlePermissionSystemModuleOnStartup(permissionsFile, permissionSystems, permissionModules, permissionInfo); } } @@ -1114,7 +1103,7 @@ public class PermissionService : BaseService, IPermissionService .FirstOrDefault(x => x.PermissionOperation.Name == operationInfo.Operation); if (permissionSystemModuleOperation != null && operationInfo.Roles != null && operationInfo.Roles.Count > 0) { - var roles = allRoles.Where(x => operationInfo.Roles.Contains(x.Name)).ToList(); + var roles = allRoles.Where(x => operationInfo.Roles.Contains(x.Name))?.ToList() ?? []; if (roles != null && roles.Count > 0) { foreach (var roleName in operationInfo.Roles) @@ -1188,7 +1177,7 @@ public class PermissionService : BaseService, IPermissionService { // Get all PermissionSystemModuleOperations by System.Name List allPermissionSystemModuleOperationsBySystem = allPermissionSystemModuleOperations - .Where(x => x.PermissionSystemModule.PermissionSystem.Name == permissionInfo.System).ToList(); + .Where(x => x.PermissionSystemModule.PermissionSystem.Name == permissionInfo.System)?.ToList() ?? []; if (allPermissionSystemModuleOperationsBySystem != null && allPermissionSystemModuleOperationsBySystem.Count > 0) { -- 2.49.1 From 68387c558c2822be81c3392b5d5e847c85b87f25 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sat, 17 May 2025 23:18:23 +0200 Subject: [PATCH 18/28] Fixing issues - 2 --- MainProject/Services/PermissionService.cs | 25 ++++++++++------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/MainProject/Services/PermissionService.cs b/MainProject/Services/PermissionService.cs index ea0bf62..e4485d8 100644 --- a/MainProject/Services/PermissionService.cs +++ b/MainProject/Services/PermissionService.cs @@ -653,7 +653,7 @@ public class PermissionService : BaseService, IPermissionService private static List? GetSystemNamesFromFile(PermissionsFile permissionsFile) { - return permissionsFile?.PermissionInfos?.Where(x => x.System != null).Select(x => x.System)?.ToList(); + return permissionsFile?.PermissionInfos?.Select(x => x.System)?.ToList(); } private static List? GetModulesNamesFromFile(PermissionsFile permissionsFile) @@ -843,12 +843,9 @@ public class PermissionService : BaseService, IPermissionService throw new CreateException($"An error occurred while saving the role for transaction ID {transaction.TransactionId}.", exception); } - Logger.Info($"Added new Role => {role?.Name}"); - } - if (role != null) - { - rolesList.Add(role); + Logger.Info($"Added new Role => {role.Name}"); } + rolesList.Add(role); } return rolesList; @@ -862,10 +859,10 @@ public class PermissionService : BaseService, IPermissionService foreach (var permissionModule in permissionModules) { PermissionSystemModule? permissionSystemModule = this.GetPermissionSystemModulesQueryable()? - .Where(x => + .FirstOrDefault(x => x.PermissionSystemId == permissionSystem!.Id && x.PermissionModuleId == permissionModule.Id - )?.FirstOrDefault(); + ); if (permissionSystemModule == null) { permissionSystemModule = this.CreatePermissionSystemModuleAsync(permissionSystem!, permissionModule, true).Result; @@ -898,7 +895,7 @@ public class PermissionService : BaseService, IPermissionService if (modules != null && modules.Count > 0) { List permissionModules = allPermissionModules.Where(x => modules.Contains(x.Name)).ToList(); - if (permissionModules != null && permissionModules.Count > 0) + if (permissionModules.Count > 0) { (permissionSystemModuleList, newPermissions) = this.HandlePermissionSystemModulesOnStartup(permissionSystem, permissionModules); } @@ -925,7 +922,7 @@ public class PermissionService : BaseService, IPermissionService var modulesNames = GetModulesNamesFromPermissionInfo(permissionInfo); if (modulesNames != null && modulesNames.Count > 0) { - List permissionModules = allPermissionModules.Where(x => modulesNames.Contains(x.Name))?.ToList() ?? []; + List permissionModules = allPermissionModules.Where(x => modulesNames.Contains(x.Name)).ToList(); (permissionSystemModuleList, newPermissions) = this.HandlePermissionSystemModuleOnStartup(permissionsFile, permissionSystems, permissionModules, permissionInfo); } } @@ -1021,7 +1018,7 @@ public class PermissionService : BaseService, IPermissionService List permissionSystemModulesList = permissionSystemModules .Where(x => x.PermissionSystem.Name == permissionInfo.System).ToList(); - if (permissionSystemModulesList != null && permissionSystemModulesList.Count > 0) + if (permissionSystemModulesList.Count > 0) { (tmpPermissionSystemModuleOperationList, tmpPermissions) = this.HandlePermissionSystemModuleOperationOnStartup ( @@ -1058,7 +1055,7 @@ public class PermissionService : BaseService, IPermissionService List? allPermissionSystemModuleOperationsBySystemModule = allPermissionSystemModuleOperationsBySystem .Where(x => x.PermissionSystemModule.PermissionModule.Name == rolePermissionModuleOperation.Module) .ToList(); - if (allPermissionSystemModuleOperationsBySystemModule != null && allPermissionSystemModuleOperationsBySystemModule.Count > 0) + if (allPermissionSystemModuleOperationsBySystemModule.Count > 0) { var operationsNames = rolePermissionModuleOperation.Operations?.Select(x => x.Operation).ToList(); if (operationsNames != null && operationsNames.Count > 0) @@ -1103,8 +1100,8 @@ public class PermissionService : BaseService, IPermissionService .FirstOrDefault(x => x.PermissionOperation.Name == operationInfo.Operation); if (permissionSystemModuleOperation != null && operationInfo.Roles != null && operationInfo.Roles.Count > 0) { - var roles = allRoles.Where(x => operationInfo.Roles.Contains(x.Name))?.ToList() ?? []; - if (roles != null && roles.Count > 0) + var roles = allRoles.Where(x => operationInfo.Roles.Contains(x.Name)).ToList(); + if (roles.Count > 0) { foreach (var roleName in operationInfo.Roles) { -- 2.49.1 From 2ee44822c24d134376fb50d28414ec60ed166cc5 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sat, 17 May 2025 23:41:35 +0200 Subject: [PATCH 19/28] Fixing issues - 3 --- MainProject/Services/PermissionService.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/MainProject/Services/PermissionService.cs b/MainProject/Services/PermissionService.cs index e4485d8..7a305a7 100644 --- a/MainProject/Services/PermissionService.cs +++ b/MainProject/Services/PermissionService.cs @@ -653,7 +653,7 @@ public class PermissionService : BaseService, IPermissionService private static List? GetSystemNamesFromFile(PermissionsFile permissionsFile) { - return permissionsFile?.PermissionInfos?.Select(x => x.System)?.ToList(); + return permissionsFile?.PermissionInfos?.Select(x => x.System).ToList(); } private static List? GetModulesNamesFromFile(PermissionsFile permissionsFile) @@ -1174,9 +1174,9 @@ public class PermissionService : BaseService, IPermissionService { // Get all PermissionSystemModuleOperations by System.Name List allPermissionSystemModuleOperationsBySystem = allPermissionSystemModuleOperations - .Where(x => x.PermissionSystemModule.PermissionSystem.Name == permissionInfo.System)?.ToList() ?? []; + .Where(x => x.PermissionSystemModule.PermissionSystem.Name == permissionInfo.System).ToList(); - if (allPermissionSystemModuleOperationsBySystem != null && allPermissionSystemModuleOperationsBySystem.Count > 0) + if (allPermissionSystemModuleOperationsBySystem.Count > 0) { (tmpRolePermissionSystemModuleOperationList, tmpPermissions) = this.HandleRolePermissionSystemModuleOperationOnStartup ( -- 2.49.1 From c5c6806a759d03987048a8c291674e3cdca97e34 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sat, 17 May 2025 23:52:14 +0200 Subject: [PATCH 20/28] Fixing issues - 4 --- MainProject/Utils/ProgramUtils.cs | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/MainProject/Utils/ProgramUtils.cs b/MainProject/Utils/ProgramUtils.cs index 52b1b33..eaa8c37 100644 --- a/MainProject/Utils/ProgramUtils.cs +++ b/MainProject/Utils/ProgramUtils.cs @@ -275,26 +275,21 @@ public static class ProgramUtils public static void CreatePermissions(ref WebApplication app) { Logger.Info("[ProgramUtils][CreatePermissions] Adding permissions..."); - using (var scope = app.Services.CreateScope()) + using var scope = app.Services.CreateScope(); + Func permissionService = scope.ServiceProvider.GetRequiredService; + var isValidThread = Task.Run(() => permissionService!.Invoke()?.CreatePermissionsOnStartupAsync()); + if (isValidThread.Result != null) { - Func permissionService = scope.ServiceProvider.GetRequiredService; - if (permissionService != null) + foreach (var result in isValidThread.Result) { - var isValidThread = Task.Run(() => permissionService!.Invoke()?.CreatePermissionsOnStartupAsync()); - if (isValidThread.Result != null) - { - foreach (var result in isValidThread.Result) - { - var currentResult = String.IsNullOrEmpty(result) ? "No permission tracked" : result; - Logger.Info($"[ProgramUtils][CreatePermissions] => {currentResult}"); - } - } - else - { - Logger.Error("[ProgramUtils][CreatePermissions] Something went wrong"); - } + var currentResult = String.IsNullOrEmpty(result) ? "No permission tracked" : result; + Logger.Info($"[ProgramUtils][CreatePermissions] => {currentResult}"); } } + else + { + Logger.Error("[ProgramUtils][CreatePermissions] Something went wrong"); + } } } \ No newline at end of file -- 2.49.1 From 6d7dc432d8a2e86ca1fb44120b504c5ef33c02d0 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sun, 18 May 2025 00:25:52 +0200 Subject: [PATCH 21/28] Reducing cognitive complexity --- MainProject/Services/PermissionService.cs | 40 +++++++++++++++++------ 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/MainProject/Services/PermissionService.cs b/MainProject/Services/PermissionService.cs index 7a305a7..af81acd 100644 --- a/MainProject/Services/PermissionService.cs +++ b/MainProject/Services/PermissionService.cs @@ -1103,16 +1103,10 @@ public class PermissionService : BaseService, IPermissionService var roles = allRoles.Where(x => operationInfo.Roles.Contains(x.Name)).ToList(); if (roles.Count > 0) { - foreach (var roleName in operationInfo.Roles) - { - (tmpRolePermissionSystemModuleOperationList, tmpPermissions) = this.HandleRolePermissionSystemModuleOperationOnStartup - ( - roles, roleName, permissionSystemModuleOperation - ); - newPermissions.AddRange(tmpPermissions); - rolePermissionSystemModuleOperationList.AddRange(tmpRolePermissionSystemModuleOperationList); - } - + (tmpRolePermissionSystemModuleOperationList, tmpPermissions) = this.HandleRolePermissionSystemModuleOperationOnStartup + ( + roles, permissionSystemModuleOperation, operationInfo + ); } } } @@ -1121,6 +1115,32 @@ public class PermissionService : BaseService, IPermissionService return (rolePermissionSystemModuleOperationList, newPermissions); } + private (List, List) HandleRolePermissionSystemModuleOperationOnStartup + ( + List roles, PermissionSystemModuleOperation permissionSystemModuleOperation, OperationInfo operationInfo + ) + { + List newPermissions = []; + List tmpPermissions; + List rolePermissionSystemModuleOperationList = []; + List tmpRolePermissionSystemModuleOperationList; + + if (operationInfo?.Roles != null) + { + foreach (var roleName in operationInfo.Roles) + { + (tmpRolePermissionSystemModuleOperationList, tmpPermissions) = this.HandleRolePermissionSystemModuleOperationOnStartup + ( + roles, roleName, permissionSystemModuleOperation + ); + newPermissions.AddRange(tmpPermissions); + rolePermissionSystemModuleOperationList.AddRange(tmpRolePermissionSystemModuleOperationList); + } + } + + return (rolePermissionSystemModuleOperationList, newPermissions); + } + private (List, List) HandleRolePermissionSystemModuleOperationOnStartup ( List roles, string roleName, PermissionSystemModuleOperation permissionSystemModuleOperation -- 2.49.1 From 0f73560cd91c791ee6bf9deed967b66b0f4d08ba Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sun, 18 May 2025 23:23:24 +0200 Subject: [PATCH 22/28] Adding tests --- MainProject.Tests/Config/permissions.json | 32 +++++++++++ MainProject.Tests/Utils/FileUtils_Tests.cs | 66 ++++++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 MainProject.Tests/Config/permissions.json create mode 100644 MainProject.Tests/Utils/FileUtils_Tests.cs diff --git a/MainProject.Tests/Config/permissions.json b/MainProject.Tests/Config/permissions.json new file mode 100644 index 0000000..aeabb85 --- /dev/null +++ b/MainProject.Tests/Config/permissions.json @@ -0,0 +1,32 @@ +{ + "PermissionInfos": [ + { + "System": "base", + "RolePermissionModuleOperations": [ + { + "Module": "roles", + "Operations": [ + { "Operation": "create", "Roles": [] }, + { "Operation": "read", "Roles": [] }, + { "Operation": "update", "Roles": [] }, + { "Operation": "delete", "Roles": [] }, + { "Operation": "list", "Roles": [] }, + { "Operation": "use", "Roles": [] } + ] + }, + { + "Module": "users", + "Operations": [ + { "Operation": "create", "Roles": [] }, + { "Operation": "read", "Roles": [] }, + { "Operation": "update", "Roles": [] }, + { "Operation": "delete", "Roles": [] }, + { "Operation": "list", "Roles": [] }, + { "Operation": "use", "Roles": [] } + ] + } + ] + } + + ] +} \ No newline at end of file diff --git a/MainProject.Tests/Utils/FileUtils_Tests.cs b/MainProject.Tests/Utils/FileUtils_Tests.cs new file mode 100644 index 0000000..a689650 --- /dev/null +++ b/MainProject.Tests/Utils/FileUtils_Tests.cs @@ -0,0 +1,66 @@ +using BasicDotnetTemplate.MainProject.Utils; +using BasicDotnetTemplate.MainProject.Models.Common; + + +namespace BasicDotnetTemplate.MainProject.Tests; + +[TestClass] +public static class FileUtils_Tests +{ + [TestMethod] + public static void ConvertFileToObject_NoFilePath() + { + try + { + try + { + PermissionsFile? permissionsFile = FileUtils.ConvertFileToObject(String.Empty); + Assert.Fail($"Expected exception instead of response: {permissionsFile}"); + } + catch (ArgumentException argumentException) + { + Assert.IsInstanceOfType(argumentException, typeof(ArgumentException)); + } + catch (Exception exception) + { + Assert.Fail($"An exception was thrown: {exception}"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public static void ConvertFileToObject_NoFile() + { + try + { + try + { + PermissionsFile? permissionsFile = FileUtils.ConvertFileToObject(System.AppDomain.CurrentDomain.BaseDirectory + "Config/no-permissions.json"); + Assert.Fail($"Expected exception instead of response: {permissionsFile}"); + } + catch (FileNotFoundException fileNotFoundException) + { + Assert.IsInstanceOfType(fileNotFoundException, typeof(FileNotFoundException)); + } + catch (Exception exception) + { + Assert.Fail($"An exception was thrown: {exception}"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + +} + + + + -- 2.49.1 From ec0847e95c2cf3921b6c4e518bc39e83827b7d81 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Sun, 18 May 2025 23:44:34 +0200 Subject: [PATCH 23/28] Packages upgrade --- MainProject/MainProject.csproj | 50 +++++++++++++++++----------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/MainProject/MainProject.csproj b/MainProject/MainProject.csproj index d34f99f..78530da 100644 --- a/MainProject/MainProject.csproj +++ b/MainProject/MainProject.csproj @@ -10,41 +10,41 @@ - + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - - - + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - + + + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - + + + + - - - - - - - - - - - + + + + + + + + + + + -- 2.49.1 From 58b7e75e779c91a3428e824407c69bf0bcb4a997 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Mon, 19 May 2025 00:03:27 +0200 Subject: [PATCH 24/28] Adding tests --- MainProject.Tests/Utils/FileUtils_Tests.cs | 55 ++++++++-------------- 1 file changed, 20 insertions(+), 35 deletions(-) diff --git a/MainProject.Tests/Utils/FileUtils_Tests.cs b/MainProject.Tests/Utils/FileUtils_Tests.cs index a689650..18001a5 100644 --- a/MainProject.Tests/Utils/FileUtils_Tests.cs +++ b/MainProject.Tests/Utils/FileUtils_Tests.cs @@ -5,60 +5,45 @@ using BasicDotnetTemplate.MainProject.Models.Common; namespace BasicDotnetTemplate.MainProject.Tests; [TestClass] -public static class FileUtils_Tests +public class FileUtils_Tests { [TestMethod] - public static void ConvertFileToObject_NoFilePath() + public void ConvertFileToObject_NoFilePath() { try { - try - { - PermissionsFile? permissionsFile = FileUtils.ConvertFileToObject(String.Empty); - Assert.Fail($"Expected exception instead of response: {permissionsFile}"); - } - catch (ArgumentException argumentException) - { - Assert.IsInstanceOfType(argumentException, typeof(ArgumentException)); - } - catch (Exception exception) - { - Assert.Fail($"An exception was thrown: {exception}"); - } + PermissionsFile? permissionsFile = FileUtils.ConvertFileToObject(String.Empty); + Assert.Fail($"Expected exception instead of response: {permissionsFile}"); } - catch (Exception ex) + catch (ArgumentException argumentException) { - Console.WriteLine(ex.InnerException); - Assert.Fail($"An exception was thrown: {ex}"); + Assert.IsInstanceOfType(argumentException, typeof(ArgumentException)); + } + catch (Exception exception) + { + Assert.Fail($"An exception was thrown: {exception}"); } } [TestMethod] - public static void ConvertFileToObject_NoFile() + public void ConvertFileToObject_NoFile() { try { - try - { - PermissionsFile? permissionsFile = FileUtils.ConvertFileToObject(System.AppDomain.CurrentDomain.BaseDirectory + "Config/no-permissions.json"); - Assert.Fail($"Expected exception instead of response: {permissionsFile}"); - } - catch (FileNotFoundException fileNotFoundException) - { - Assert.IsInstanceOfType(fileNotFoundException, typeof(FileNotFoundException)); - } - catch (Exception exception) - { - Assert.Fail($"An exception was thrown: {exception}"); - } + PermissionsFile? permissionsFile = FileUtils.ConvertFileToObject(System.AppDomain.CurrentDomain.BaseDirectory + "Config/no-permissions.json"); + Assert.Fail($"Expected exception instead of response: {permissionsFile}"); } - catch (Exception ex) + catch (FileNotFoundException fileNotFoundException) { - Console.WriteLine(ex.InnerException); - Assert.Fail($"An exception was thrown: {ex}"); + Assert.IsInstanceOfType(fileNotFoundException, typeof(FileNotFoundException)); + } + catch (Exception exception) + { + Assert.Fail($"An exception was thrown: {exception}"); } } + } -- 2.49.1 From 0cc6b0265c847feb4de72f4917c62b8f50cee247 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Mon, 19 May 2025 00:04:17 +0200 Subject: [PATCH 25/28] Updated filename --- MainProject/Utils/{FileUtils.cs.cs => FileUtils.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename MainProject/Utils/{FileUtils.cs.cs => FileUtils.cs} (100%) diff --git a/MainProject/Utils/FileUtils.cs.cs b/MainProject/Utils/FileUtils.cs similarity index 100% rename from MainProject/Utils/FileUtils.cs.cs rename to MainProject/Utils/FileUtils.cs -- 2.49.1 From f65dfab41484f73d5688dd1d71425efcaf4d04dd Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Mon, 19 May 2025 00:24:50 +0200 Subject: [PATCH 26/28] Adding tests for FileUtils --- .../Config/invalid-permissions.json | 31 +++++++++++++++++++ MainProject.Tests/MainProject.Tests.csproj | 5 ++- MainProject.Tests/Utils/FileUtils_Tests.cs | 31 +++++++++++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 MainProject.Tests/Config/invalid-permissions.json diff --git a/MainProject.Tests/Config/invalid-permissions.json b/MainProject.Tests/Config/invalid-permissions.json new file mode 100644 index 0000000..6ba8ce1 --- /dev/null +++ b/MainProject.Tests/Config/invalid-permissions.json @@ -0,0 +1,31 @@ +{ + "PermissionInfos": [ + { + "System": "base", + "RolePermissionModuleOperations": [ + { + "Module": "roles", + "Operations": [ + { "Operation": "create", "Roles": [] }, + { "Operation": "read", "Roles": [] }, + { "Operation": "update", "Roles": [] }, + { "Operation": "delete", "Roles": [] }, + { "Operation": "list", "Roles": [] }, + { "Operation": "use", "Roles": [] } + ] + }, + { + "Module": "users", + "Operations": [ + { "Operation": "create", "Roles": [] }, + { "Operation": "read", "Roles": [] }, + { "Operation": "update", "Roles": [] }, + { "Operation": "delete", "Roles": [] }, + { "Operation": "list", "Roles": [] }, + { "Operation": "use", "Roles": [] } + ] + } + ] + + ] +} \ No newline at end of file diff --git a/MainProject.Tests/MainProject.Tests.csproj b/MainProject.Tests/MainProject.Tests.csproj index a899faa..45f0343 100644 --- a/MainProject.Tests/MainProject.Tests.csproj +++ b/MainProject.Tests/MainProject.Tests.csproj @@ -29,6 +29,9 @@ - + + + + diff --git a/MainProject.Tests/Utils/FileUtils_Tests.cs b/MainProject.Tests/Utils/FileUtils_Tests.cs index 18001a5..cef4c33 100644 --- a/MainProject.Tests/Utils/FileUtils_Tests.cs +++ b/MainProject.Tests/Utils/FileUtils_Tests.cs @@ -43,6 +43,37 @@ public class FileUtils_Tests } } + [TestMethod] + public void ConvertFileToObject() + { + try + { + PermissionsFile? permissionsFile = FileUtils.ConvertFileToObject(System.AppDomain.CurrentDomain.BaseDirectory + "Config/permissions.json"); + Assert.IsTrue(permissionsFile != null); + } + catch (Exception exception) + { + Assert.Fail($"An exception was thrown: {exception}"); + } + } + + [TestMethod] + public void ConvertFileToObject_InvalidOperationException() + { + try + { + PermissionsFile? permissionsFile = FileUtils.ConvertFileToObject(System.AppDomain.CurrentDomain.BaseDirectory + "Config/invalid-permissions.json"); + Assert.Fail($"Expected exception instead of response: {permissionsFile}"); + } + catch (InvalidOperationException invalidOperationException) + { + Assert.IsInstanceOfType(invalidOperationException, typeof(InvalidOperationException)); + } + catch (Exception exception) + { + Assert.Fail($"An exception was thrown: {exception}"); + } + } } -- 2.49.1 From 49ac876a66e3ce7ab9c5141dfc87d499339b338d Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Tue, 27 May 2025 23:25:41 +0200 Subject: [PATCH 27/28] Adding tests for CreatePermissionsOnStartupAsync_Success --- MainProject.Tests/Config/permissions.json | 3 +- .../Services/PermissionService_Tests.cs | 103 +++++++++++++++--- 2 files changed, 88 insertions(+), 18 deletions(-) diff --git a/MainProject.Tests/Config/permissions.json b/MainProject.Tests/Config/permissions.json index aeabb85..b1a82dd 100644 --- a/MainProject.Tests/Config/permissions.json +++ b/MainProject.Tests/Config/permissions.json @@ -21,8 +21,7 @@ { "Operation": "read", "Roles": [] }, { "Operation": "update", "Roles": [] }, { "Operation": "delete", "Roles": [] }, - { "Operation": "list", "Roles": [] }, - { "Operation": "use", "Roles": [] } + { "Operation": "list", "Roles": [] } ] } ] diff --git a/MainProject.Tests/Services/PermissionService_Tests.cs b/MainProject.Tests/Services/PermissionService_Tests.cs index 413572b..591d653 100644 --- a/MainProject.Tests/Services/PermissionService_Tests.cs +++ b/MainProject.Tests/Services/PermissionService_Tests.cs @@ -3,6 +3,7 @@ using BasicDotnetTemplate.MainProject.Models.Api.Data.User; using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; using Newtonsoft.Json; using BasicDotnetTemplate.MainProject.Models.Api.Common.Exceptions; +using Microsoft.AspNetCore.Mvc.Diagnostics; namespace BasicDotnetTemplate.MainProject.Tests; @@ -82,7 +83,7 @@ public class PermissionService_Tests } } -#region "PermissionSystem" + #region "PermissionSystem" [TestMethod] public async Task GetPermissionSystemByGuidAsync_Null() @@ -250,10 +251,10 @@ public class PermissionService_Tests } } -#endregion - + #endregion -#region "PermissionModule" + + #region "PermissionModule" [TestMethod] public async Task GetPermissionModuleByGuidAsync_Null() @@ -423,10 +424,10 @@ public class PermissionService_Tests } } -#endregion + #endregion -#region "PermissionOperation" + #region "PermissionOperation" [TestMethod] public async Task GetPermissionOperationByGuidAsync_Null() @@ -574,10 +575,10 @@ public class PermissionService_Tests } } -#endregion + #endregion -#region "PermissionSystemModule" + #region "PermissionSystemModule" [TestMethod] public async Task GetPermissionSystemModuleByGuidAsync_Null() @@ -694,10 +695,10 @@ public class PermissionService_Tests } } -#endregion + #endregion -#region "PermissionSystemModuleOperation" + #region "PermissionSystemModuleOperation" [TestMethod] public async Task GetPermissionSystemModuleOperationByGuidAsync_Null() @@ -814,10 +815,10 @@ public class PermissionService_Tests } } -#endregion + #endregion -#region "RolePermissionSystemModuleOperation" + #region "RolePermissionSystemModuleOperation" [TestMethod] public async Task GetRolePermissionSystemModuleOperationByGuidAsync_Null() @@ -887,7 +888,7 @@ public class PermissionService_Tests IsNotEditable = expectedUser.Role?.IsNotEditable ?? false, Guid = expectedUser.Role?.Guid ?? String.Empty }; - + var permission = await exceptionPermissionService.CreateRolePermissionSystemModuleOperationAsync(role, _permissionSystemModuleOperation, true); Assert.Fail($"Expected exception instead of response: {permission?.Guid}"); } @@ -950,11 +951,11 @@ public class PermissionService_Tests } } -#endregion + #endregion -#region "DeletePermissions" + #region "DeletePermissions" [TestMethod] public async Task DeleteRolePermissionSystemModuleOperationAsync() @@ -1052,8 +1053,78 @@ public class PermissionService_Tests } } -#endregion + #endregion + + #region "CreatePermissions" + + [TestMethod] + public void CreatePermissionsOnStartupAsync_Success() + { + try + { + + if (_permissionService != null) + { + List permissions = _permissionService.CreatePermissionsOnStartupAsync(); + Assert.IsFalse(permissions == null); + List cleanedPermissions = new(); + + foreach (var permission in permissions) + { + cleanedPermissions.Add(permission + .Replace("Added new PermissionSystem => ", "") + .Replace("Added new PermissionModule => ", "") + .Replace("Added new PermissionOperation => ", "") + .Replace("Added new PermissionSystemModule => ", "") + .Replace("Added new PermissionSystemModuleOperation => ", "") + .Replace("Added new RolePermissionSystemModuleOperation => ", "") + ); + } + Assert.IsTrue(cleanedPermissions.Contains("base")); + + Assert.IsTrue(cleanedPermissions.Contains("roles")); + Assert.IsTrue(cleanedPermissions.Contains("users")); + + Assert.IsTrue(cleanedPermissions.Contains("create")); + Assert.IsTrue(cleanedPermissions.Contains("read")); + Assert.IsTrue(cleanedPermissions.Contains("update")); + Assert.IsTrue(cleanedPermissions.Contains("delete")); + Assert.IsTrue(cleanedPermissions.Contains("list")); + Assert.IsTrue(cleanedPermissions.Contains("use")); + + Assert.IsTrue(cleanedPermissions.Contains("base.roles")); + Assert.IsTrue(cleanedPermissions.Contains("base.users")); + + Assert.IsTrue(cleanedPermissions.Contains("base.roles.create")); + Assert.IsTrue(cleanedPermissions.Contains("base.roles.read")); + Assert.IsTrue(cleanedPermissions.Contains("base.roles.update")); + Assert.IsTrue(cleanedPermissions.Contains("base.roles.delete")); + Assert.IsTrue(cleanedPermissions.Contains("base.roles.list")); + Assert.IsTrue(cleanedPermissions.Contains("base.roles.use")); + + Assert.IsTrue(cleanedPermissions.Contains("base.users.create")); + Assert.IsTrue(cleanedPermissions.Contains("base.users.read")); + Assert.IsTrue(cleanedPermissions.Contains("base.users.update")); + Assert.IsTrue(cleanedPermissions.Contains("base.users.delete")); + Assert.IsTrue(cleanedPermissions.Contains("base.users.list")); + + Assert.IsFalse(cleanedPermissions.Contains("base.users.use")); + + } + else + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + #endregion } -- 2.49.1 From 7aa438f6c1098f8303deda23f750e789dc311e34 Mon Sep 17 00:00:00 2001 From: csimonapastore Date: Tue, 27 May 2025 23:52:48 +0200 Subject: [PATCH 28/28] Fixed error in PermissionService --- MainProject.Tests/Config/permissions.json | 6 +++--- .../Services/PermissionService_Tests.cs | 4 ++++ MainProject/MainProject.csproj | 14 +++++++------- MainProject/Services/PermissionService.cs | 2 ++ 4 files changed, 16 insertions(+), 10 deletions(-) diff --git a/MainProject.Tests/Config/permissions.json b/MainProject.Tests/Config/permissions.json index b1a82dd..04a7e8e 100644 --- a/MainProject.Tests/Config/permissions.json +++ b/MainProject.Tests/Config/permissions.json @@ -6,10 +6,10 @@ { "Module": "roles", "Operations": [ - { "Operation": "create", "Roles": [] }, + { "Operation": "create", "Roles": ["Admin"] }, { "Operation": "read", "Roles": [] }, - { "Operation": "update", "Roles": [] }, - { "Operation": "delete", "Roles": [] }, + { "Operation": "update", "Roles": ["Admin"] }, + { "Operation": "delete", "Roles": ["Admin"] }, { "Operation": "list", "Roles": [] }, { "Operation": "use", "Roles": [] } ] diff --git a/MainProject.Tests/Services/PermissionService_Tests.cs b/MainProject.Tests/Services/PermissionService_Tests.cs index 591d653..a465849 100644 --- a/MainProject.Tests/Services/PermissionService_Tests.cs +++ b/MainProject.Tests/Services/PermissionService_Tests.cs @@ -1103,6 +1103,10 @@ public class PermissionService_Tests Assert.IsTrue(cleanedPermissions.Contains("base.roles.list")); Assert.IsTrue(cleanedPermissions.Contains("base.roles.use")); + Assert.IsTrue(cleanedPermissions.Contains("base.roles.create for role Admin")); + Assert.IsTrue(cleanedPermissions.Contains("base.roles.update for role Admin")); + Assert.IsTrue(cleanedPermissions.Contains("base.roles.delete for role Admin")); + Assert.IsTrue(cleanedPermissions.Contains("base.users.create")); Assert.IsTrue(cleanedPermissions.Contains("base.users.read")); Assert.IsTrue(cleanedPermissions.Contains("base.users.update")); diff --git a/MainProject/MainProject.csproj b/MainProject/MainProject.csproj index 78530da..24c681d 100644 --- a/MainProject/MainProject.csproj +++ b/MainProject/MainProject.csproj @@ -30,21 +30,21 @@ all - + - - + + - - - - + + + + diff --git a/MainProject/Services/PermissionService.cs b/MainProject/Services/PermissionService.cs index af81acd..8ab2923 100644 --- a/MainProject/Services/PermissionService.cs +++ b/MainProject/Services/PermissionService.cs @@ -1107,6 +1107,8 @@ public class PermissionService : BaseService, IPermissionService ( roles, permissionSystemModuleOperation, operationInfo ); + newPermissions.AddRange(tmpPermissions); + rolePermissionSystemModuleOperationList.AddRange(tmpRolePermissionSystemModuleOperationList); } } } -- 2.49.1