29 Commits

Author SHA1 Message Date
7aa438f6c1 Fixed error in PermissionService 2025-05-27 23:52:48 +02:00
49ac876a66 Adding tests for CreatePermissionsOnStartupAsync_Success 2025-05-27 23:25:41 +02:00
f65dfab414 Adding tests for FileUtils 2025-05-19 00:24:50 +02:00
0cc6b0265c Updated filename 2025-05-19 00:04:17 +02:00
58b7e75e77 Adding tests 2025-05-19 00:03:27 +02:00
ec0847e95c Packages upgrade 2025-05-18 23:44:34 +02:00
0f73560cd9 Adding tests 2025-05-18 23:23:24 +02:00
6d7dc432d8 Reducing cognitive complexity 2025-05-18 00:25:52 +02:00
c5c6806a75 Fixing issues - 4 2025-05-17 23:52:14 +02:00
2ee44822c2 Fixing issues - 3 2025-05-17 23:41:35 +02:00
68387c558c Fixing issues - 2 2025-05-17 23:18:23 +02:00
448afad655 Fixing issues - 1 2025-05-17 22:57:53 +02:00
9936e85781 Added permissions creation during startup 2025-05-17 22:47:22 +02:00
c639f86068 Adding permissions during startup 2025-04-27 22:29:35 +02:00
8a2f038185 Adding RolePermissionSystemModuleOperation tests 2025-04-27 20:39:50 +02:00
e578102289 Adding PermissionSystemModuleOperation tests 2025-04-27 20:27:45 +02:00
dfadde4416 Adding PermissionSystemModule tests 2025-04-27 20:11:08 +02:00
74a5ae5548 Adding PermissionOperation tests + minor fixes 2025-04-27 19:54:55 +02:00
c5fa25ceeb Adding PermissionModule tests 2025-04-27 18:37:09 +02:00
a5c3c5cbd0 Adding tests for PermissionService 2025-04-27 18:24:44 +02:00
2a5d7ff5f6 Adding permissions' methods 2025-04-26 23:40:07 +02:00
b778a357ba Fixing issues and improving coverage 2025-03-28 23:15:53 +01:00
df428b9201 Fixing issues 2025-03-28 22:38:10 +01:00
a648a2ea77 FIxing issues 2025-03-28 22:32:24 +01:00
366962abfa Adding tests 2025-03-28 22:15:39 +01:00
d52c385e7c Added role update endpoint 2025-03-28 20:19:26 +01:00
f64e367645 Added tests 2025-03-27 20:06:38 +01:00
654cd159bc Added RoleController 2025-03-27 19:05:15 +01:00
Caterina Simona Pastore
ac20664446 Merged roles branch 2025-03-26 23:52:19 +01:00
53 changed files with 5781 additions and 63 deletions

View File

@@ -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": [] }
]
}
]
]
}

View File

@@ -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": [] }
]
}
]
}
]
}

View File

@@ -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<IRoleService>? _roleServiceMock;
private RoleController? _roleController;
[TestInitialize]
public void Setup()
{
IConfiguration configuration = TestUtils.CreateConfiguration();
_roleServiceMock = new Mock<IRoleService>();
_roleController = new RoleController(configuration, _roleServiceMock.Object);
}
[TestMethod]
public void RoleController_NullConfiguration()
{
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
var exception = true;
try
{
var roleServiceMock = new Mock<IRoleService>();
_ = 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<string>())).ReturnsAsync(role);
ObjectResult response = (ObjectResult)(await _roleController.GetRoleByGuidAsync(guid));
if (response != null && response.Value != null)
{
Assert.IsTrue(response.StatusCode == StatusCodes.Status200OK);
var result = (BaseResponse<object>)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<string>())).ReturnsAsync(role);
ObjectResult response = (ObjectResult)(await _roleController.GetRoleByGuidAsync(guid));
if (response != null && response.Value != null)
{
Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest);
var result = (BaseResponse<object>)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<string>())).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<string>())).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<object>)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<string>())).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<object>)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<string>(), It.IsAny<string>())).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<object>)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<string>(), It.IsAny<string>())).ReturnsAsync(false);
ObjectResult response = (ObjectResult)(await _roleController.CreateRoleAsync(request));
if (response != null && response.Value != null)
{
Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest);
var result = (BaseResponse<object>)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<string>(), It.IsAny<string>())).ReturnsAsync(true);
_roleServiceMock?.Setup(s => s.CreateRoleAsync(
It.IsAny<CreateRoleRequestData>()
)).ReturnsAsync(role);
ObjectResult response = (ObjectResult)(await _roleController.CreateRoleAsync(request));
if (response != null && response.Value != null)
{
Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest);
var result = (BaseResponse<object>)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<string>(), It.IsAny<string>())).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<object>)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<string>(), It.IsAny<string>())).ReturnsAsync(true);
_roleServiceMock?.Setup(s => s.CreateRoleAsync(
It.IsAny<CreateRoleRequestData>()
)).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<object>)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<string>(), It.IsAny<string>())).ReturnsAsync(true);
_roleServiceMock?.Setup(s => s.CreateRoleAsync(
It.IsAny<CreateRoleRequestData>()
)).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<object>)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<string>())).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<string>())).ReturnsAsync(role);
ObjectResult response = (ObjectResult)(await _roleController.DeleteRoleByGuidAsync(guid));
if (response != null && response.Value != null)
{
Assert.IsTrue(response.StatusCode == StatusCodes.Status400BadRequest);
var result = (BaseResponse<object>)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<string>())).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<string>())).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<object>)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<string>())).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<object>)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<string>())).ReturnsAsync(role);
_roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(true);
_roleServiceMock?.Setup(s => s.UpdateRoleAsync(It.IsAny<CreateRoleRequestData>(), It.IsAny<Role>())).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<object>)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<string>())).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<string>())).ReturnsAsync(role);
_roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny<string>(), It.IsAny<string>())).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<object>)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<string>())).ReturnsAsync(role);
_roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny<string>(), It.IsAny<string>())).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<object>)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<string>())).ReturnsAsync(role);
_roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(true);
_roleServiceMock?.Setup(s => s.UpdateRoleAsync(It.IsAny<CreateRoleRequestData>(), It.IsAny<Role>())).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<object>)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<string>())).ReturnsAsync(role);
_roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(true);
_roleServiceMock?.Setup(s => s.UpdateRoleAsync(It.IsAny<CreateRoleRequestData>(), It.IsAny<Role>())).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<object>)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<string>())).ReturnsAsync(role);
_roleServiceMock?.Setup(s => s.CheckIfNameIsValid(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(true);
_roleServiceMock?.Setup(s => s.UpdateRoleAsync(
It.IsAny<CreateRoleRequestData>(), It.IsAny<Role>()
)).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<object>)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
}

