using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Http; using System.Security.Claims; using UserManagement.Application.Interfaces; using UserManagement.Infrastructure.Interfaces; namespace UserManagement.Application.Services { public class AuthService : IAuthService { // CTOR private readonly IUserRepository _userRepository; public AuthService(IUserRepository userRepository) { _userRepository = userRepository; } // LOGIN public async Task SignInAsync(string username, string password, HttpContext httpContext) { var user = await _userRepository.GetByUsernameAsync(username, includeRoles: true); if (user == null || !BCrypt.Net.BCrypt.Verify(password, user.PasswordHash)) { throw new UnauthorizedAccessException("Benutzername und Passwort stimmen nicht überein!"); } var claims = new List { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Surname, user.LastName ?? ""), new Claim(ClaimTypes.GivenName, user.FirstName ?? "") }; claims.AddRange(user.UserRoles.Select(role => new Claim(ClaimTypes.Role, role.Role.Name))); var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { IsPersistent = true, AllowRefresh = true, ExpiresUtc = DateTime.UtcNow.AddMinutes(60) }; var principal = new ClaimsPrincipal(claimsIdentity); await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, authProperties); return principal; } // LOGOUT public async Task SignOutAsync(HttpContext httpContext) { await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } } }