Skip to content

Commit

Permalink
Manage unknown user creating stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
ludo committed Mar 7, 2023
1 parent 2f7643c commit 2d46512
Show file tree
Hide file tree
Showing 9 changed files with 45 additions and 50 deletions.
2 changes: 1 addition & 1 deletion Server.UnitTest/Server.UnitTest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

<ItemGroup>
<PackageReference Include="coverlet.msbuild" Version="3.2.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageReference Include="Moq" Version="4.18.4" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" />
Expand Down
48 changes: 20 additions & 28 deletions Server.UnitTest/Services/TestStuffService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,15 @@ public class TestStuffService
StfCreatedAt = DateTime.UtcNow.ToString("o")
};

private readonly SqliteConnection _connection;
private readonly StuffDbContext _dbContext;
private readonly IStuffService _stuffService;

public TestStuffService()
{
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open();
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<StuffDbContext>()
.UseSqlite(_connection)
.UseSqlite(connection)
.Options;
_dbContext = new StuffDbContext(options);
_dbContext.Database.EnsureCreated();
Expand All @@ -71,13 +70,6 @@ public TestStuffService()
_stuffService = new StuffService(_dbContext, mockHttpCtx);
}

[Fact]
public void Dispose()
{
_dbContext.Dispose();
_connection.Close();
}

// ***** ***** ***** LIST
[Fact]
public async Task StuffService_GetListAsync_ShouldReturn_Ok()
Expand Down Expand Up @@ -164,38 +156,38 @@ public async Task StuffService_SearchListAsync_ShouldThrow_ArgumentException()
[Fact]
public async Task StuffService_CreateAsync_ShouldReturn_Ok()
{
// Arrange1
// Arrange
// Existing user
_dbContext.Add(_dbUser);
await _dbContext.SaveChangesAsync();

// Act1
// Act
var serviceResult = await _stuffService.CreateAsync(DatumModelTest);

// Assert1
// Assert
int actual = serviceResult.Id.Count(x => x == '-');
int expected = 4;
Assert.Equal(expected, actual);
}

// ***
// Arrange2
// Creating user at the same time as stuff
DatumModelTest.User = null;

// Act2
serviceResult = await _stuffService.CreateAsync(DatumModelTest);
[Fact]
public async Task StuffService_CreateAsync_Without_User_ShouldThrow_KeyNotFoundException()
{
// Arrange
// No user in DB

// Assert2
actual = serviceResult.Id.Count(x => x == '-');
expected = 4;
Assert.Equal(expected, actual);
// Act
var serviceResult = _stuffService.CreateAsync(DatumModelTest);
var exception = await Record.ExceptionAsync(() => serviceResult);

// Restore
DatumModelTest.User = TestUserModel;
// Assert
Assert.NotNull(exception);
Assert.IsType<KeyNotFoundException>(exception);
Assert.Equal("User not found.", exception.Message);
}

