Files
Htmx/Htmx.ApiDemo/Templates/Login.htmx.routing.cs
T

65 lines
2.1 KiB
C#

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Antiforgery;
using Htmx.ApiDemo.Templates;
using Htmx.ApiDemo.Data;
using Microsoft.AspNetCore.Mvc;
namespace Htmx.ApiDemo;
public static partial class RouteMap
{
private static void GetLogin(WebApplication app)
=> app.MapGet("/login", (IHttpContextAccessor contextAccessor, IAntiforgery antiforgery) =>
{
var context = contextAccessor.HttpContext
?? throw new InvalidOperationException("HttpContext is not available.");
if (context.User.Identity?.IsAuthenticated == true)
{
context.Response.Redirect("/");
return;
}
var afToken = antiforgery.GetAndStoreTokens(context).RequestToken;
var loginComponent = new Login(afToken: afToken);
loginComponent.HtmxAwareWriteToBody(
context: context,
title: "Login",
appName: "HtmxApp",
pageTitle: "Welcome back"
);
});
private static void PostLogin(WebApplication app)
=> app.MapPost("/login", async ValueTask
(
[FromForm] string email,
[FromForm] string password,
[FromServices] IHttpContextAccessor httpContextAccessor,
[FromServices] IAntiforgery antiforgery,
[FromServices] AppAuthService authService
) =>
{
var context = httpContextAccessor.HttpContext
?? throw new InvalidOperationException("HttpContext is not available.");
var afToken = antiforgery.GetAndStoreTokens(context).RequestToken;
var (success, error) = await authService.LoginAsync(email, password);
if (success)
{
context.Response.Redirect("/");
return;
}
var loginComponent = new Login(error, afToken: afToken);
loginComponent.HtmxAwareWriteToBody(
context: context,
title: "Login",
appName: "HtmxApp",
pageTitle: "Welcome back"
);
});
}