Skip to content

Commit

Permalink
Role-based auth - API + WEB
Browse files Browse the repository at this point in the history
  • Loading branch information
crni99 committed Sep 20, 2024
1 parent 4180df9 commit 70bd74c
Show file tree
Hide file tree
Showing 64 changed files with 1,372 additions and 754 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@

namespace AirportAutomationApi.Test.Controllers
{
public class ApiUserManagementControllerTests
public class ApiUsersControllerTests
{
private readonly ApiUserManagementController _controller;
private readonly Mock<IApiUserManagementService> _apiUserServiceMock;
private readonly ApiUsersController _controller;
private readonly Mock<IApiUserService> _apiUserServiceMock;
private readonly Mock<IPaginationValidationService> _paginationValidationServiceMock;
private readonly Mock<IInputValidationService> _inputValidationServiceMock;
private readonly Mock<IUtilityService> _utilityServiceMock;
private readonly Mock<IMapper> _mapperMock;
private readonly Mock<ILogger<ApiUserManagementController>> _loggerMock;
private readonly Mock<ILogger<ApiUsersController>> _loggerMock;
private readonly Mock<IConfiguration> _configurationMock;

private readonly ApiUserEntity apiUserEntity = new()
Expand All @@ -40,14 +40,14 @@ public class ApiUserManagementControllerTests
Roles = "SuperAdmin"
};

public ApiUserManagementControllerTests()
public ApiUsersControllerTests()
{
_apiUserServiceMock = new Mock<IApiUserManagementService>();
_apiUserServiceMock = new Mock<IApiUserService>();
_paginationValidationServiceMock = new Mock<IPaginationValidationService>();
_inputValidationServiceMock = new Mock<IInputValidationService>();
_utilityServiceMock = new Mock<IUtilityService>();
_mapperMock = new Mock<IMapper>();
_loggerMock = new Mock<ILogger<ApiUserManagementController>>();
_loggerMock = new Mock<ILogger<ApiUsersController>>();
_configurationMock = new Mock<IConfiguration>();
var configBuilder = new ConfigurationBuilder();
configBuilder.AddInMemoryCollection(new Dictionary<string, string>
Expand All @@ -57,7 +57,7 @@ public ApiUserManagementControllerTests()
_configurationMock.Setup(x => x.GetSection(It.IsAny<string>()))
.Returns(configBuilder.Build().GetSection(""));

_controller = new ApiUserManagementController(
_controller = new ApiUsersController(
_apiUserServiceMock.Object,
_paginationValidationServiceMock.Object,
_inputValidationServiceMock.Object,
Expand Down Expand Up @@ -420,7 +420,7 @@ public async Task PutApiUser_ReturnsNoContent_WhenUpdateIsSuccessful()
{
// Arrange
int id = 1;
var apiUserRoleDto = new ApiUserRoleDto { Id = id };
var apiUserRoleDto = new ApiUserRoleDto { ApiUserId = id };
var apiUserEntity = new ApiUserEntity { ApiUserId = id };

_inputValidationServiceMock.Setup(service => service.IsNonNegativeInt(id)).Returns(true);
Expand All @@ -441,7 +441,7 @@ public async Task PutApiUser_ReturnsBadRequest_WhenIdIsInvalid()
{
// Arrange
int invalidId = -1;
var apiUserRoleDto = new ApiUserRoleDto { Id = invalidId };
var apiUserRoleDto = new ApiUserRoleDto { ApiUserId = invalidId };

_inputValidationServiceMock.Setup(service => service.IsNonNegativeInt(invalidId)).Returns(false);

Expand All @@ -459,7 +459,7 @@ public async Task PutApiUser_ReturnsBadRequest_WhenIdInDtoDoesNotMatchIdInUrl()
{
// Arrange
int id = 1;
var apiUserRoleDto = new ApiUserRoleDto { Id = 2 };
var apiUserRoleDto = new ApiUserRoleDto { ApiUserId = 2 };

_inputValidationServiceMock.Setup(service => service.IsNonNegativeInt(id)).Returns(true);

Expand All @@ -476,7 +476,7 @@ public async Task PutApiUser_ReturnsNotFound_WhenApiUserDoesNotExist()
{
// Arrange
int id = 1;
var apiUserRoleDto = new ApiUserRoleDto { Id = id };
var apiUserRoleDto = new ApiUserRoleDto { ApiUserId = id };

_inputValidationServiceMock.Setup(service => service.IsNonNegativeInt(id)).Returns(true);
_apiUserServiceMock.Setup(service => service.ApiUserExists(id)).ReturnsAsync(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@

namespace AirportAutomationApi.Test.Services
{
public class ApiUserManagementServiceTests
public class ApiUserServiceTests
{
private readonly Mock<IApiUserManagementRepository> _repositoryMock;
private readonly ApiUserManagementService _service;
private readonly Mock<IApiUserRepository> _repositoryMock;
private readonly ApiUserService _service;

public ApiUserManagementServiceTests()
public ApiUserServiceTests()
{
_repositoryMock = new Mock<IApiUserManagementRepository>();
_service = new ApiUserManagementService(_repositoryMock.Object);
_repositoryMock = new Mock<IApiUserRepository>();
_service = new ApiUserService(_repositoryMock.Object);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace AirportAutomation.Application.Dtos.ApiUser;

public class ApiUserRoleDto
{
public int Id { get; set; }
public int ApiUserId { get; set; }

[Required(ErrorMessage = "User Name is required.")]
[MaxLength(50, ErrorMessage = "User Name cannot be longer than 50 characters.")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@

namespace AirportAutomation.Application.Services
{
public class ApiUserManagementService : IApiUserManagementService
public class ApiUserService : IApiUserService
{

private readonly IApiUserManagementRepository _apiUserManagementRepository;
private readonly IApiUserRepository _apiUserManagementRepository;

public ApiUserManagementService(IApiUserManagementRepository apiUserManagementRepository)
public ApiUserService(IApiUserRepository apiUserManagementRepository)
{
_apiUserManagementRepository = apiUserManagementRepository;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace AirportAutomation.Core.Interfaces.IRepositories
{
public interface IApiUserManagementRepository
public interface IApiUserRepository
{
Task<IList<ApiUserEntity>> GetApiUsers(int page, int pageSize);
Task<ApiUserEntity?> GetApiUser(int id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace AirportAutomation.Core.Interfaces.IServices
{
public interface IApiUserManagementService
public interface IApiUserService
{
Task<IList<ApiUserEntity>> GetApiUsers(int page, int pageSize);
Task<ApiUserEntity?> GetApiUser(int id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@

namespace AirportAutomation.Infrastructure.Repositories
{
public class ApiUserManagementRepository : IApiUserManagementRepository
public class ApiUserRepository : IApiUserRepository
{
protected readonly DatabaseContext _context;

public ApiUserManagementRepository(DatabaseContext context)
public ApiUserRepository(DatabaseContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@
<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="8.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="PagedList" Version="1.17.0" />
<PackageReference Include="PagedList.Mvc" Version="4.5.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.0.2" />
<PackageReference Include="System.Resources.ResourceManager" Version="4.3.0" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
namespace AirportAutomation.Web.Controllers
{
[Route("[controller]")]
public class AirlineController : Controller
public class AirlineController : BaseController
{
private readonly IHttpCallService _httpCallService;
private readonly IAlertService _alertService;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
using AirportAutomation.Application.Dtos.ApiUser;
using AirportAutomation.Core.Entities;
using AirportAutomation.Web.Interfaces;
using AirportAutomation.Web.Models.ApiUser;
using AirportAutomation.Web.Models.Response;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;

namespace AirportAutomation.Web.Controllers
{
[Route("[controller]")]
public class ApiUserController : BaseController
{
private readonly IHttpCallService _httpCallService;
private readonly IAlertService _alertService;
private readonly IMapper _mapper;

public ApiUserController(IHttpCallService httpCallService, IAlertService alertService, IMapper mapper)
{
_httpCallService = httpCallService;
_alertService = alertService;
_mapper = mapper;
}

[HttpGet]
public async Task<IActionResult> Index(int page = 1, int pageSize = 10)
{
if (page < 1)
{
_alertService.SetAlertMessage(TempData, "invalid_page_number", false);
return RedirectToAction("Index");
}
var response = await _httpCallService.GetDataList<ApiUserEntity>(page, pageSize);
if (response == null)
{
return View();
}
var pagedResponse = _mapper.Map<PagedResponse<ApiUserViewModel>>(response);
return View(pagedResponse);
}

[HttpGet]
[Route("{id}")]
public async Task<IActionResult> Details(int id)
{
var response = await _httpCallService.GetData<ApiUserEntity>(id);
if (response is null)
{
_alertService.SetAlertMessage(TempData, "data_not_found", false);
return RedirectToAction("Index");
}
else
{
return View(_mapper.Map<ApiUserViewModel>(response));
}
}


[HttpGet]
[Route("GetApiUsersByName/{name}")]
public async Task<IActionResult> GetApiUsersByName(string name)
{
if (string.IsNullOrEmpty(name))
{
_alertService.SetAlertMessage(TempData, "missing_field", false);
return RedirectToAction("Index");
}
var response = await _httpCallService.GetDataByName<ApiUserEntity>(name);
return Json(response);
}

[HttpGet]
[Route("Create")]
public IActionResult Create()
{
return View();
}

[HttpGet]
[Route("Edit/{id}")]
public async Task<IActionResult> Edit(int id)
{
var response = await _httpCallService.GetData<ApiUserEntity>(id);
if (response is null)
{
_alertService.SetAlertMessage(TempData, "data_not_found", false);
return RedirectToAction("Details", new { id });
}
else
{
return View(_mapper.Map<ApiUserViewModel>(response));
}
}

[HttpPost]
[Route("EditApiUser")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditApiUser(ApiUserViewModel apiUserDto)
{
if (ModelState.IsValid)
{
var apiUser = _mapper.Map<ApiUserEntity>(apiUserDto);
var response = await _httpCallService.EditData<ApiUserEntity>(apiUser, apiUser.ApiUserId);
if (response)
{
_alertService.SetAlertMessage(TempData, "edit_data_success", true);
return RedirectToAction("Details", new { id = apiUserDto.Id });
}
else
{
_alertService.SetAlertMessage(TempData, "edit_data_failed", false);
return RedirectToAction("Edit", new { id = apiUserDto.Id });
}
}
else { return RedirectToAction("Index"); }
}

[HttpGet]
[Route("Delete/{id}")]
public async Task<IActionResult> Delete(int id)
{
var response = await _httpCallService.DeleteData<ApiUserEntity>(id);
if (response)
{
_alertService.SetAlertMessage(TempData, "delete_data_success", true);
return RedirectToAction("Index");
}
else
{
_alertService.SetAlertMessage(TempData, "delete_data_failed", false);
return RedirectToAction("Details", new { id });
}
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace AirportAutomation.Web.Controllers
{
public class BaseController : Controller
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);

ViewBag.ApiUserRole = HttpContext.Session.GetString("AccessRole");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
namespace AirportAutomation.Web.Controllers
{
[Route("[controller]")]
public class DestinationController : Controller
public class DestinationController : BaseController
{
private readonly IHttpCallService _httpCallService;
private readonly IAlertService _alertService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
namespace AirportAutomation.Web.Controllers
{
[Route("[controller]")]
public class FlightController : Controller
public class FlightController : BaseController
{
private readonly IHttpCallService _httpCallService;
private readonly IAlertService _alertService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
namespace AirportAutomation.Web.Controllers
{
[Route("[controller]")]
public class HealthCheckController : Controller
public class HealthCheckController : BaseController
{
private readonly IHttpCallService _httpCallService;
private readonly IMapper _mapper;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
using AirportAutomation.Web.Authentication;
using AirportAutomation.Web.Interfaces;
using AirportAutomation.Web.Interfaces;
using AirportAutomation.Web.Models.ApiUser;
using Microsoft.AspNetCore.Mvc;

namespace AirportAutomation.Web.Controllers
{
[Route("")]
public class HomeController : Controller
public class HomeController : BaseController
{
private readonly IHttpCallService _httpCallService;
private readonly IAlertService _alertService;
Expand All @@ -26,7 +26,7 @@ public IActionResult Index(bool logout = false)
string token = _httpCallService.GetToken();
if (!string.IsNullOrEmpty(token))
{
return Redirect("HealthCheck");
return Redirect("/");
}
return View("Index");
}
Expand Down
Loading

0 comments on commit 70bd74c

Please sign in to comment.