View File

@@ -39,7 +39,6 @@ public class RootController_Test
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex.InnerException);
Assert.Fail($"An exception was thrown: {ex}"); Assert.Fail($"An exception was thrown: {ex}");
} }
} }

View File

@@ -31,7 +31,7 @@ using BasicDotnetTemplate.MainProject.Models.Database.SqlServer;
namespace BasicDotnetTemplate.MainProject.Tests; namespace BasicDotnetTemplate.MainProject.Tests;
[TestClass] [TestClass]
public class UserControllerTests public class UserController_Tests
{ {
private Mock<IUserService>? _userServiceMock; private Mock<IUserService>? _userServiceMock;
private Mock<IRoleService>? _roleServiceMock; private Mock<IRoleService>? _roleServiceMock;
@@ -43,7 +43,7 @@ public class UserControllerTests
IConfiguration configuration = TestUtils.CreateConfiguration(); IConfiguration configuration = TestUtils.CreateConfiguration();
_userServiceMock = new Mock<IUserService>(); _userServiceMock = new Mock<IUserService>();
_roleServiceMock = new Mock<IRoleService>(); _roleServiceMock = new Mock<IRoleService>();
_userController = new UserController(configuration, _userServiceMock?.Object, _roleServiceMock.Object); _userController = new UserController(configuration, _userServiceMock.Object, _roleServiceMock.Object);
} }
[TestMethod] [TestMethod]
@@ -100,7 +100,7 @@ public class UserControllerTests
} }
[TestMethod] [TestMethod]
public async Task GetUserByGuidAsync_AuthenticateRequestDataNull() public async Task GetUserByGuidAsync_GuidIsEmpty()
{ {
if (_userController == null) if (_userController == null)
{ {
@@ -232,7 +232,7 @@ public class UserControllerTests
} }
[TestMethod] [TestMethod]
public async Task CreateUserAsync_Should_Return_200_When_Successful() public async Task CreateUserAsync_Success()
{ {
if (_userController == null) if (_userController == null)
{ {

View File

@@ -68,7 +68,6 @@ public class VersionController_Tests
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex.InnerException);
Assert.Fail($"An exception was thrown: {ex}"); Assert.Fail($"An exception was thrown: {ex}");
} }
} }
@@ -80,7 +79,6 @@ public class VersionController_Tests
try try
{ {
Console.WriteLine(System.AppDomain.CurrentDomain.BaseDirectory);
var configuration = TestUtils.CreateEmptyConfiguration(System.AppDomain.CurrentDomain.BaseDirectory + "/JsonData", "emptyAppsettings.json"); var configuration = TestUtils.CreateEmptyConfiguration(System.AppDomain.CurrentDomain.BaseDirectory + "/JsonData", "emptyAppsettings.json");
VersionController versionController = new VersionController(configuration); VersionController versionController = new VersionController(configuration);
var result = versionController.GetVersion(); var result = versionController.GetVersion();
@@ -97,7 +95,6 @@ public class VersionController_Tests
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex.InnerException);
Assert.Fail($"An exception was thrown: {ex}"); Assert.Fail($"An exception was thrown: {ex}");
} }
} }

View File

@@ -29,6 +29,9 @@
<ItemGroup> <ItemGroup>
<Content Include="JsonData/**" CopyToOutputDirectory="Always" CopyToPublishDirectory="Always" /> <Content Include="JsonData/**" CopyToOutputDirectory="Always" CopyToPublishDirectory="Always" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Content Include="Config/**" CopyToOutputDirectory="Always" CopyToPublishDirectory="Always" />
</ItemGroup>
</Project> </Project>

View File

@@ -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<AutoMapperConfiguration>();
});
_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<RoleDto>(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}");
}
}
}

View File

