@page
@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;
@model LoginModel
Jerguero
¡Iniciá sesión para comenzar a crear definiciones!
@section Scripts {
}
@functions {
public class LoginModel(ILogger logger) : PageModel
{
private readonly ILogger _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 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
{
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 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;
}
}
}
}