// EN: Custom authentication handler for functional tests.
// VI: Authentication handler tùy chỉnh cho functional tests.
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace OrderService.FunctionalTests;
///
/// EN: Test authentication handler that creates a fake authenticated user with configurable claims.
/// VI: Authentication handler test tạo user authenticated giả với claims có thể cấu hình.
///
public class TestAuthHandler : AuthenticationHandler
{
///
/// EN: Authentication scheme name used in tests.
/// VI: Tên scheme xác thực sử dụng trong tests.
///
public const string SchemeName = "TestScheme";
///
/// EN: Default test user ID.
/// VI: User ID test mặc định.
///
public static readonly Guid TestUserId = Guid.Parse("11111111-1111-1111-1111-111111111111");
///
/// EN: Default test merchant ID.
/// VI: Merchant ID test mặc định.
///
public static readonly Guid TestMerchantId = Guid.Parse("22222222-2222-2222-2222-222222222222");
///
/// EN: Default test shop ID.
/// VI: Shop ID test mặc định.
///
public static readonly Guid TestShopId = Guid.Parse("33333333-3333-3333-3333-333333333333");
public TestAuthHandler(
IOptionsMonitor options,
ILoggerFactory logger,
UrlEncoder encoder)
: base(options, logger, encoder)
{
}
protected override Task HandleAuthenticateAsync()
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, TestUserId.ToString()),
new Claim("sub", TestUserId.ToString()),
new Claim("merchant_id", TestMerchantId.ToString()),
new Claim("shop_id", TestShopId.ToString()),
new Claim(ClaimTypes.Role, "admin"),
new Claim("role", "admin"),
};
var identity = new ClaimsIdentity(claims, SchemeName);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, SchemeName);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}