80 lines
2.6 KiB
C#

using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using EnotaryoPH.Data;
using EnotaryoPH.Web.Common.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
namespace EnotaryoPH.Web.Pages
{
public class LoginModel : PageModel
{
private readonly NotaryoDBContext _notaryoDBContext;
private readonly IPasswordService _passwordService;
public LoginModel(IPasswordService passwordService, NotaryoDBContext notaryoDBContext)
{
_passwordService = passwordService;
_notaryoDBContext = notaryoDBContext;
}
public async Task<IActionResult> OnGetAsync() => Page();
public async Task<IActionResult> OnGetLogoutAsync()
{
await HttpContext.SignOutAsync();
return RedirectToPage("/Login");
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = _notaryoDBContext.Users.FirstOrDefault(u => EF.Functions.Like(u.Email, Email));
if (user == null)
{
ModelState.AddModelError("", "Invalid Email or Password");
return Page();
}
if (!_passwordService.VerifyHashedPassword(user.PasswordHash, Password))
{
ModelState.AddModelError("", "Invalid Email or Password");
return Page();
}
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, user.User_UID.ToString()),
new(ClaimTypes.Name, user.Email),
new(ClaimTypes.Email, user.Email),
new(ClaimTypes.Role, user.Role!)
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties();
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
return RedirectToPage("/Principal/Dashboard/Dashboard");
}
[Required]
[EmailAddress]
[BindProperty]
public string Email { get; set; }
[Required]
[BindProperty]
public string Password { get; set; }
}
}