Added basic authentication and localization
This commit is contained in:
65
src/Server/Controllers/AccountController.cs
Normal file
65
src/Server/Controllers/AccountController.cs
Normal 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");
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ public class HomeController : Controller
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[Authorize]
|
||||
[HttpGet("/")]
|
||||
public IActionResult Index()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user