[Fact]
public async Task StuffService_CreateAsync_ShouldReturn_ArgumentException()
public async Task StuffService_CreateAsync_ShouldThrow_ArgumentException()
{
// Arrange
DatumModelTest.Label = string.Empty;
Expand Down
10 changes: 7 additions & 3 deletions Server.UnitTest/Shared/TestErrorController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Moq;
using Server.Shared;
using Xunit;
Expand All @@ -15,6 +16,7 @@ public void ErrorController_NotFoundObjectResult()
{
// Arrange
var mockEnv = Mock.Of<IHostEnvironment>();
var mockLogger = Mock.Of<ILogger<ErrorController>>();
var mockException = Mock.Of<IExceptionHandlerFeature>(x => x.Error == new KeyNotFoundException("Not found"));

var context = new DefaultHttpContext();
Expand All @@ -26,7 +28,7 @@ public void ErrorController_NotFoundObjectResult()
};

// Act
IActionResult actionResult = controller.Error(mockEnv);
IActionResult actionResult = controller.Error(mockEnv, mockLogger);

// Assert
var notFoundResult = Assert.IsType<NotFoundObjectResult>(actionResult);
Expand All @@ -40,6 +42,7 @@ public void ErrorHandlerFilter_BadRequestObjectResult_Development()
{
// Arrange
var mockEnv = Mock.Of<IHostEnvironment>(x => x.EnvironmentName == "Development");
var mockLogger = Mock.Of<ILogger<ErrorController>>();
var mockException = Mock.Of<IExceptionHandlerFeature>(x => x.Error == new ArgumentException("Should be displayed"));

var context = new DefaultHttpContext();
Expand All @@ -51,7 +54,7 @@ public void ErrorHandlerFilter_BadRequestObjectResult_Development()
};

// Act
IActionResult actionResult = controller.Error(mockEnv);
IActionResult actionResult = controller.Error(mockEnv, mockLogger);

// Assert
var notFoundResult = Assert.IsType<BadRequestObjectResult>(actionResult);
Expand All @@ -65,6 +68,7 @@ public void ErrorHandlerFilter_BadRequestObjectResult_Production()
{
// Arrange
var mockEnv = Mock.Of<IHostEnvironment>(x => x.EnvironmentName == "Production");
var mockLogger = Mock.Of<ILogger<ErrorController>>();
var mockException = Mock.Of<IExceptionHandlerFeature>(x => x.Error == new ArgumentException("Should not be displayed"));

var context = new DefaultHttpContext();
Expand All @@ -76,7 +80,7 @@ public void ErrorHandlerFilter_BadRequestObjectResult_Production()
};

// Act
IActionResult actionResult = controller.Error(mockEnv);
IActionResult actionResult = controller.Error(mockEnv, mockLogger);

// Assert
var notFoundResult = Assert.IsType<BadRequestObjectResult>(actionResult);
Expand Down
6 changes: 3 additions & 3 deletions Server/Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
</None>
<PackageReference Include="IdentityModel" Version="6.0.0" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.13" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.13" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.14" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.14" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.14" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>

Expand Down
6 changes: 2 additions & 4 deletions Server/Services/StuffService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,8 @@ public async Task<DatumModel> CreateAsync(DatumModel input)
UserModel userAuth = _httpContext.HttpContext.GetCurrentUser();
TUser dbUser = await _dbContext.TUsers.FirstOrDefaultAsync(x => x.UsrId == userAuth.Id);
if (dbUser == null)
{ // Create and attach new user
dbUser.UsrCreatedAt = DateTime.UtcNow.ToStrDate();
dbStuff.StfUser = dbUser;
{
throw new KeyNotFoundException("User not found.");
}

// Attach foreign key
Expand All @@ -95,7 +94,6 @@ public async Task<DatumModel> ReadAsync(string stuffId)
.Where(x => x.StfId == stuffId)
.Include(x => x.StfUser)
.FirstOrDefaultAsync();

if (dbStuff == null)
{
throw new KeyNotFoundException("Stuff not found.");
Expand Down
3 changes: 2 additions & 1 deletion Server/Shared/ErrorController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace Server.Shared;
[ApiExplorerSettings(IgnoreApi = true)]
public class ErrorController : ControllerBase
{
public IActionResult Error([FromServices] IHostEnvironment env)
public IActionResult Error([FromServices] IHostEnvironment env, [FromServices] ILogger<ErrorController> logger)
{
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
if (context == null)
Expand All @@ -16,6 +16,7 @@ public IActionResult Error([FromServices] IHostEnvironment env)
}

var exception = context.Error;
logger.LogCritical(exception, "API_ERROR");
var msg = exception.InnerException == null
? exception.Message
: exception.InnerException.Message;
Expand Down
14 changes: 7 additions & 7 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"preview": "vite preview"
},
"devDependencies": {
"@axa-fr/vanilla-oidc": "^6.15.2",
"@axa-fr/vanilla-oidc": "^6.15.5",
"@sveltejs/vite-plugin-svelte": "^2.0.2",
"axios": "^1.2.2",
"bootstrap": "^5.2.3",
Expand Down
4 changes: 2 additions & 2 deletions client/src/lib/const.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ export const configuration = {
silent_redirect_uri: window.location.origin + "/authentication/silent-callback",
scope: "openid profile email api offline_access",
authority: "https://demo.duendesoftware.com",
service_worker_relative_url: "/OidcServiceWorker.js",
// service_worker_relative_url: "/OidcServiceWorker.js",
service_worker_only: false,
monitor_session: true
monitor_session: false
};

export const apiErrMsg = {
Expand Down

0 comments on commit 2d46512

Please sign in to comment.