From 3bf91892f60fb80731cc76ae7ac9fac7ad23b7a9 Mon Sep 17 00:00:00 2001 From: jessikitty Date: Thu, 21 May 2026 13:54:59 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20Add=20authentication=20=E2=80=94=20Acco?= =?UTF-8?q?untController=20with=20cookie=20auth=20login/logout?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Controllers/AccountController.cs | 63 ++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Controllers/AccountController.cs diff --git a/Controllers/AccountController.cs b/Controllers/AccountController.cs new file mode 100644 index 0000000..4598150 --- /dev/null +++ b/Controllers/AccountController.cs @@ -0,0 +1,63 @@ +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Mvc; +using System.Security.Claims; + +namespace NoticeBoard.Controllers; + +public class AccountController : Controller +{ + private readonly IConfiguration _config; + + public AccountController(IConfiguration config) + { + _config = config; + } + + [HttpGet] + public IActionResult Login(string? returnUrl = null) + { + if (User.Identity?.IsAuthenticated == true) + return RedirectToAction("Index", "Admin"); + + ViewBag.ReturnUrl = returnUrl; + return View(); + } + + [HttpPost] + public async Task Login(string username, string password, string? returnUrl = null) + { + var adminUser = _config["Admin:Username"] ?? "admin"; + var adminPass = _config["Admin:Password"] ?? "admin"; + + if (username == adminUser && password == adminPass) + { + var claims = new List + { + new Claim(ClaimTypes.Name, username), + new Claim(ClaimTypes.Role, "Admin") + }; + + var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); + var principal = new ClaimsPrincipal(identity); + + await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); + + if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl)) + return Redirect(returnUrl); + + return RedirectToAction("Index", "Admin"); + } + + ViewBag.Error = "Invalid username or password."; + ViewBag.ReturnUrl = returnUrl; + return View(); + } + + [HttpGet] + public async Task Logout() + { + await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + return RedirectToAction("Login"); + } +}