Wp2ghost/GhostImageManager/Services/AuthService.cs

61 lines
1.8 KiB
C#
Raw Permalink Normal View History

2026-09-24 19:23:54 +02:00
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;
2026-09-28 19:09:09 +02:00
private readonly ILogger<AuthService> _logger;
2026-09-24 19:23:54 +02:00
2026-09-28 19:09:09 +02:00
public AuthService(IConfiguration configuration, ILogger<AuthService> logger)
2026-09-24 19:23:54 +02:00
{
_appSettings = configuration.GetSection("AppSettings").Get<AppSettings>() ?? new AppSettings();
2026-09-28 19:09:09 +02:00
_logger = logger;
2026-09-24 19:23:54 +02:00
}
public bool ValidatePassword(string password)
{
2026-09-28 19:09:09 +02:00
var isValid = !string.IsNullOrEmpty(password) &&
password == _appSettings.Password;
if (!isValid)
{
_logger.LogWarning("Passwort-Validierung fehlgeschlagen");
}
return isValid;
2026-09-24 19:23:54 +02:00
}
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);
}
}