Skip to content

Commit 07e0cca

Browse files
committed
code redactored with auth: Integration test fixing
1 parent 3df8f74 commit 07e0cca

33 files changed

+152
-131
lines changed

src/Api.Test/EndpointsTests/IntegrationTests/ProductControllerTest.cs

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,16 @@
1-
using Newtonsoft.Json;
1+
using Microsoft.AspNetCore.Authentication;
2+
using Microsoft.AspNetCore.TestHost;
3+
using Microsoft.Extensions.DependencyInjection;
4+
using Microsoft.Extensions.Logging;
5+
using Microsoft.Extensions.Options;
6+
using Newtonsoft.Json;
27
using System;
38
using System.Collections.Generic;
49
using System.Linq;
10+
using System.Net.Http.Headers;
511
using System.Net.Http.Json;
12+
using System.Security.Claims;
13+
using System.Text.Encodings.Web;
614
using System.Threading.Tasks;
715
using Xero.Demo.Api.Domain;
816
using Xero.Demo.Api.Domain.Models;
@@ -12,6 +20,24 @@
1220

1321
namespace Xero.Demo.Api.Tests.EndpointTests.IntegrationTests
1422
{
23+
public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
24+
{
25+
public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
26+
: base(options, logger, encoder, clock) { }
27+
28+
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
29+
{
30+
var claims = new[] { new Claim(ClaimTypes.Role, CONSTANTS.Roles.Reader) };
31+
var identity = new ClaimsIdentity(claims, "Test");
32+
var principal = new ClaimsPrincipal(identity);
33+
var ticket = new AuthenticationTicket(principal, "Test");
34+
35+
var result = AuthenticateResult.Success(ticket);
36+
37+
return Task.FromResult(result);
38+
}
39+
}
40+
1541
[Trait("Category", "Integration")]
1642
public class ProductControllerTest : IDisposable
1743
{
@@ -28,7 +54,17 @@ public ProductControllerTest()
2854
public async Task GetAsync_Returns_200(string culture, string version)
2955
{
3056
// Given
31-
var client = factory.CreateClient();
57+
var client = factory.WithWebHostBuilder(builder =>
58+
{
59+
builder.ConfigureTestServices(services =>
60+
{
61+
services.AddAuthentication("Test")
62+
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
63+
"Test", options => { });
64+
});
65+
})
66+
.CreateClient();
67+
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Test");
3268

3369
// When
3470
var response = await client.GetAsync(string.Format(SampleDataV1.productEndpoint, culture, version));

src/Api.Test/Setup/SetupStartup.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ protected override void ConfigureWebHost(IWebHostBuilder builder)
2222
services.Remove(descriptor);
2323

2424
services.AddDbContext<Database>(options => options.UseInMemoryDatabase("TestDB"));
25-
//services.AddSingleton<IDatabase>(provider => provider.GetService<Database>());
2625

2726
var sp = services.BuildServiceProvider();
2827

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
using Microsoft.AspNetCore.Mvc;
2+
using Xero.Demo.Api.Domain;
3+
using Xero.Demo.Api.Domain.Extension;
4+
using Xero.Demo.Api.Xero.Demo.Domain.Services;
5+
using static Xero.Demo.Api.Domain.Models.CONSTANTS;
6+
7+
namespace Xero.Demo.Api.Endpoints.Common
8+
{
9+
[ApiVersion(ApiVersionNumbers.V1)]
10+
[ApiVersion(ApiVersionNumbers.V2)]
11+
public class LoginController : BaseApiController
12+
{
13+
private readonly IUserService _userService;
14+
15+
public LoginController(IUserService userService)
16+
{
17+
_userService = userService;
18+
}
19+
20+
[HttpPost(Roles.Admin)]
21+
public IActionResult AuthenticateAdmin(string culture = "en-US")
22+
{
23+
var response = _userService.Authenticate(Roles.Admin);
24+
25+
if (response == null) return BadRequest(ModelState.GetErrorMessages());
26+
27+
return Ok(response);
28+
}
29+
30+
[HttpPost(Roles.Editor)]
31+
public IActionResult AuthenticateEditor(string culture = "en-US")
32+
{
33+
var response = _userService.Authenticate(Roles.Editor);
34+
35+
if (response == null) return BadRequest(ModelState.GetErrorMessages());
36+
37+
return Ok(response);
38+
}
39+
40+
[HttpPost(Roles.Reader)]
41+
public IActionResult AuthenticateReader(string culture = "en-US")
42+
{
43+
var response = _userService.Authenticate(Roles.Reader);
44+
45+
if (response == null) return BadRequest(ModelState.GetErrorMessages());
46+
47+
return Ok(response);
48+
}
49+
}
50+
}

src/Api/Endpoints/Common/UsersController.cs

Lines changed: 0 additions & 30 deletions
This file was deleted.

src/Api/Endpoints/V1/Products/Create.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public ProductsController(Database db)
2626
/// <param name="product">Enter the product</param>
2727
/// <param name="culture">Enter the culture</param>
2828
/// <returns></returns>
29-
[Authorize(Policy = "ShouldBeAnAdmin")]
29+
[Authorize(Policy = Policy.ShouldBeAnAdmin)]
3030
[FeatureGate(Features.PRODUCT)]
3131
[ApiVersion(ApiVersionNumbers.V1)]
3232
[HttpPost("", Name = RouteNames.PostAsync)]

src/Api/Endpoints/V1/Products/Delete.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public partial class ProductsController
1919
/// <param name="id">Enter the product id</param>
2020
/// <param name="culture"></param>
2121
/// <returns></returns>
22-
[Authorize(Policy = "ShouldBeAnAdmin")]
22+
[Authorize(Policy = Policy.ShouldBeAnAdmin)]
2323
[ApiVersion(ApiVersionNumbers.V1)]
2424
[HttpDelete("{id}", Name = RouteNames.DeleteAsync)]
2525
[ProducesResponseType(StatusCodes.Status204NoContent)]

src/Api/Endpoints/V1/Products/Read.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,16 @@ public partial class ProductsController
1818
/// List of products.
1919
/// </summary>
2020
/// <returns>Returns list of products</returns>
21-
[Authorize(Policy = "ShouldBeAReader")]
21+
[Authorize(Policy = Policy.ShouldBeAReader)]
2222
[ApiVersion(ApiVersionNumbers.V1)]
2323
[HttpGet("", Name = RouteNames.GetAsync)]
2424
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(List<ProductDTO>))]
2525
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
2626
public async Task<IActionResult> GetAsync(string culture = "en-US")
2727
{
28+
// ### START ::: The localization can be accessed.
2829
//var language = AddLocalizationExtension._e[WELCOME];
29-
//_logger.LogInformation(string.Format(AddLocalizationExtension._e[WELCOME].Value));
30+
// ### END ::: The localization can be accessed.
3031

3132
var products = await _db.Products.AsQueryable().ToListAsync();
3233

@@ -46,7 +47,7 @@ public async Task<IActionResult> GetAsync(string culture = "en-US")
4647
/// </summary>
4748
/// <param name="id">Enter the id of product</param>
4849
/// <returns>Returns list of products</returns>
49-
[Authorize(Policy = "ShouldBeAReader")]
50+
[Authorize(Policy = Policy.ShouldBeAReader)]
5051
[ApiVersion(ApiVersionNumbers.V1)]
5152
[HttpGet("{id}", Name = RouteNames.GetByIdAsync)]
5253
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ProductDTO))]

src/Api/Endpoints/V1/Products/Update.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public partial class ProductsController
1818
/// <param name="product">Enter the product</param>
1919
/// <param name="culture"></param>
2020
/// <returns></returns>
21-
[Authorize(Policy = "ShouldBeAReader")]
21+
[Authorize(Policy = Policy.ShouldBeAnEditor)]
2222
[ApiVersion(ApiVersionNumbers.V1)]
2323
[HttpPut("{id}", Name = RouteNames.PutAsync)]
2424
[ProducesResponseType(StatusCodes.Status204NoContent)]

src/Api/Product.db

0 Bytes
Binary file not shown.

src/Api/Program.cs

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,6 @@ public static async Task Main(string[] args)
1414
{
1515
var webHost = CreateHostBuilder(args).Build();
1616

17-
using (var scope = webHost.Services.CreateScope())
18-
{
19-
var context = scope.ServiceProvider.GetRequiredService<Database>();
20-
21-
var productCount = await context.Products.CountAsync();
22-
if (context != null && context.Database != null && productCount == 0)
23-
await context.Database.MigrateAsync();
24-
}
2517
await webHost.RunAsync();
2618
}
2719

0 commit comments

Comments
 (0)