PlotDirector/PlotLine/Services/WritingSolverResultContext.cs

46 lines
2.6 KiB
C#

using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Caching.Memory;
using PlotLine.Models.WritingSolver;
namespace PlotLine.Services;
// Only an opaque browser identifier leaves the server. Context expires absolutely,
// is bound to the signed-in subject, and is disposable on restart or graph change.
public sealed class WritingSolverResultContext(IMemoryCache cache)
{
private const string Cookie = "pd-solver-result";
private static readonly TimeSpan Lifetime = TimeSpan.FromHours(2);
private sealed record Entry(string Version, SolverAnswer[] Answers);
private static string? Token(HttpContext context) => context.Request.Cookies[Cookie] is { Length: 64 } token
&& token.All(Uri.IsHexDigit) ? token : null;
private static string Key(HttpContext context, string token, string slug)
{
var identity = context.User.Identity?.IsAuthenticated == true
? "user:" + context.User.FindFirstValue(ClaimTypes.NameIdentifier) + ":" + context.User.Identity.AuthenticationType
: "anonymous";
return "solver-result:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token + "|" + identity + "|" + slug)));
}
public void Save(HttpContext context, SolverGraph graph, SolverOutcome outcome, string slug)
{
if (context.User.Identity?.IsAuthenticated == true && string.IsNullOrEmpty(context.User.FindFirstValue(ClaimTypes.NameIdentifier))) return;
var token = Token(context) ?? Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
context.Response.Cookies.Append(Cookie, token, new CookieOptions
{
HttpOnly = true, Secure = context.Request.IsHttps, SameSite = SameSiteMode.Lax,
Path = "/writing-problems", MaxAge = Lifetime, IsEssential = true
});
cache.Set(Key(context, token, slug), new Entry(graph.Version,
outcome.Answers.Select(a => new SolverAnswer(a.Node, a.Choices.ToArray())).ToArray()), Lifetime);
}
public SolverOutcome? Read(HttpContext context, SolverGraph graph, string slug)
{
if (context.User.Identity?.IsAuthenticated == true && string.IsNullOrEmpty(context.User.FindFirstValue(ClaimTypes.NameIdentifier))) return null;
var token = Token(context);
if (token is null || !cache.TryGetValue<Entry>(Key(context, token, slug), out var entry)
|| entry is null || entry.Version != graph.Version) return null;
var outcome = WritingSolverEngine.Evaluate(graph, entry.Answers);
return outcome.Next is null && outcome.Reassurance is null && outcome.Solutions.FirstOrDefault()?.Slug == slug ? outcome : null;
}
}