Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use token roles in controllers #1211

Merged
merged 9 commits into from
Dec 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions backend/api.test/Database/DatabaseUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
using Api.Database.Context;
using Api.Database.Models;
using Api.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Moq;
namespace Api.Test.Database
{
public class DatabaseUtilities : IDisposable
{
private readonly AccessRoleService _accessRoleService;
private readonly AreaService _areaService;
private readonly DeckService _deckService;
private readonly InstallationService _installationService;
Expand All @@ -23,13 +25,14 @@ public DatabaseUtilities(FlotillaDbContext context)
{
var defaultLocalizationPoseService = new DefaultLocalizationPoseService(context);

_installationService = new InstallationService(context);
_plantService = new PlantService(context, _installationService);
_deckService = new DeckService(context, defaultLocalizationPoseService, _installationService, _plantService);
_areaService = new AreaService(context, _installationService, _plantService, _deckService, defaultLocalizationPoseService);
_missionRunService = new MissionRunService(context, new MockSignalRService(), new Mock<ILogger<MissionRunService>>().Object);
_accessRoleService = new AccessRoleService(context, new HttpContextAccessor());
_installationService = new InstallationService(context, _accessRoleService);
_plantService = new PlantService(context, _installationService, _accessRoleService);
_deckService = new DeckService(context, defaultLocalizationPoseService, _installationService, _plantService, _accessRoleService);
_areaService = new AreaService(context, _installationService, _plantService, _deckService, defaultLocalizationPoseService, _accessRoleService);
_missionRunService = new MissionRunService(context, new MockSignalRService(), new Mock<ILogger<MissionRunService>>().Object, _accessRoleService);
_robotModelService = new RobotModelService(context);
_robotService = new RobotService(context, new Mock<ILogger<RobotService>>().Object, _robotModelService, new MockSignalRService());
_robotService = new RobotService(context, new Mock<ILogger<RobotService>>().Object, _robotModelService, new MockSignalRService(), _accessRoleService);
}

public void Dispose()
Expand Down Expand Up @@ -113,15 +116,15 @@ public async Task<Area> NewArea(string installationCode, string plantCode, strin
return await _areaService.Create(createAreaQuery);
}

public async Task<Robot> NewRobot(RobotStatus status, Area area)
public async Task<Robot> NewRobot(RobotStatus status, Area area, Installation installation)
{
var createRobotQuery = new CreateRobotQuery
{
Name = "TestBot",
IsarId = Guid.NewGuid().ToString(),
RobotType = RobotType.Robot,
SerialNumber = "0001",
CurrentInstallation = "kaa",
CurrentInstallation = installation,
CurrentArea = area,
VideoStreams = new List<CreateVideoStreamQuery>(),
Host = "localhost",
Expand Down
27 changes: 15 additions & 12 deletions backend/api.test/EventHandlers/TestMissionEventHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using Api.Test.Database;
using Api.Test.Mocks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Moq;
Expand Down Expand Up @@ -46,6 +47,7 @@ public class TestMissionEventHandler : IDisposable
private readonly RobotService _robotService;
private readonly ISignalRService _signalRService;
private readonly DatabaseUtilities _databaseUtilities;
private readonly AccessRoleService _accessRoleService;

public TestMissionEventHandler(DatabaseFixture fixture)
{
Expand All @@ -62,17 +64,18 @@ public TestMissionEventHandler(DatabaseFixture fixture)

_signalRService = new MockSignalRService();
_mqttService = new MqttService(mqttServiceLogger, configuration);
_missionRunService = new MissionRunService(_context, _signalRService, missionLogger);
_accessRoleService = new AccessRoleService(_context, new HttpContextAccessor());
_missionRunService = new MissionRunService(_context, _signalRService, missionLogger, _accessRoleService);
_robotModelService = new RobotModelService(_context);
_robotService = new RobotService(_context, robotServiceLogger, _robotModelService, _signalRService);
_robotService = new RobotService(_context, robotServiceLogger, _robotModelService, _signalRService, _accessRoleService);
_robotModelService = new RobotModelService(_context);
_robotControllerMock = new RobotControllerMock();
_isarServiceMock = new MockIsarService();
_installationService = new InstallationService(_context);
_installationService = new InstallationService(_context, _accessRoleService);
_defaultLocalisationPoseService = new DefaultLocalizationPoseService(_context);
_plantService = new PlantService(_context, _installationService);
_deckService = new DeckService(_context, _defaultLocalisationPoseService, _installationService, _plantService);
_areaService = new AreaService(_context, _installationService, _plantService, _deckService, _defaultLocalisationPoseService);
_plantService = new PlantService(_context, _installationService, _accessRoleService);
_deckService = new DeckService(_context, _defaultLocalisationPoseService, _installationService, _plantService, _accessRoleService);
_areaService = new AreaService(_context, _installationService, _plantService, _deckService, _defaultLocalisationPoseService, _accessRoleService);
_missionSchedulingService = new MissionSchedulingService(missionSchedulingServiceLogger, _missionRunService, _robotService, _robotControllerMock.Mock.Object, _areaService,
_isarServiceMock);

Expand Down Expand Up @@ -122,7 +125,7 @@ public async void ScheduledMissionStartedWhenSystemIsAvailable()
var plant = await _databaseUtilities.NewPlant(installation.InstallationCode);
var deck = await _databaseUtilities.NewDeck(installation.InstallationCode, plant.PlantCode);
var area = await _databaseUtilities.NewArea(installation.InstallationCode, plant.PlantCode, deck.Name);
var robot = await _databaseUtilities.NewRobot(RobotStatus.Available, area);
var robot = await _databaseUtilities.NewRobot(RobotStatus.Available, area, installation);
var missionRun = await _databaseUtilities.NewMissionRun(installation.InstallationCode, robot, area, false);

SetupMocksForRobotController(robot, missionRun);
Expand All @@ -143,7 +146,7 @@ public async void SecondScheduledMissionQueuedIfRobotIsBusy()
var plant = await _databaseUtilities.NewPlant(installation.InstallationCode);
var deck = await _databaseUtilities.NewDeck(installation.InstallationCode, plant.PlantCode);
var area = await _databaseUtilities.NewArea(installation.InstallationCode, plant.PlantCode, deck.Name);
var robot = await _databaseUtilities.NewRobot(RobotStatus.Available, area);
var robot = await _databaseUtilities.NewRobot(RobotStatus.Available, area, installation);
var missionRunOne = await _databaseUtilities.NewMissionRun(installation.InstallationCode, robot, area, false);
var missionRunTwo = await _databaseUtilities.NewMissionRun(installation.InstallationCode, robot, area, false);

Expand All @@ -168,7 +171,7 @@ public async void NewMissionIsStartedWhenRobotBecomesAvailable()
var plant = await _databaseUtilities.NewPlant(installation.InstallationCode);
var deck = await _databaseUtilities.NewDeck(installation.InstallationCode, plant.PlantCode);
var area = await _databaseUtilities.NewArea(installation.InstallationCode, plant.PlantCode, deck.Name);
var robot = await _databaseUtilities.NewRobot(RobotStatus.Busy, area);
var robot = await _databaseUtilities.NewRobot(RobotStatus.Busy, area, installation);
var missionRun = await _databaseUtilities.NewMissionRun(installation.InstallationCode, robot, area, false);

SetupMocksForRobotController(robot, missionRun);
Expand Down Expand Up @@ -205,7 +208,7 @@ public async void NoMissionIsStartedIfQueueIsEmptyWhenRobotBecomesAvailable()
var plant = await _databaseUtilities.NewPlant(installation.InstallationCode);
var deck = await _databaseUtilities.NewDeck(installation.InstallationCode, plant.PlantCode);
var area = await _databaseUtilities.NewArea(installation.InstallationCode, plant.PlantCode, deck.Name);
var robot = await _databaseUtilities.NewRobot(RobotStatus.Busy, area);
var robot = await _databaseUtilities.NewRobot(RobotStatus.Busy, area, installation);

var mqttEventArgs = new MqttReceivedArgs(
new IsarRobotStatusMessage
Expand Down Expand Up @@ -245,8 +248,8 @@ public async void MissionRunIsStartedForOtherAvailableRobotIfOneRobotHasAnOngoin
var plant = await _databaseUtilities.NewPlant(installation.InstallationCode);
var deck = await _databaseUtilities.NewDeck(installation.InstallationCode, plant.PlantCode);
var area = await _databaseUtilities.NewArea(installation.InstallationCode, plant.PlantCode, deck.Name);
var robotOne = await _databaseUtilities.NewRobot(RobotStatus.Available, area);
var robotTwo = await _databaseUtilities.NewRobot(RobotStatus.Available, area);
var robotOne = await _databaseUtilities.NewRobot(RobotStatus.Available, area, installation);
var robotTwo = await _databaseUtilities.NewRobot(RobotStatus.Available, area, installation);
var missionRunOne = await _databaseUtilities.NewMissionRun(installation.InstallationCode, robotOne, area, false);
var missionRunTwo = await _databaseUtilities.NewMissionRun(installation.InstallationCode, robotTwo, area, false);

Expand Down
40 changes: 40 additions & 0 deletions backend/api.test/Mocks/HttpContextAccessorMock.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;

namespace Api.Test.Mocks
{
public class MockHttpContextAccessor : IHttpContextAccessor
{
public HttpContext? HttpContext
{
get
{
var context = new DefaultHttpContext();
var tokenHandler = new JwtSecurityTokenHandler();
var claims = new List<Claim>
{
new(ClaimTypes.Role, "Role.Admin"),
new(ClaimTypes.Role, "Role.User"),
new(ClaimTypes.Role, "Role.User.JSV")
andchiind marked this conversation as resolved.
Show resolved Hide resolved
};

var rng = RandomNumberGenerator.Create();
byte[] key = new byte[32];
rng.GetBytes(key);
var securityKey = new SymmetricSecurityKey(key) { KeyId = Guid.NewGuid().ToString() };
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

string issuer = Guid.NewGuid().ToString();
string jwtToken = tokenHandler.WriteToken(new JwtSecurityToken(issuer, null, claims, null, DateTime.UtcNow.AddMinutes(20), signingCredentials));
context.Request.Headers.Authorization = jwtToken;
return context;
}
set { }
}
}
}
15 changes: 3 additions & 12 deletions backend/api.test/Mocks/SignalRServiceMock.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Threading.Tasks;
using Api.Database.Models;
namespace Api.Services
{
public class MockSignalRService : ISignalRService
Expand All @@ -7,22 +8,12 @@ public MockSignalRService()
{
}

public async Task SendMessageAsync<T>(string label, T messageObject)
public async Task SendMessageAsync<T>(string label, Installation? installation, T messageObject)
{
await Task.CompletedTask;
}

public async Task SendMessageAsync<T>(string label, string user, T messageObject)
{
await Task.CompletedTask;
}

public async Task SendMessageAsync(string label, string message)
{
await Task.CompletedTask;
}

public async Task SendMessageAsync(string label, string user, string message)
public async Task SendMessageAsync(string label, Installation? installation, string message)
{
await Task.CompletedTask;
}
Expand Down
7 changes: 5 additions & 2 deletions backend/api.test/Services/MissionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Api.Database.Models;
using Api.Services;
using Api.Test.Database;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;
Expand All @@ -18,13 +19,15 @@ public class MissionServiceTest : IDisposable
private readonly ILogger<MissionRunService> _logger;
private readonly MissionRunService _missionRunService;
private readonly ISignalRService _signalRService;
private readonly IAccessRoleService _accessRoleService;

public MissionServiceTest(DatabaseFixture fixture)
{
_context = fixture.NewContext;
_logger = new Mock<ILogger<MissionRunService>>().Object;
_signalRService = new MockSignalRService();
_missionRunService = new MissionRunService(_context, _signalRService, _logger);
_accessRoleService = new AccessRoleService(_context, new HttpContextAccessor());
_missionRunService = new MissionRunService(_context, _signalRService, _logger, _accessRoleService);
_databaseUtilities = new DatabaseUtilities(_context);
}

Expand Down Expand Up @@ -53,7 +56,7 @@ public async Task Create()
var plant = await _databaseUtilities.NewPlant(installation.InstallationCode);
var deck = await _databaseUtilities.NewDeck(installation.InstallationCode, plant.PlantCode);
var area = await _databaseUtilities.NewArea(installation.InstallationCode, plant.PlantCode, deck.Name);
var robot = await _databaseUtilities.NewRobot(RobotStatus.Available, area);
var robot = await _databaseUtilities.NewRobot(RobotStatus.Available, area, installation);
var missionRun = await _databaseUtilities.NewMissionRun(installation.InstallationCode, robot, area, false);

await _missionRunService.Create(missionRun);
Expand Down
21 changes: 16 additions & 5 deletions backend/api.test/Services/RobotService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Api.Database.Context;
using Api.Database.Models;
using Api.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;
Expand All @@ -18,13 +19,15 @@ public class RobotServiceTest : IDisposable
private readonly ILogger<RobotService> _logger;
private readonly RobotModelService _robotModelService;
private readonly ISignalRService _signalRService;
private readonly IAccessRoleService _accessRoleService;

public RobotServiceTest(DatabaseFixture fixture)
{
_context = fixture.NewContext;
_logger = new Mock<ILogger<RobotService>>().Object;
_robotModelService = new RobotModelService(_context);
_signalRService = new MockSignalRService();
_accessRoleService = new AccessRoleService(_context, new HttpContextAccessor());
}

public void Dispose()
Expand All @@ -36,7 +39,7 @@ public void Dispose()
[Fact]
public async Task ReadAll()
{
var robotService = new RobotService(_context, _logger, _robotModelService, _signalRService);
var robotService = new RobotService(_context, _logger, _robotModelService, _signalRService, _accessRoleService);
var robots = await robotService.ReadAll();

Assert.True(robots.Any());
Expand All @@ -45,7 +48,7 @@ public async Task ReadAll()
[Fact]
public async Task Read()
{
var robotService = new RobotService(_context, _logger, _robotModelService, _signalRService);
var robotService = new RobotService(_context, _logger, _robotModelService, _signalRService, _accessRoleService);
var robots = await robotService.ReadAll();
var firstRobot = robots.First();
var robotById = await robotService.ReadById(firstRobot.Id);
Expand All @@ -56,15 +59,23 @@ public async Task Read()
[Fact]
public async Task ReadIdDoesNotExist()
{
var robotService = new RobotService(_context, _logger, _robotModelService, _signalRService);
var robotService = new RobotService(_context, _logger, _robotModelService, _signalRService, _accessRoleService);
var robot = await robotService.ReadById("some_id_that_does_not_exist");
Assert.Null(robot);
}

[Fact]
public async Task Create()
{
var robotService = new RobotService(_context, _logger, _robotModelService, _signalRService);
var robotService = new RobotService(_context, _logger, _robotModelService, _signalRService, _accessRoleService);
var installationService = new InstallationService(_context, _accessRoleService);

var installation = await installationService.Create(new CreateInstallationQuery
{
Name = "Johan Sverdrup",
andchiind marked this conversation as resolved.
Show resolved Hide resolved
InstallationCode = "JSV"
});

var robotsBefore = await robotService.ReadAll();
int nRobotsBefore = robotsBefore.Count();
var videoStreamQuery = new CreateVideoStreamQuery
Expand All @@ -82,7 +93,7 @@ public async Task Create()
{
videoStreamQuery
},
CurrentInstallation = "",
CurrentInstallation = installation,
RobotType = RobotType.Robot,
Host = "",
Port = 1,
Expand Down
3 changes: 3 additions & 0 deletions backend/api.test/TestWebApplicationFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Api.Test.Mocks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
Expand All @@ -28,7 +29,9 @@ protected override void ConfigureWebHost(IWebHostBuilder builder)
builder.ConfigureTestServices(
services =>
{
services.AddScoped<IAccessRoleService, AccessRoleService>();
services.AddScoped<IIsarService, MockIsarService>();
services.AddScoped<IHttpContextAccessor, MockHttpContextAccessor>();
services.AddScoped<IEchoService, MockEchoService>();
services.AddScoped<IMapService, MockMapService>();
services.AddScoped<IBlobService, MockBlobService>();
Expand Down
2 changes: 1 addition & 1 deletion backend/api/Controllers/Models/CreateRobotQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public struct CreateRobotQuery

public string SerialNumber { get; set; }

public string CurrentInstallation { get; set; }
public Installation CurrentInstallation { get; set; }

public Area CurrentArea { get; set; }

Expand Down
2 changes: 1 addition & 1 deletion backend/api/Controllers/Models/RobotResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class RobotResponse

public string SerialNumber { get; set; }

public string CurrentInstallation { get; set; }
public Installation? CurrentInstallation { get; }

public AreaResponse? CurrentArea { get; set; }

Expand Down
1 change: 1 addition & 0 deletions backend/api/Database/Context/FlotillaDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public class FlotillaDbContext(DbContextOptions options) : DbContext(options)
public DbSet<Source> Sources => Set<Source>();
public DbSet<SafePosition> SafePositions => Set<SafePosition>();
public DbSet<DefaultLocalizationPose> DefaultLocalizationPoses => Set<DefaultLocalizationPose>();
public DbSet<AccessRole> AccessRoles => Set<AccessRole>();

// Timeseries:
public DbSet<RobotPressureTimeseries> RobotPressureTimeseries => Set<RobotPressureTimeseries>();
Expand Down
Loading
Loading