@@ -69,7 +69,6 @@ public class Program_Tests
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex.InnerException);
Assert.Fail($"An exception was thrown: {ex}"); Assert.Fail($"An exception was thrown: {ex}");
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -2,6 +2,8 @@
using BasicDotnetTemplate.MainProject.Services; using BasicDotnetTemplate.MainProject.Services;
using BasicDotnetTemplate.MainProject.Models.Api.Data.Role; using BasicDotnetTemplate.MainProject.Models.Api.Data.Role;
using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; 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] [TestMethod]
public async Task CreateRoleData() public async Task CreateRoleAsync_Success()
{ {
try 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] [TestMethod]
public async Task CheckIfNameIsValid_NameCurrentRole() 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] [TestMethod]
public async Task DeleteRoleAsync() public async Task DeleteRoleAsync()
{ {

View File

@@ -2,6 +2,7 @@ using BasicDotnetTemplate.MainProject.Services;
using BasicDotnetTemplate.MainProject.Models.Api.Data.User; using BasicDotnetTemplate.MainProject.Models.Api.Data.User;
using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; using BasicDotnetTemplate.MainProject.Models.Database.SqlServer;
using Newtonsoft.Json; 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] [TestMethod]
public async Task CheckIfEmailIsValid_EmailCurrentUser() public async Task CheckIfEmailIsValid_EmailCurrentUser()
{ {

View File

@@ -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<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
if (ThrowExceptionOnSave)
{
throw new Exception("Database error");
}
return base.SaveChangesAsync(cancellationToken);
}
}

View File

@@ -64,11 +64,21 @@ public static class TestUtils
return _appSettings.DatabaseSettings?.SqlServerConnectionString ?? String.Empty; return _appSettings.DatabaseSettings?.SqlServerConnectionString ?? String.Empty;
} }
public static SqlServerContext CreateInMemorySqlContext() public static string GetFakeConnectionString()
{ {
var options = new DbContextOptionsBuilder<SqlServerContext>() 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<SqlServerContext> CreateInMemorySqlContextOptions()
{
return new DbContextOptionsBuilder<SqlServerContext>()
.UseSqlite("DataSource=:memory:") // Database in-memory .UseSqlite("DataSource=:memory:") // Database in-memory
.Options; .Options;
}
public static SqlServerContext CreateInMemorySqlContext()
{
var options = CreateInMemorySqlContextOptions();
var context = new SqlServerContext(options); var context = new SqlServerContext(options);
context.Database.OpenConnection(); context.Database.OpenConnection();
@@ -79,8 +89,6 @@ public static class TestUtils
public static BaseService CreateBaseService() public static BaseService CreateBaseService()
{ {
IConfiguration configuration = CreateConfiguration(); IConfiguration configuration = CreateConfiguration();
var optionsBuilder = new DbContextOptionsBuilder<SqlServerContext>();
optionsBuilder.UseSqlServer(GetSqlConnectionString(configuration));
SqlServerContext sqlServerContext = CreateInMemorySqlContext(); SqlServerContext sqlServerContext = CreateInMemorySqlContext();
var httpContextAccessor = new Mock<IHttpContextAccessor>(); var httpContextAccessor = new Mock<IHttpContextAccessor>();
return new BaseService(httpContextAccessor.Object, configuration, sqlServerContext); return new BaseService(httpContextAccessor.Object, configuration, sqlServerContext);
@@ -89,8 +97,6 @@ public static class TestUtils
public static AuthService CreateAuthService() public static AuthService CreateAuthService()
{ {
IConfiguration configuration = CreateConfiguration(); IConfiguration configuration = CreateConfiguration();
var optionsBuilder = new DbContextOptionsBuilder<SqlServerContext>();
optionsBuilder.UseSqlServer(GetSqlConnectionString(configuration));
SqlServerContext sqlServerContext = CreateInMemorySqlContext(); SqlServerContext sqlServerContext = CreateInMemorySqlContext();
var userServiceMock = new Mock<IUserService>(); var userServiceMock = new Mock<IUserService>();
var httpContextAccessor = new Mock<IHttpContextAccessor>(); var httpContextAccessor = new Mock<IHttpContextAccessor>();
@@ -105,6 +111,15 @@ public static class TestUtils
return new UserService(httpContextAccessor.Object, configuration, sqlServerContext); 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<IHttpContextAccessor>();
return new UserService(httpContextAccessor.Object, configuration, sqlServerContext);
}
public static JwtService CreateJwtService() public static JwtService CreateJwtService()
{ {
IConfiguration configuration = CreateConfiguration(); IConfiguration configuration = CreateConfiguration();
@@ -124,6 +139,32 @@ public static class TestUtils
var httpContextAccessor = new Mock<IHttpContextAccessor>(); var httpContextAccessor = new Mock<IHttpContextAccessor>();
return new RoleService(httpContextAccessor.Object, configuration, sqlServerContext); 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<IHttpContextAccessor>();
return new RoleService(httpContextAccessor.Object, configuration, sqlServerContext);
}
public static PermissionService CreatePermissionService()
{
IConfiguration configuration = CreateConfiguration();
SqlServerContext sqlServerContext = CreateInMemorySqlContext();
var httpContextAccessor = new Mock<IHttpContextAccessor>();
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<IHttpContextAccessor>();
return new PermissionService(httpContextAccessor.Object, configuration, sqlServerContext);
}
} }

View File

@@ -151,8 +151,6 @@ public class CryptoUtils_Tests
AppSettings appSettings = ProgramUtils.AddConfiguration(ref builder, System.AppDomain.CurrentDomain.BaseDirectory + "/JsonData"); AppSettings appSettings = ProgramUtils.AddConfiguration(ref builder, System.AppDomain.CurrentDomain.BaseDirectory + "/JsonData");
CryptUtils cryptoUtils = new CryptUtils(appSettings); CryptUtils cryptoUtils = new CryptUtils(appSettings);
var verified = cryptoUtils.VerifyPassword(password, salt, 0, hashedPassword); var verified = cryptoUtils.VerifyPassword(password, salt, 0, hashedPassword);
Console.WriteLine(cryptoUtils.GeneratePassword(password, salt, 0));
Assert.IsTrue(verified); Assert.IsTrue(verified);
} }
catch (Exception ex) catch (Exception ex)

View File

@@ -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<PermissionsFile>(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<PermissionsFile>(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<PermissionsFile>(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<PermissionsFile>(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}");
}
}
}

View File

@@ -299,7 +299,6 @@ public class ProgramUtils_Tests
ProgramUtils.AddDbContext(ref builder, realAppSettings); ProgramUtils.AddDbContext(ref builder, realAppSettings);
var areEquals = expectedDbSettings.SqlServerConnectionString == realAppSettings.DatabaseSettings?.SqlServerConnectionString; var areEquals = expectedDbSettings.SqlServerConnectionString == realAppSettings.DatabaseSettings?.SqlServerConnectionString;
Console.WriteLine(realAppSettings.DatabaseSettings?.SqlServerConnectionString);
Assert.IsTrue(areEquals); Assert.IsTrue(areEquals);
} }
catch (Exception ex) catch (Exception ex)

View File

@@ -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": [] }
]
}
]
}
]
}

