summaryrefslogtreecommitdiff
path: root/Controllers
diff options
context:
space:
mode:
Diffstat (limited to 'Controllers')
-rw-r--r--Controllers/LoginController.cs50
1 files changed, 50 insertions, 0 deletions
diff --git a/Controllers/LoginController.cs b/Controllers/LoginController.cs
new file mode 100644
index 0000000..b01553c
--- /dev/null
+++ b/Controllers/LoginController.cs
@@ -0,0 +1,50 @@
+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<IActionResult> Login(
+ [FromForm] string username,
+ [FromForm] string password,
+ HBContext db) {
+
+ var user = db.Users.FirstOrDefault(u => u.Username == 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.Username),
+ 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();
+}