Wp2ghost/GhostImageManager/Services/AuthService.cs
2026-09-24 19:23:54 +02:00

51 lines
1.6 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;
public AuthService(IConfiguration configuration)
{
_appSettings = configuration.GetSection("AppSettings").Get<AppSettings>() ?? new AppSettings();
}
public bool ValidatePassword(string password)
{
return !string.IsNullOrEmpty(password) &&
password == _appSettings.Password;
}
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);
}
}