BotSharp/src/Infrastructure/BotSharp.Abstraction/Users/Models/UserAuthorization.cs

47 lines
1.4 KiB
C#
Raw Normal View History

2024-11-14 23:33:26 +00:00
namespace BotSharp.Abstraction.Users.Models;
public class UserAuthorization
{
public bool IsAdmin { get; set; }
public IEnumerable<string> Permissions { get; set; } = [];
2024-11-15 02:19:53 +00:00
public IEnumerable<UserAgent> AgentActions { get; set; } = [];
2024-11-14 23:33:26 +00:00
}
2024-11-15 02:19:53 +00:00
public static class UserAuthorizationExtension
{
public static bool IsAgentActionAllowed(this UserAuthorization auth, string agentId, string targetAction)
{
if (auth == null || string.IsNullOrEmpty(agentId)) return false;
if (auth.IsAdmin) return true;
var found = auth.AgentActions.FirstOrDefault(x => x.AgentId == agentId);
if (found == null) return false;
var actions = found.Actions ?? [];
return actions.Any(x => x == targetAction);
}
2024-11-21 16:31:24 +00:00
/// <summary>
/// Get allowed user actions on the agent. If user is admin, returns null;
/// </summary>
/// <param name="auth"></param>
/// <param name="agentId"></param>
/// <returns></returns>
public static IEnumerable<string>? GetAllowedAgentActions(this UserAuthorization auth, string agentId)
{
if (auth == null || string.IsNullOrEmpty(agentId))
{
return [];
}
if (auth.IsAdmin)
{
return null;
}
var found = auth.AgentActions.FirstOrDefault(x => x.AgentId == agentId);
return found?.Actions ?? [];
}
2024-11-15 02:19:53 +00:00
}