jerguero-cs/Pages/Login.cshtml.cs

80 lines
2.1 KiB
C#
Raw Normal View History

2024-08-24 16:45:34 +00:00
using System.Security.Claims;
using Jerguero.Model;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Jerguero.Pages;
public class LoginModel(ILogger<LoginModel> logger) : PageModel
{
private readonly ILogger<LoginModel> _logger = logger;
[BindProperty]
public Person LoginPerson { get; set; } = default!;
public string RedirectUrl = "/";
public IActionResult OnGet(string? redirect)
{
RedirectUrl = redirect ?? "/";
if (User.Identity?.IsAuthenticated == true)
{
return LocalRedirect(redirect ?? "/");
}
return Page();
}
public async Task<IActionResult> OnPostAsync(string? redirect)
{
_logger.LogInformation($"Got `{redirect}` as redirect param");
if (!ModelState.IsValid || LoginPerson == null)
{
return Page();
}
// login
var loginCorrect = await AuthenticateUser(LoginPerson.Email, LoginPerson.Password);
if (!loginCorrect)
{
ModelState.AddModelError(string.Empty, "Credenciales inválidos");
return Page();
}
var claims = new List<Claim>
{
new(ClaimTypes.Name, LoginPerson.Email),
new(ClaimTypes.Role, "User"),
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
new AuthenticationProperties { }
);
return LocalRedirect(redirect ?? "/");
}
private async Task<bool> AuthenticateUser(string email, string password)
{
_logger.LogInformation("Authenticating: {}", new { Email = email, Password = password });
await Task.Delay(1000);
if (email == "a@b.c")
{
return true;
}
else
{
return false;
}
}
}