Refactor AuthController for interface and policy checks

Refactored AuthController to implement IAuthController and expose AuthService. Removed the protected IsUserInPolicyAsync method in favor of using an extension method for policy checks. Updated the Logout logic to use the new approach. Consolidated using directives into a single line.
This commit is contained in:
2026-02-06 13:41:45 +01:00
parent ef7c9c2b97
commit ae7f0b80f3

View File

@@ -1,3 +1,4 @@
using EnvelopeGenerator.API.Controllers.Interfaces;
using EnvelopeGenerator.API.Models;
using EnvelopeGenerator.Domain.Constants;
using Microsoft.AspNetCore.Authentication;
@@ -13,20 +14,14 @@ namespace EnvelopeGenerator.API.Controllers;
/// </summary>
[Route("api/[controller]")]
[ApiController]
public partial class AuthController(IOptions<AuthTokenKeys> authTokenKeyOptions, IAuthorizationService authService) : ControllerBase
public partial class AuthController(IOptions<AuthTokenKeys> authTokenKeyOptions, IAuthorizationService authService) : ControllerBase, IAuthController
{
private readonly AuthTokenKeys authTokenKeys = authTokenKeyOptions.Value;
/// <summary>
/// Überprüft, ob der Benutzer über die angegebene Berechtigung verfügt.
///
/// </summary>
/// <param name="policyName"></param>
/// <returns></returns>
protected async Task<bool> IsUserInPolicyAsync(string policyName)
{
var result = await authService.AuthorizeAsync(User, policyName);
return result.Succeeded;
}
public IAuthorizationService AuthService { get; } = authService;
/// <summary>
/// Entfernt das Authentifizierungs-Cookie des Benutzers (AuthCookie)
@@ -48,9 +43,9 @@ public partial class AuthController(IOptions<AuthTokenKeys> authTokenKeyOptions,
[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
if (await IsUserInPolicyAsync(AuthPolicy.Sender))
if (await this.IsUserInPolicyAsync(AuthPolicy.Sender))
Response.Cookies.Delete(authTokenKeys.Cookie);
else if (await IsUserInPolicyAsync(AuthPolicy.ReceiverOrReceiverTFA))
else if (await this.IsUserInPolicyAsync(AuthPolicy.ReceiverOrReceiverTFA))
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
else
return Unauthorized();