Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@

using Honamic.Framework.Applications.Authorizes;
using Honamic.Framework.Applications.Results;
using Honamic.Framework.Commands;

Expand All @@ -8,6 +9,8 @@ public record CreateTodoItemCommand(string title, string content, List<string> t



//[DynamicAuthorize]
Copy link

Copilot AI May 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Consider removing the commented-out '[DynamicAuthorize]' attribute if it is no longer required to reduce code clutter.

Suggested change
//[DynamicAuthorize]

Copilot uses AI. Check for mistakes.
[Authorize("admin")]
public record CreateTodoItem2Command(string title, string content, List<string> tags)
: ICommand<Result<CreateTodoItem2ResultCommand>>;

Expand Down
5 changes: 3 additions & 2 deletions TodoSample/Facade/TodoItems/TodoItemFacade.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Honamic.Framework.Applications.Results;
using Honamic.Framework.Applications.Authorizes;
using Honamic.Framework.Applications.Results;
using Honamic.Framework.Commands;
using Honamic.Framework.Events;
using Honamic.Framework.Facade;
Expand All @@ -8,7 +9,7 @@

namespace Honamic.Todo.Facade.TodoItems;

[FacadeDynamicAuthorize]
[DynamicAuthorize]
internal class TodoItemFacade : BaseFacade, ITodoItemFacade
{
private readonly ICommandBus _commandBus;
Expand Down
3 changes: 2 additions & 1 deletion TodoSample/Facade/TodoItems/TodoItemQueryFacade.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
using Honamic.Todo.Query.Domain.TodoItems.Queries;
using Honamic.Todo.Query.Domain.TodoItems;
using Honamic.Framework.Applications.Results;
using Honamic.Framework.Applications.Authorizes;

namespace Honamic.Todo.Facade.TodoItems;

[FacadeDynamicAuthorize]
[DynamicAuthorize]
[DisplayName("نمایش انجام دادنی ها")]
public class TodoItemQueryFacade : BaseFacade, ITodoItemQueryFacade
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Honamic.Framework.Applications.Authorizes;

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class AllowAnonymousAttribute : Attribute
{

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace Honamic.Framework.Applications.Authorizes;

[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class AuthorizeAttribute : Attribute
{
public AuthorizeAttribute()
{
Permissions = null;
}

public AuthorizeAttribute(params string[] permissions)
{
Permissions = permissions;
}

public string[]? Permissions { get; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Honamic.Framework.Applications.Authorizes;

[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class DynamicAuthorizeAttribute : Attribute
{

}
11 changes: 11 additions & 0 deletions src/Core/Applications.Abstractions/Authorizes/IAuthorization.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Honamic.Framework.Applications.Authorizes;

public interface IAuthorization
{
[Obsolete("Use HaveAccessAsync instead. This method will be removed in future versions.")]
bool HaveAccess(string permission);

Task<bool> HaveAccessAsync(string permission);

bool IsAuthenticated();
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public UnauthorizedException(string permissionName)
{
PermissionName = permissionName;
}
public override string Message => "the request does not have valid authentication credentials for the operation";
public override string Message => "You do not have permission to perform this operation";

public string PermissionName { get; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
using Honamic.Framework.Applications.Authorizes;
using Honamic.Framework.Applications.Exceptions;
using Honamic.Framework.Commands;
using System.Reflection;

namespace Honamic.Framework.Applications.CommandHandlerDecorators;

public class AuthorizeCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
where TCommand : ICommand
{
private readonly ICommandHandler<TCommand> _commandHandler;
private readonly IAuthorization _authorization;

public AuthorizeCommandHandlerDecorator(ICommandHandler<TCommand> commandHandler, IAuthorization authorization)
{
_commandHandler = commandHandler;
_authorization = authorization;
}

public async Task HandleAsync(TCommand command, CancellationToken cancellationToken)
{
await _authorization.AuthorizeCommandAttributes(typeof(TCommand));

await _commandHandler.HandleAsync(command, cancellationToken);
}
}

public class AuthorizeCommandHandlerDecorator<TCommand, TResponse> : ICommandHandler<TCommand, TResponse>
where TCommand : ICommand<TResponse>
{
private readonly ICommandHandler<TCommand, TResponse> _commandHandler;
private readonly IAuthorization _authorization;

public AuthorizeCommandHandlerDecorator(ICommandHandler<TCommand, TResponse> commandHandler, IAuthorization authorization)
{
_commandHandler = commandHandler;
_authorization = authorization;
}

public async Task<TResponse> HandleAsync(TCommand command, CancellationToken cancellationToken)
{
await _authorization.AuthorizeCommandAttributes(typeof(TCommand));

return await _commandHandler.HandleAsync(command, cancellationToken);
}
}

internal static class AuthorizeCommandHandlerDecoratorHelper
{

public static async Task AuthorizeCommandAttributes(this IAuthorization authorization, Type type)
{
await authorization.AuthorizeWithAttributes(type);

await authorization.AuthorizeWithDynamicPermissions(type);
}

public static async Task AuthorizeWithDynamicPermissions(this IAuthorization authorization, Type type)
{
var dynamicAuthorizeAttribute = type.GetCustomAttribute<DynamicAuthorizeAttribute>();

if (dynamicAuthorizeAttribute is not null)
{
if (!authorization.IsAuthenticated())
{
throw new UnauthenticatedException();
}

string dynamicPermission = CalculatePermissionName(type);

if (!await authorization.HaveAccessAsync(dynamicPermission))
{
throw new UnauthorizedException(dynamicPermission);
}
}
}

public static async Task AuthorizeWithAttributes(this IAuthorization authorization, Type type)
{
var authorizeAttribute = type.GetCustomAttribute<AuthorizeAttribute>();

if (authorizeAttribute is not null)
{
if (!authorization.IsAuthenticated())
{
throw new UnauthenticatedException();
}

if (authorizeAttribute.Permissions?.Length > 0)
{
foreach (var permission in authorizeAttribute.Permissions)
{
if (!await authorization.HaveAccessAsync(permission))
{
throw new UnauthorizedException(permission);
}
}
}
}
}

private static string CalculatePermissionName(Type type)
{
return type.Name;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
using Honamic.Framework.Applications.Exceptions;
using Honamic.Framework.Applications.Results;
using Honamic.Framework.Commands;
using Honamic.Framework.Domain;

namespace Honamic.Framework.Applications.CommandHandlerDecorators;

public class ExceptionCommandHandlerDecorator<TCommand, TResponse> : ICommandHandler<TCommand, TResponse>
where TCommand : ICommand<TResponse>
{
private readonly ICommandHandler<TCommand, TResponse> _commandHandler;

public ExceptionCommandHandlerDecorator(ICommandHandler<TCommand, TResponse> commandHandler)
{
_commandHandler = commandHandler;
}

public async Task<TResponse> HandleAsync(TCommand command, CancellationToken cancellationToken)
{
TResponse result;
try
{
result = await _commandHandler.HandleAsync(command, cancellationToken);
}
catch (Exception ex)
{
if (IsResultOriented(typeof(TResponse)))
{
result = CreateResultWithError(typeof(TResponse), ex);
return result;
}

throw;
}

return result;
}

private TResponse CreateResultWithError(Type type, Exception ex)
Copy link

Copilot AI May 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Consider abstracting the common result creation logic shared with ResultOrientedCommandHandlerDecorator into a common helper to avoid code duplication.

Copilot uses AI. Check for mistakes.
{
var resultObject = CreateResult(type);

if (resultObject is Result result)
{
switch (ex)
{
case UnauthenticatedException:
result.SetStatusAsUnauthenticated();
result.AppendError(ex.Message);
break;
case UnauthorizedException:
result.SetStatusAsUnauthorized();
result.AppendError(ex.Message);
break;
case BusinessException businessException:
result.Status = ResultStatus.ValidationError;
var code = businessException.GetCode();
var message = businessException.GetMessage();
result.AppendError(message, null, code);
break;
default:
result.SetStatusAsUnhandledExceptionWithSorryError();
result.AppendError(ex.ToString(), "Exception");
break;
}
return resultObject;
}

// If we can't cast to Result, we have a serious error
throw new ArgumentException($"Expected a Result type but got {type.FullName}");
}

private TResponse CreateResult(Type type)
{
// For non-generic Result
if (type == typeof(Result))
{
return (TResponse)(object)new Result();
}

// For Result<T>
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Result<>))
{
var genericArgType = type.GenericTypeArguments[0];
var resultType = typeof(Result<>).MakeGenericType(genericArgType);
return (TResponse)Activator.CreateInstance(resultType);
}

return default;
}

private bool IsResultOriented(Type type)
{
if (type == typeof(Result))
{
return true;
}

if (type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(Result<>))
{
return true;
}

return false;
}
}
Loading