View File

@@ -55,7 +55,7 @@ namespace BasicDotnetTemplate.MainProject.Controllers
} }
catch (Exception exception) catch (Exception exception)
{ {
var message = "Something went wrong"; var message = this._somethingWentWrong;
if (!String.IsNullOrEmpty(exception.Message)) if (!String.IsNullOrEmpty(exception.Message))
{ {
message += $". {exception.Message}"; message += $". {exception.Message}";

View File

@@ -13,6 +13,7 @@ namespace BasicDotnetTemplate.MainProject.Controllers
protected readonly IConfiguration _configuration; protected readonly IConfiguration _configuration;
protected readonly AppSettings _appSettings; protected readonly AppSettings _appSettings;
protected readonly string _requestNotWellFormed = "Request is not well formed"; protected readonly string _requestNotWellFormed = "Request is not well formed";
protected readonly string _somethingWentWrong = "Something went wrong";
protected BaseController( protected BaseController(
IConfiguration configuration IConfiguration configuration

View File

@@ -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<GetRoleResponse>(StatusCodes.Status200OK)]
[ProducesResponseType<BaseResponse<object>>(StatusCodes.Status404NotFound)]
[ProducesResponseType<BaseResponse<object>>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<BaseResponse<object>>(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> 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<RoleDto>(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<GetRoleResponse>(StatusCodes.Status201Created)]
[ProducesResponseType<BaseResponse<object>>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<BaseResponse<object>>(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> 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<RoleDto>(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<GetRoleResponse>(StatusCodes.Status201Created)]
[ProducesResponseType<BaseResponse<object>>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<BaseResponse<object>>(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> 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<RoleDto>(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<GetRoleResponse>(StatusCodes.Status200OK)]
[ProducesResponseType<BaseResponse<object>>(StatusCodes.Status404NotFound)]
[ProducesResponseType<BaseResponse<object>>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<BaseResponse<object>>(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> 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);
}
}
}
}

View File

@@ -57,7 +57,7 @@ namespace BasicDotnetTemplate.MainProject.Controllers
} }
catch (Exception exception) catch (Exception exception)
{ {
var message = "Something went wrong"; var message = this._somethingWentWrong;
if (!String.IsNullOrEmpty(exception.Message)) if (!String.IsNullOrEmpty(exception.Message))
{ {
message += $". {exception.Message}"; message += $". {exception.Message}";
@@ -118,7 +118,7 @@ namespace BasicDotnetTemplate.MainProject.Controllers
} }
catch (Exception exception) catch (Exception exception)
{ {
var message = "Something went wrong"; var message = this._somethingWentWrong;
if (!String.IsNullOrEmpty(exception.Message)) if (!String.IsNullOrEmpty(exception.Message))
{ {
message += $". {exception.Message}"; message += $". {exception.Message}";

View File

@@ -6,29 +6,75 @@ namespace BasicDotnetTemplate.MainProject.Core.Database
{ {
public class SqlServerContext : DbContext public class SqlServerContext : DbContext
{ {
private const string _isDeletedFalse = "[IsDeleted] = 0";
private const string _isEnabled = "[Enabled] = 1";
public SqlServerContext(DbContextOptions<SqlServerContext> options) public SqlServerContext(DbContextOptions<SqlServerContext> options)
: base(options) : base(options)
{ {
} }
public DbSet<User> Users { get; set; } public DbSet<PermissionModule> PermissionModules { get; set; }
public DbSet<PermissionOperation> PermissionOperations { get; set; }
public DbSet<PermissionSystem> PermissionSystems { get; set; }
public DbSet<PermissionSystemModule> PermissionSystemModules { get; set; }
public DbSet<PermissionSystemModuleOperation> PermissionSystemModuleOperations { get; set; }
public DbSet<RolePermissionSystemModuleOperation> RolePermissionSystemModuleOperations { get; set; }
public DbSet<Role> Roles { get; set; } public DbSet<Role> Roles { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
#region "INDEXES"
// Indexes
modelBuilder.Entity<User>() modelBuilder.Entity<User>()
.HasIndex(x => x.Email, "IX_Email"); .HasIndex(x => x.Email, "IX_Email");
modelBuilder.Entity<User>() modelBuilder.Entity<User>()
.HasIndex(x => new { x.IsDeleted, x.Guid }, "IX_IsDeleted_Guid") .HasIndex(x => new { x.IsDeleted, x.Guid }, "IX_IsDeleted_Guid")
.HasFilter("[IsDeleted] = 0"); .HasFilter(_isDeletedFalse);
modelBuilder.Entity<Role>() modelBuilder.Entity<Role>()
.HasIndex(x => new { x.IsDeleted, x.Guid }, "IX_IsDeleted_Guid") .HasIndex(x => new { x.IsDeleted, x.Guid }, "IX_IsDeleted_Guid")
.HasFilter("[IsDeleted] = 0"); .HasFilter(_isDeletedFalse);
modelBuilder.Entity<PermissionSystem>()
.HasIndex(x => new { x.IsDeleted }, "IX_IsDeleted")
.HasFilter(_isDeletedFalse);
modelBuilder.Entity<PermissionSystem>()
.HasIndex(x => new { x.Enabled }, "IX_Enabled")
.HasFilter(_isEnabled);
modelBuilder.Entity<PermissionSystem>()
.HasIndex(x => new { x.IsDeleted, x.Name, x.Enabled }, "IX_IsDeleted_Name_Enabled")
.HasFilter(_isEnabled)
.HasFilter(_isDeletedFalse);
modelBuilder.Entity<PermissionModule>()
.HasIndex(x => new { x.IsDeleted }, "IX_IsDeleted")
.HasFilter(_isDeletedFalse);
modelBuilder.Entity<PermissionModule>()
.HasIndex(x => new { x.Enabled }, "IX_Enabled")
.HasFilter(_isEnabled);
modelBuilder.Entity<PermissionModule>()
.HasIndex(x => new { x.IsDeleted, x.Name, x.Enabled }, "IX_IsDeleted_Name_Enabled")
.HasFilter(_isEnabled)
.HasFilter(_isDeletedFalse);
modelBuilder.Entity<PermissionOperation>()
.HasIndex(x => new { x.IsDeleted, x.Name }, "IX_IsDeleted_Name");
modelBuilder.Entity<PermissionSystemModuleOperation>()
.HasIndex(x => new { x.IsDeleted, x.Enabled, x.Guid }, "IX_IsDeleted_Enabled_Guid");
#endregion
} }
} }
} }

View File

@@ -1,6 +1,7 @@
using BasicDotnetTemplate.MainProject.Models.Api.Common.User; using BasicDotnetTemplate.MainProject.Models.Api.Common.User;
using SqlServerDatabase = BasicDotnetTemplate.MainProject.Models.Database.SqlServer; using SqlServerDatabase = BasicDotnetTemplate.MainProject.Models.Database.SqlServer;
using AutoMapper; using AutoMapper;
using BasicDotnetTemplate.MainProject.Models.Api.Common.Role;
namespace BasicDotnetTemplate.MainProject.Core.Middlewares; namespace BasicDotnetTemplate.MainProject.Core.Middlewares;
@@ -8,6 +9,7 @@ public class AutoMapperConfiguration : Profile
{ {
public AutoMapperConfiguration() public AutoMapperConfiguration()
{ {
CreateMap<SqlServerDatabase.Role, RoleDto>();
CreateMap<SqlServerDatabase.User, UserDto>(); CreateMap<SqlServerDatabase.User, UserDto>();
} }

View File

@@ -10,41 +10,41 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" /> <PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="coverlet.msbuild" Version="6.0.2"> <PackageReference Include="coverlet.msbuild" Version="6.0.4">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.13" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.16" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.13" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.2" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="9.0.2" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="9.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.2"> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.2" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.2" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.2"> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="9.0.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.5" />
<PackageReference Include="Microsoft.Identity.Web" Version="3.7.1" /> <PackageReference Include="Microsoft.Identity.Web" Version="3.9.2" />
<PackageReference Include="MongoDB.Driver" Version="2.28.0" /> <PackageReference Include="MongoDB.Driver" Version="3.4.0" />
<PackageReference Include="MongoDB.EntityFrameworkCore" Version="8.1.0" /> <PackageReference Include="MongoDB.EntityFrameworkCore" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NLog" Version="5.2.8" /> <PackageReference Include="NLog" Version="5.4.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" /> <PackageReference Include="NLog.Extensions.Logging" Version="5.4.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.3" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.2" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0" /> <PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="8.1.2" />
<PackageReference Include="Swashbuckle.AspNetCore.Filters" Version="8.0.0" /> <PackageReference Include="Swashbuckle.AspNetCore.Filters" Version="8.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Filters.Abstractions" Version="8.0.0" /> <PackageReference Include="Swashbuckle.AspNetCore.Filters.Abstractions" Version="8.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="6.5.0" /> <PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="8.1.2" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="6.5.0" /> <PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="8.1.2" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="6.5.0" /> <PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="8.1.2" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.5.0" /> <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="8.1.2" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -0,0 +1,543 @@
// <auto-generated />
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
{
/// <inheritdoc />
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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int>("PermissionModuleId")
.HasColumnType("int");
b.Property<int>("PermissionSystemId")
.HasColumnType("int");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int>("PermissionOperationId")
.HasColumnType("int");
b.Property<int>("PermissionSystemModuleId")
.HasColumnType("int");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsNotEditable")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<bool>("Active")
.HasColumnType("bit");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int>("PermissionSystemModuleOperationId")
.HasColumnType("int");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("FirstName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<bool>("IsTestUser")
.HasColumnType("bit");
b.Property<string>("LastName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("PasswordSalt")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("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
}
}
}

View File

@@ -0,0 +1,283 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace MainProject.Migrations
{
/// <inheritdoc />
public partial class AddingPermissionsTables : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "PermissionModules",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
Enabled = table.Column<bool>(type: "bit", nullable: false),
Guid = table.Column<string>(type: "nvarchar(45)", maxLength: 45, nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false),
CreationUserId = table.Column<int>(type: "int", nullable: true),
UpdateTime = table.Column<DateTime>(type: "datetime2", nullable: true),
UpdateUserId = table.Column<int>(type: "int", nullable: true),
DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true),
DeletionUserId = table.Column<int>(type: "int", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_PermissionModules", x => x.Id);
});
migrationBuilder.CreateTable(
name: "PermissionOperations",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
Guid = table.Column<string>(type: "nvarchar(45)", maxLength: 45, nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false),
CreationUserId = table.Column<int>(type: "int", nullable: true),
UpdateTime = table.Column<DateTime>(type: "datetime2", nullable: true),
UpdateUserId = table.Column<int>(type: "int", nullable: true),
DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true),
DeletionUserId = table.Column<int>(type: "int", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_PermissionOperations", x => x.Id);
});
migrationBuilder.CreateTable(
name: "PermissionSystems",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
Enabled = table.Column<bool>(type: "bit", nullable: false),
Guid = table.Column<string>(type: "nvarchar(45)", maxLength: 45, nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false),
CreationUserId = table.Column<int>(type: "int", nullable: true),
UpdateTime = table.Column<DateTime>(type: "datetime2", nullable: true),
UpdateUserId = table.Column<int>(type: "int", nullable: true),
DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true),
DeletionUserId = table.Column<int>(type: "int", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_PermissionSystems", x => x.Id);
});
migrationBuilder.CreateTable(
name: "PermissionSystemModules",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PermissionSystemId = table.Column<int>(type: "int", nullable: false),
PermissionModuleId = table.Column<int>(type: "int", nullable: false),
Enabled = table.Column<bool>(type: "bit", nullable: false),
Guid = table.Column<string>(type: "nvarchar(45)", maxLength: 45, nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false),
CreationUserId = table.Column<int>(type: "int", nullable: true),
UpdateTime = table.Column<DateTime>(type: "datetime2", nullable: true),
UpdateUserId = table.Column<int>(type: "int", nullable: true),
DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true),
DeletionUserId = table.Column<int>(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<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PermissionSystemModuleId = table.Column<int>(type: "int", nullable: false),
PermissionOperationId = table.Column<int>(type: "int", nullable: false),
Enabled = table.Column<bool>(type: "bit", nullable: false),
Guid = table.Column<string>(type: "nvarchar(45)", maxLength: 45, nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false),
CreationUserId = table.Column<int>(type: "int", nullable: true),
UpdateTime = table.Column<DateTime>(type: "datetime2", nullable: true),
UpdateUserId = table.Column<int>(type: "int", nullable: true),
DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true),
DeletionUserId = table.Column<int>(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<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
RoleId = table.Column<int>(type: "int", nullable: false),
PermissionSystemModuleOperationId = table.Column<int>(type: "int", nullable: false),
Active = table.Column<bool>(type: "bit", nullable: false),
Guid = table.Column<string>(type: "nvarchar(45)", maxLength: 45, nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreationTime = table.Column<DateTime>(type: "datetime2", nullable: false),
CreationUserId = table.Column<int>(type: "int", nullable: true),
UpdateTime = table.Column<DateTime>(type: "datetime2", nullable: true),
UpdateUserId = table.Column<int>(type: "int", nullable: true),
DeletionTime = table.Column<DateTime>(type: "datetime2", nullable: true),
DeletionUserId = table.Column<int>(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");
}
/// <inheritdoc />
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");
}
}
}

View File

@@ -22,6 +22,270 @@ namespace MainProject.Migrations
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.PermissionModule", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int>("PermissionModuleId")
.HasColumnType("int");
b.Property<int>("PermissionSystemId")
.HasColumnType("int");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int>("PermissionOperationId")
.HasColumnType("int");
b.Property<int>("PermissionSystemModuleId")
.HasColumnType("int");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("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 => modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.Role", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@@ -72,6 +336,58 @@ namespace MainProject.Migrations
b.ToTable("Roles"); b.ToTable("Roles");
}); });
modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.RolePermissionSystemModuleOperation", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<bool>("Active")
.HasColumnType("bit");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<int?>("CreationUserId")
.HasColumnType("int");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2");
b.Property<int?>("DeletionUserId")
.HasColumnType("int");
b.Property<string>("Guid")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("nvarchar(45)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<int>("PermissionSystemModuleOperationId")
.HasColumnType("int");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<DateTime?>("UpdateTime")
.HasColumnType("datetime2");
b.Property<int?>("UpdateUserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("PermissionSystemModuleOperationId");
b.HasIndex("RoleId");
b.ToTable("RolePermissionSystemModuleOperations");
});
modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.User", b => modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.User", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@@ -151,6 +467,63 @@ namespace MainProject.Migrations
b.ToTable("Users"); 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 => modelBuilder.Entity("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.User", b =>
{ {
b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.Role", "Role") b.HasOne("BasicDotnetTemplate.MainProject.Models.Database.SqlServer.Role", "Role")

View File

@@ -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)
{
}
}

View File

@@ -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)
{
}
}

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -0,0 +1,8 @@
using BasicDotnetTemplate.MainProject.Models.Api.Common.Role;
namespace BasicDotnetTemplate.MainProject.Models.Api.Response.Role;
public class GetRoleResponse : BaseResponse<RoleDto>
{
public GetRoleResponse(int status, string? message, RoleDto? data) : base(status, message, data) { }
}

View File

@@ -0,0 +1,9 @@
namespace BasicDotnetTemplate.MainProject.Models.Common;
public class OperationInfo
{
#nullable enable
public string? Operation { get; set; }
public List<string>? Roles {get; set; }
#nullable disable
}

View File

@@ -0,0 +1,9 @@
namespace BasicDotnetTemplate.MainProject.Models.Common;
public class PermissionInfo
{
#nullable enable
public string? System { get; set; }
public List<RolePermissionModuleOperation>? RolePermissionModuleOperations {get; set; }
#nullable disable
}

View File

@@ -0,0 +1,8 @@
namespace BasicDotnetTemplate.MainProject.Models.Common;
public class PermissionsFile
{
#nullable enable
public List<PermissionInfo>? PermissionInfos { get; set; }
#nullable disable
}

View File

@@ -0,0 +1,9 @@
namespace BasicDotnetTemplate.MainProject.Models.Common;
public class RolePermissionModuleOperation
{
#nullable enable
public string? Module { get; set; }
public List<OperationInfo>? Operations { get; set; }
#nullable disable
}

View File

@@ -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; }
}
}

View File

@@ -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; }
}
}

