2026-11-14 10:11:12 +00:00
using System.Text.RegularExpressions ;
using Bifrost.Web.Features.Shared ;
using Bifrost.Web.Tests.Support ;
namespace Bifrost.Web.Tests.Support ;
/// <summary>The merge status page as a browser uses it: a GET with the session, a POST with the antiforgery pair the page itself handed out.</summary>
internal static class MergePage
{
public const string Url = "/Membership/MergeStatus" ;
2026-11-14 10:27:22 +00:00
public const string AccountsUrl = "/Membership/MergeAccounts" ;
2026-11-14 10:11:12 +00:00
public sealed record Antiforgery ( string Token , string Cookie ) ;
2026-11-14 10:27:22 +00:00
public static async Task < ( HttpResponseMessage Response , string Html ) > GetAsync ( HeimdallHost host , string session , string query = "" , string url = Url )
2026-11-14 10:11:12 +00:00
{
using var client = host . NewClient ( ) ;
2026-11-14 10:27:22 +00:00
using var request = new HttpRequestMessage ( HttpMethod . Get , url + query ) ;
2026-11-14 10:11:12 +00:00
request . Headers . Add ( "Cookie" , $"{BifrostCookies.Session}={session}" ) ;
var response = await client . SendAsync ( request ) ;
return ( response , await response . Content . ReadAsStringAsync ( ) ) ;
}
/// <summary>The antiforgery pair from a page of this member that carries a form.</summary>
2026-11-14 10:27:22 +00:00
public static async Task < Antiforgery > TokenAsync ( HeimdallHost host , string session , string url = Url )
2026-11-14 10:11:12 +00:00
{
2026-11-14 10:27:22 +00:00
var ( response , html ) = await GetAsync ( host , session , "" , url ) ;
2026-11-14 10:11:12 +00:00
var token = Regex . Match ( html , "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"" ) . Groups [ 1 ] . Value ;
Assert . NotEmpty ( token ) ;
return new Antiforgery ( token , HeimdallHost . CookieValue ( response , BifrostCookies . Antiforgery ) ! ) ;
}
public static async Task < HttpResponseMessage > PostAsync (
2026-11-14 10:27:22 +00:00
HeimdallHost host , string session , Antiforgery antiforgery , string handler , IDictionary < string , string > form , string url = Url )
2026-11-14 10:11:12 +00:00
{
using var client = host . NewClient ( ) ;
var fields = new Dictionary < string , string > ( form ) { [ "__RequestVerificationToken" ] = antiforgery . Token } ;
2026-11-14 10:27:22 +00:00
using var request = new HttpRequestMessage ( HttpMethod . Post , $"{url}?handler={handler}" ) { Content = new FormUrlEncodedContent ( fields ) } ;
2026-11-14 10:11:12 +00:00
request . Headers . Add ( "Cookie" , $"{BifrostCookies.Session}={session}; {BifrostCookies.Antiforgery}={antiforgery.Cookie}" ) ;
return await client . SendAsync ( request ) ;
}
public static string? Location ( HttpResponseMessage response ) = > response . Headers . Location ? . OriginalString ;
}