Added basic authentication and localization

This commit is contained in:
2025-12-14 11:38:32 +01:00
parent 78f52faf46
commit c56b8a7f32
9 changed files with 184 additions and 7 deletions

View File

@@ -0,0 +1,65 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Server.Models;
namespace Server.Controllers;
[Route("[Controller]")]
public class AccountController : Controller
{
private readonly SimpleAuthOptions _options;
public AccountController(IOptions<SimpleAuthOptions> options)
{
_options = options.Value;
}
[HttpGet("Login")]
public IActionResult Login(string? returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost("Login")]
public async Task<IActionResult> Login(
string username,
string password,
string? returnUrl = null)
{
var user = _options.Users.SingleOrDefault(u =>
u.Username == username && u.Password == password);
if (user == null)
{
ModelState.AddModelError("", "Invalid credentials");
return View();
}
var claims = new List<Claim>
{
new(ClaimTypes.Name, user.Username)
};
claims.AddRange(user.Roles.Select(r =>
new Claim(ClaimTypes.Role, r)));
var identity = new ClaimsIdentity(
claims, "AppCookie");
await HttpContext.SignInAsync(
"AppCookie",
new ClaimsPrincipal(identity));
return Redirect(returnUrl ?? "/");
}
[HttpGet("Logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync("AppCookie");
return RedirectToAction("Login");
}
}

View File

@@ -16,6 +16,7 @@ public class HomeController : Controller
_logger = logger;
}
[Authorize]
[HttpGet("/")]
public IActionResult Index()
{