60 lines
1.8 KiB
C#
60 lines
1.8 KiB
C#
using System.Security.Claims;
|
|
using GhostImageManager.Models;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
|
|
namespace GhostImageManager.Services;
|
|
|
|
public class AuthService
|
|
{
|
|
private readonly AppSettings _appSettings;
|
|
private readonly ILogger<AuthService> _logger;
|
|
|
|
public AuthService(IConfiguration configuration, ILogger<AuthService> logger)
|
|
{
|
|
_appSettings = configuration.GetSection("AppSettings").Get<AppSettings>() ?? new AppSettings();
|
|
_logger = logger;
|
|
}
|
|
|
|
public bool ValidatePassword(string password)
|
|
{
|
|
var isValid = !string.IsNullOrEmpty(password) &&
|
|
password == _appSettings.Password;
|
|
|
|
if (!isValid)
|
|
{
|
|
_logger.LogWarning("Passwort-Validierung fehlgeschlagen");
|
|
}
|
|
|
|
return isValid;
|
|
}
|
|
|
|
public async Task SignInAsync(HttpContext context, string password)
|
|
{
|
|
if (!ValidatePassword(password))
|
|
throw new UnauthorizedAccessException("Ungültiges Passwort.");
|
|
|
|
var claims = new List<Claim>
|
|
{
|
|
new(ClaimTypes.Name, "Admin"),
|
|
new(ClaimTypes.Role, "Administrator")
|
|
};
|
|
|
|
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
|
var principal = new ClaimsPrincipal(identity);
|
|
|
|
await context.SignInAsync(
|
|
CookieAuthenticationDefaults.AuthenticationScheme,
|
|
principal,
|
|
new AuthenticationProperties
|
|
{
|
|
IsPersistent = true,
|
|
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(_appSettings.SessionTimeoutMinutes)
|
|
});
|
|
}
|
|
|
|
public async Task SignOutAsync(HttpContext context)
|
|
{
|
|
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
|
}
|
|
}
|