From 79549bea050cc71c5602de5323d0950ef88f03a1 Mon Sep 17 00:00:00 2001 From: Caterina Simona Pastore <45461004+csimonapastore@users.noreply.github.com> Date: Wed, 28 May 2025 00:10:38 +0200 Subject: [PATCH] Sprint 5 (#28) --- .../Config/invalid-permissions.json | 31 + MainProject.Tests/Config/permissions.json | 31 + .../Controllers/RoleController_Tests.cs | 999 +++++++++++++ .../Controllers/RootController_Tests.cs | 1 - .../Controllers/UserController_Tests.cs | 8 +- .../Controllers/VersionController_Tests.cs | 3 - MainProject.Tests/MainProject.Tests.csproj | 5 +- .../Response/Role/GetRoleResponse_Tests.cs | 102 ++ MainProject.Tests/Program_Tests.cs | 1 - .../Services/PermissionService_Tests.cs | 1135 +++++++++++++++ .../Services/RoleService_Tests.cs | 146 +- .../Services/UserService_Tests.cs | 48 + .../TestsUtils/ExceptionSqlServerContext.cs | 24 + MainProject.Tests/TestsUtils/TestUtils.cs | 53 +- MainProject.Tests/Utils/CryptoUtils_Tests.cs | 2 - MainProject.Tests/Utils/FileUtils_Tests.cs | 82 ++ MainProject.Tests/Utils/ProgramUtils_Tests.cs | 1 - MainProject/Config/permissions.json | 32 + MainProject/Controllers/AuthController.cs | 2 +- MainProject/Controllers/BaseController.cs | 1 + MainProject/Controllers/RoleController.cs | 227 +++ MainProject/Controllers/UserController.cs | 4 +- MainProject/Core/Database/SqlServerContext.cs | 54 +- .../Middlewares/AutoMapperConfiguration.cs | 2 + MainProject/MainProject.csproj | 50 +- ...183010_AddingPermissionsTables.Designer.cs | 543 +++++++ .../20250426183010_AddingPermissionsTables.cs | 283 ++++ .../SqlServerContextModelSnapshot.cs | 373 +++++ .../Api/Common/Exceptions/CreateException.cs | 11 + .../Api/Common/Exceptions/UpdateException.cs | 11 + MainProject/Models/Api/Common/Role/RoleDto.cs | 14 + .../Api/Request/Role/CreateRoleRequest.cs | 10 + .../Api/Response/Role/GetRoleResponse.cs | 8 + MainProject/Models/Common/OperationInfo.cs | 9 + MainProject/Models/Common/PermissionInfo.cs | 9 + MainProject/Models/Common/PermissionsFile.cs | 8 + .../Common/RolePermissionModuleOperation.cs | 9 + .../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/Models/Settings/AppSettings.cs | 2 +- .../Models/Settings/PermissionsSettings.cs | 8 + MainProject/Program.cs | 1 + MainProject/Services/PermissionService.cs | 1278 +++++++++++++++++ MainProject/Services/RoleService.cs | 45 +- MainProject/Services/UserService.cs | 9 +- MainProject/Utils/CommonDbMethodsUtils.cs | 32 + MainProject/Utils/FileUtils.cs | 42 + MainProject/Utils/ProgramUtils.cs | 21 + MainProject/appsettings.json | 3 + 53 files changed, 5781 insertions(+), 63 deletions(-) create mode 100644 MainProject.Tests/Config/invalid-permissions.json create mode 100644 MainProject.Tests/Config/permissions.json create mode 100644 MainProject.Tests/Controllers/RoleController_Tests.cs create mode 100644 MainProject.Tests/Models/Api/Response/Role/GetRoleResponse_Tests.cs create mode 100644 MainProject.Tests/Services/PermissionService_Tests.cs create mode 100644 MainProject.Tests/TestsUtils/ExceptionSqlServerContext.cs create mode 100644 MainProject.Tests/Utils/FileUtils_Tests.cs create mode 100644 MainProject/Config/permissions.json create mode 100644 MainProject/Controllers/RoleController.cs create mode 100644 MainProject/Migrations/20250426183010_AddingPermissionsTables.Designer.cs create mode 100644 MainProject/Migrations/20250426183010_AddingPermissionsTables.cs create mode 100644 MainProject/Models/Api/Common/Exceptions/CreateException.cs create mode 100644 MainProject/Models/Api/Common/Exceptions/UpdateException.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 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/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/Models/Settings/PermissionsSettings.cs create mode 100644 MainProject/Services/PermissionService.cs create mode 100644 MainProject/Utils/CommonDbMethodsUtils.cs create mode 100644 MainProject/Utils/FileUtils.cs 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/Config/permissions.json b/MainProject.Tests/Config/permissions.json new file mode 100644 index 0000000..04a7e8e --- /dev/null +++ b/MainProject.Tests/Config/permissions.json @@ -0,0 +1,31 @@ +{ + "PermissionInfos": [ + { + "System": "base", + "RolePermissionModuleOperations": [ + { + "Module": "roles", + "Operations": [ + { "Operation": "create", "Roles": ["Admin"] }, + { "Operation": "read", "Roles": [] }, + { "Operation": "update", "Roles": ["Admin"] }, + { "Operation": "delete", "Roles": ["Admin"] }, + { "Operation": "list", "Roles": [] }, + { "Operation": "use", "Roles": [] } + ] + }, + { + "Module": "users", + "Operations": [ + { "Operation": "create", "Roles": [] }, + { "Operation": "read", "Roles": [] }, + { "Operation": "update", "Roles": [] }, + { "Operation": "delete", "Roles": [] }, + { "Operation": "list", "Roles": [] } + ] + } + ] + } + + ] +} \ No newline at end of file diff --git a/MainProject.Tests/Controllers/RoleController_Tests.cs b/MainProject.Tests/Controllers/RoleController_Tests.cs new file mode 100644 index 0000000..5fcd784 --- /dev/null +++ b/MainProject.Tests/Controllers/RoleController_Tests.cs @@ -0,0 +1,999 @@ +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); + } + } + + #region "GET" + + [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"); + } + } + + #endregion + + #region "CREATE" + + [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"); + } + } + + #endregion + + #region "DELETE" + + [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"); + } + } + + #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_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() + { + 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.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 4dfd820..cc94f2b 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; @@ -43,7 +43,7 @@ public class UserControllerTests 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] @@ -100,7 +100,7 @@ public class UserControllerTests } [TestMethod] - public async Task GetUserByGuidAsync_AuthenticateRequestDataNull() + public async Task GetUserByGuidAsync_GuidIsEmpty() { if (_userController == null) { @@ -232,7 +232,7 @@ public class UserControllerTests } [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/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/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}"); + } + } + +} + + + + 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/PermissionService_Tests.cs b/MainProject.Tests/Services/PermissionService_Tests.cs new file mode 100644 index 0000000..a465849 --- /dev/null +++ b/MainProject.Tests/Services/PermissionService_Tests.cs @@ -0,0 +1,1135 @@ +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; +using Microsoft.AspNetCore.Mvc.Diagnostics; + + +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 + "-SYSTEM", + Enabled = false + }; + + private static PermissionModule _permissionModule = new PermissionModule() + { + Name = _name + "-MODULE", + Enabled = false + }; + + private static PermissionOperation _permissionOperation = new PermissionOperation() + { + Name = _name + "-OPERATION" + }; + + private static PermissionSystemModule _permissionSystemModule = new PermissionSystemModule() + { + PermissionSystem = _permissionSystem, + PermissionSystemId = 0, + PermissionModule = _permissionModule, + PermissionModuleId = 0, + Enabled = false + }; + + private static PermissionSystemModuleOperation _permissionSystemModuleOperation = new PermissionSystemModuleOperation() + { + PermissionSystemModule = _permissionSystemModule, + PermissionSystemModuleId = 0, + PermissionOperation = _permissionOperation, + PermissionOperationId = 0, + 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() + { + 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(_permissionSystem.Name, true); + Assert.IsInstanceOfType(permission, typeof(PermissionSystem)); + Assert.IsNotNull(permission); + Assert.IsTrue(permission.Name == _permissionSystem.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 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 + { + Assert.Fail($"PermissionService is null"); + } + } + catch (Exception ex) + { + Assert.Fail($"An exception was thrown: {ex}"); + } + } + + [TestMethod] + public async Task HandleEnabledPermissionSystemAsync() + { + try + { + var updated = await _permissionService.HandleEnabledPermissionSystemAsync(_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 + + + #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 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 + { + 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 + + + #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 + + + #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 permission = await exceptionPermissionService.CreatePermissionSystemModuleAsync(_permissionSystem, _permissionModule, 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 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 "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 permission = await exceptionPermissionService.CreatePermissionSystemModuleOperationAsync(_permissionSystemModule, _permissionOperation, 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 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 "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() + { + 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() + { + 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() + { + try + { + var deleted = await _permissionService.DeletePermissionSystemAsync(_permissionSystem); + Assert.IsTrue(deleted); + + } + catch (Exception ex) + { + Console.WriteLine(ex.InnerException); + 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}"); + } + } + + [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 + + + #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.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")); + 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 +} + + + diff --git a/MainProject.Tests/Services/RoleService_Tests.cs b/MainProject.Tests/Services/RoleService_Tests.cs index dfd172e..03cf382 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; @@ -62,7 +64,7 @@ public class RoleService_Tests } [TestMethod] - public async Task CreateRoleData() + public async Task CreateRoleAsync_Success() { try { @@ -93,6 +95,43 @@ 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)); + Assert.IsInstanceOfType(exception, typeof(CreateException)); + } + } + else + { + Assert.Fail($"RoleService is null"); + } + } + catch (Exception ex) + { + Assert.Fail($"An exception was thrown: {ex}"); + } + } + [TestMethod] public async Task CheckIfNameIsValid_NameCurrentRole() { @@ -261,6 +300,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..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; @@ -119,6 +120,53 @@ 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)); + Assert.IsInstanceOfType(exception, typeof(CreateException)); + } + } + 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/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 099777c..ab74ca0 100644 --- a/MainProject.Tests/TestsUtils/TestUtils.cs +++ b/MainProject.Tests/TestsUtils/TestUtils.cs @@ -64,11 +64,21 @@ public static class TestUtils return _appSettings.DatabaseSettings?.SqlServerConnectionString ?? String.Empty; } - public static SqlServerContext CreateInMemorySqlContext() + public static string GetFakeConnectionString() { - var options = new DbContextOptionsBuilder() + 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 DbContextOptions CreateInMemorySqlContextOptions() + { + 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(); @@ -79,8 +89,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 +97,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 +111,15 @@ public static class TestUtils return new UserService(httpContextAccessor.Object, configuration, sqlServerContext); } + public static UserService CreateUserServiceException() + { + var sqlServerContext = new ExceptionSqlServerContext(); + sqlServerContext.ThrowExceptionOnSave = true; + IConfiguration configuration = CreateConfiguration(); + var httpContextAccessor = new Mock(); + return new UserService(httpContextAccessor.Object, configuration, sqlServerContext); + } + public static JwtService CreateJwtService() { IConfiguration configuration = CreateConfiguration(); @@ -124,6 +139,32 @@ public static class TestUtils var httpContextAccessor = new Mock(); return new RoleService(httpContextAccessor.Object, configuration, sqlServerContext); } + + public static RoleService CreateRoleServiceException() + { + var sqlServerContext = new ExceptionSqlServerContext(); + sqlServerContext.ThrowExceptionOnSave = true; + IConfiguration configuration = CreateConfiguration(); + 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() + { + var sqlServerContext = new ExceptionSqlServerContext(); + sqlServerContext.ThrowExceptionOnSave = true; + IConfiguration configuration = CreateConfiguration(); + var httpContextAccessor = new Mock(); + return new PermissionService(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/FileUtils_Tests.cs b/MainProject.Tests/Utils/FileUtils_Tests.cs new file mode 100644 index 0000000..cef4c33 --- /dev/null +++ b/MainProject.Tests/Utils/FileUtils_Tests.cs @@ -0,0 +1,82 @@ +using BasicDotnetTemplate.MainProject.Utils; +using BasicDotnetTemplate.MainProject.Models.Common; + + +namespace BasicDotnetTemplate.MainProject.Tests; + +[TestClass] +public class FileUtils_Tests +{ + [TestMethod] + public void ConvertFileToObject_NoFilePath() + { + 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}"); + } + } + + [TestMethod] + public void ConvertFileToObject_NoFile() + { + 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}"); + } + } + + [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}"); + } + } + +} + + + + 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/Config/permissions.json b/MainProject/Config/permissions.json new file mode 100644 index 0000000..aeabb85 --- /dev/null +++ b/MainProject/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/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 new file mode 100644 index 0000000..5b369a1 --- /dev/null +++ b/MainProject/Controllers/RoleController.cs @@ -0,0 +1,227 @@ +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 = this._somethingWentWrong; + 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 = this._somethingWentWrong; + if (!String.IsNullOrEmpty(exception.Message)) + { + message += $". {exception.Message}"; + } + return InternalServerError(message); + } + + } + + [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 (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) + ) + { + 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 = this._somethingWentWrong; + 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 = this._somethingWentWrong; + if (!String.IsNullOrEmpty(exception.Message)) + { + message += $". {exception.Message}"; + } + return InternalServerError(message); + } + + } + + + } +} \ No newline at end of file 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}"; 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/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/MainProject.csproj b/MainProject/MainProject.csproj index d34f99f..24c681d 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 - - - - + + + + - - - - - - - - - - - + + + + + + + + + + + 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/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/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 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/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/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 new file mode 100644 index 0000000..8ab2923 --- /dev/null +++ b/MainProject/Services/PermissionService.cs @@ -0,0 +1,1278 @@ + +using System.Collections; +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; + +public interface IPermissionService +{ + Task GetPermissionSystemByGuidAsync(string guid); + Task GetPermissionSystemByNameAsync(string name); + Task HandleEnabledPermissionSystemAsync(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); + + 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() + { + 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 static PermissionOperation CreatePermissionOperationData(string name) + { + PermissionOperation permission = new() + { + CreationTime = DateTime.UtcNow, + Name = name, + IsDeleted = false, + Guid = Guid.NewGuid().ToString() + }; + + return permission; + } + + private static 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 static 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 static 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 static 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 static 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 HandleEnabledPermissionSystemAsync(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 + + + + #region "CreatePermissionOnStartup" + + private static List? GetSystemNamesFromFile(PermissionsFile permissionsFile) + { + return permissionsFile?.PermissionInfos?.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 (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}"); + } + 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()? + .FirstOrDefault(x => + x.PermissionSystemId == permissionSystem!.Id && + x.PermissionModuleId == permissionModule.Id + ); + 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.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.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.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.Count > 0) + { + (tmpRolePermissionSystemModuleOperationList, tmpPermissions) = this.HandleRolePermissionSystemModuleOperationOnStartup + ( + roles, permissionSystemModuleOperation, operationInfo + ); + newPermissions.AddRange(tmpPermissions); + rolePermissionSystemModuleOperationList.AddRange(tmpRolePermissionSystemModuleOperationList); + } + } + } + } + + 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 + ) + { + 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.Count > 0) + { + (tmpRolePermissionSystemModuleOperationList, tmpPermissions) = this.HandleRolePermissionSystemModuleOperationOnStartup + ( + allPermissionSystemModuleOperationsBySystem, + allRoles, + permissionInfo + ); + newPermissions.AddRange(tmpPermissions); + rolePermissionSystemModuleOperationList.AddRange(tmpRolePermissionSystemModuleOperationList); + } + } + } + } + + return (rolePermissionSystemModuleOperationList, newPermissions); + + } + + public List CreatePermissionsOnStartupAsync() + { + try + { + 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) + { + Logger.Error(exception, $"[PermissionService][CreatePermissionsOnStartupAsync]"); + throw new CreateException($"An error occurred while adding permissions during startup", exception); + } + + } + + + + #endregion + + + +} \ No newline at end of file diff --git a/MainProject/Services/RoleService.cs b/MainProject/Services/RoleService.cs index 96f127b..d10f0e4 100644 --- a/MainProject/Services/RoleService.cs +++ b/MainProject/Services/RoleService.cs @@ -1,9 +1,11 @@ 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; +using BasicDotnetTemplate.MainProject.Utils; namespace BasicDotnetTemplate.MainProject.Services; @@ -13,6 +15,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); } @@ -20,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); } @@ -107,7 +112,35 @@ public class RoleService : BaseService, IRoleService { await transaction.RollbackAsync(); Logger.Error(exception, $"[RoleService][CreateRoleAsync]"); - throw; + throw new CreateException($"An error occurred while saving the role for transaction ID {transaction.TransactionId}.", exception); + } + + return role; + } + + public async Task UpdateRoleAsync(CreateRoleRequestData data, Role role) + { + if (role.IsNotEditable) + return 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) + { + Logger.Error(exception, $"[RoleService][UpdateRoleAsync] | {transaction.TransactionId}"); + await transaction.RollbackAsync(); + 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 ba471ab..3fe1314 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; @@ -77,7 +78,6 @@ public class UserService : BaseService, IUserService if (user != null) { var encryptedPassword = user.PasswordHash; - Console.WriteLine(encryptedPassword); } return user; @@ -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(); @@ -119,7 +120,7 @@ public class UserService : BaseService, IUserService { await transaction.RollbackAsync(); Logger.Error(exception, $"[UserService][CreateUserAsync]"); - throw; + throw new CreateException($"An error occurred while creating the user for transaction ID {transaction.TransactionId}.", exception); } 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 b/MainProject/Utils/FileUtils.cs new file mode 100644 index 0000000..5c7be6e --- /dev/null +++ b/MainProject/Utils/FileUtils.cs @@ -0,0 +1,42 @@ +using System.Text.Json; +using NLog; + + + +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 = "") + { + 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, jsonSerializerOptions); + } + 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..eaa8c37 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,24 @@ public static class ProgramUtils } + public static void CreatePermissions(ref WebApplication app) + { + Logger.Info("[ProgramUtils][CreatePermissions] Adding permissions..."); + using var scope = app.Services.CreateScope(); + Func permissionService = scope.ServiceProvider.GetRequiredService; + 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"); + } + } + } \ 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