View File

@@ -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; }
}
}

View File

@@ -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; }
}
}

View File

@@ -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; }
}
}

View File

@@ -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; }
}
}

View File

@@ -9,6 +9,6 @@ public class AppSettings
public DatabaseSettings? DatabaseSettings { get; set; } public DatabaseSettings? DatabaseSettings { get; set; }
public JwtSettings? JwtSettings { get; set; } public JwtSettings? JwtSettings { get; set; }
public EncryptionSettings? EncryptionSettings { get; set; } public EncryptionSettings? EncryptionSettings { get; set; }
public PermissionsSettings? PermissionsSettings { get; set; }
#nullable disable #nullable disable
} }

View File

@@ -0,0 +1,8 @@
namespace BasicDotnetTemplate.MainProject.Models.Settings;
public class PermissionsSettings
{
#nullable enable
public string? FilePath { get; set; }
#nullable disable
}

View File

@@ -45,6 +45,7 @@ internal static class Program
WebApplication app = builder.Build(); WebApplication app = builder.Build();
ProgramUtils.AddMiddlewares(ref app); ProgramUtils.AddMiddlewares(ref app);
ProgramUtils.CreateRoles(ref app); ProgramUtils.CreateRoles(ref app);
ProgramUtils.CreatePermissions(ref app);
Logger.Info("[Program][Initialize] End building"); Logger.Info("[Program][Initialize] End building");
return app; return app;

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,11 @@
using System.Collections; using System.Collections;
using BasicDotnetTemplate.MainProject.Core.Database; using BasicDotnetTemplate.MainProject.Core.Database;
using BasicDotnetTemplate.MainProject.Models.Api.Common.Exceptions;
using BasicDotnetTemplate.MainProject.Models.Api.Data.Role; using BasicDotnetTemplate.MainProject.Models.Api.Data.Role;
using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; using BasicDotnetTemplate.MainProject.Models.Database.SqlServer;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using BasicDotnetTemplate.MainProject.Utils;
namespace BasicDotnetTemplate.MainProject.Services; namespace BasicDotnetTemplate.MainProject.Services;
@@ -13,6 +15,7 @@ public interface IRoleService
Task<Role?> GetRoleByGuidAsync(string guid); Task<Role?> GetRoleByGuidAsync(string guid);
Task<bool> CheckIfNameIsValid(string name, string? guid = ""); Task<bool> CheckIfNameIsValid(string name, string? guid = "");
Task<Role?> CreateRoleAsync(CreateRoleRequestData data); Task<Role?> CreateRoleAsync(CreateRoleRequestData data);
Task<Role?> UpdateRoleAsync(CreateRoleRequestData data, Role role);
Task<Role?> GetRoleForUser(string? guid); Task<Role?> GetRoleForUser(string? guid);
Task<bool?> DeleteRoleAsync(Role role); Task<bool?> DeleteRoleAsync(Role role);
} }
@@ -20,22 +23,24 @@ public interface IRoleService
public class RoleService : BaseService, IRoleService public class RoleService : BaseService, IRoleService
{ {
private readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); private readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
private readonly CommonDbMethodsUtils _commonDbMethodsUtils;
public RoleService( public RoleService(
IHttpContextAccessor httpContextAccessor, IHttpContextAccessor httpContextAccessor,
IConfiguration configuration, IConfiguration configuration,
SqlServerContext sqlServerContext SqlServerContext sqlServerContext
) : base(httpContextAccessor, configuration, sqlServerContext) ) : base(httpContextAccessor, configuration, sqlServerContext)
{ } {
_commonDbMethodsUtils = new CommonDbMethodsUtils(sqlServerContext);
}
private IQueryable<Role> GetRolesQueryable() private IQueryable<Role> GetRolesQueryable()
{ {
return this._sqlServerContext.Roles.Where(x => !x.IsDeleted); return _commonDbMethodsUtils.GetRolesQueryable();
} }
private IQueryable<Role> GetRoleByNameQueryable(string name) private IQueryable<Role> GetRoleByNameQueryable(string name)
{ {
return this.GetRolesQueryable().Where(x => return _commonDbMethodsUtils.GetRoleByNameQueryable(name);
x.Name.ToString() == name.ToString()
);
} }
@@ -107,7 +112,35 @@ public class RoleService : BaseService, IRoleService
{ {
await transaction.RollbackAsync(); await transaction.RollbackAsync();
Logger.Error(exception, $"[RoleService][CreateRoleAsync]"); 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<Role?> 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; return role;

View File

@@ -1,6 +1,7 @@
using System.Collections; using System.Collections;
using BasicDotnetTemplate.MainProject.Core.Database; using BasicDotnetTemplate.MainProject.Core.Database;
using BasicDotnetTemplate.MainProject.Models.Api.Common.Exceptions;
using BasicDotnetTemplate.MainProject.Models.Api.Data.User; using BasicDotnetTemplate.MainProject.Models.Api.Data.User;
using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; using BasicDotnetTemplate.MainProject.Models.Database.SqlServer;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@@ -77,7 +78,6 @@ public class UserService : BaseService, IUserService
if (user != null) if (user != null)
{ {
var encryptedPassword = user.PasswordHash; var encryptedPassword = user.PasswordHash;
Console.WriteLine(encryptedPassword);
} }
return user; return user;
@@ -104,12 +104,13 @@ public class UserService : BaseService, IUserService
public async Task<User?> CreateUserAsync(CreateUserRequestData data, Role role) public async Task<User?> CreateUserAsync(CreateUserRequestData data, Role role)
{ {
User? user;
using var transaction = await _sqlServerContext.Database.BeginTransactionAsync(); using var transaction = await _sqlServerContext.Database.BeginTransactionAsync();
User? user;
var tempUser = CreateUserData(data, role);
try try
{ {
var tempUser = CreateUserData(data, role);
await _sqlServerContext.Users.AddAsync(tempUser); await _sqlServerContext.Users.AddAsync(tempUser);
await _sqlServerContext.SaveChangesAsync(); await _sqlServerContext.SaveChangesAsync();
await transaction.CommitAsync(); await transaction.CommitAsync();
@@ -119,7 +120,7 @@ public class UserService : BaseService, IUserService
{ {
await transaction.RollbackAsync(); await transaction.RollbackAsync();
Logger.Error(exception, $"[UserService][CreateUserAsync]"); Logger.Error(exception, $"[UserService][CreateUserAsync]");
throw; throw new CreateException($"An error occurred while creating the user for transaction ID {transaction.TransactionId}.", exception);
} }

View File

@@ -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<Role> GetRolesQueryable()
{
return this._sqlServerContext.Roles.Where(x => !x.IsDeleted);
}
public IQueryable<Role> GetRoleByNameQueryable(string name)
{
return this.GetRolesQueryable().Where(x =>
x.Name.ToString() == name.ToString()
);
}
}

View File

@@ -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<T>(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<T>(fileContent, jsonSerializerOptions);
}
catch (JsonException ex)
{
throw new InvalidOperationException("Error during file deserialization", ex);
}
}
}

View File

@@ -218,6 +218,7 @@ public static class ProgramUtils
builder.Services.AddHttpContextAccessor(); builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<IAuthService, AuthService>(); builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IJwtService, JwtService>(); builder.Services.AddScoped<IJwtService, JwtService>();
builder.Services.AddScoped<IPermissionService, PermissionService>();
builder.Services.AddScoped<IRoleService, RoleService>(); builder.Services.AddScoped<IRoleService, RoleService>();
builder.Services.AddScoped<IUserService, UserService>(); builder.Services.AddScoped<IUserService, UserService>();
Logger.Info("[ProgramUtils][AddScopes] Done scopes"); 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<IPermissionService?> permissionService = scope.ServiceProvider.GetRequiredService<IPermissionService>;
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");
}
}
} }

View File

@@ -37,6 +37,9 @@
"EncryptionSettings": { "EncryptionSettings": {
"Salt": "S7VIidfXQf1tOQYX", "Salt": "S7VIidfXQf1tOQYX",
"Pepper": "" "Pepper": ""
},
"PermissionsSettings": {
"FilePath": "Config/permissions.json"
} }
} }
} }