using HyperBooru.Services; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Cryptography.KeyDerivation; using Microsoft.AspNetCore.Mvc; using System.Security.Claims; namespace HyperBooru.Controllers; [ApiController] [Route("/")] public class LoginController : Controller { private IHttpContextAccessor httpContextAccessor; public LoginController(IHttpContextAccessor httpContextAccessor) => this.httpContextAccessor = httpContextAccessor; [HttpPost("Login")] public async Task Login( [FromForm] string username, [FromForm] string password, HBContext db) { var user = db.Users.FirstOrDefault(u => u.Name == username); if(user is null) return StatusCode(403); var hash = UserService.HashPassword(password); if(hash != user.PasswordHash) return StatusCode(403); var claims = new Claim[] { new Claim(ClaimTypes.Name, user.Name), new Claim("ObjectId", user.ObjectId.ToString()) }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); await httpContextAccessor.HttpContext!.SignInAsync(claimsPrincipal); return Ok(); } [HttpPost("Logout")] public async Task Logout() => await httpContextAccessor.HttpContext!.SignOutAsync(); }