140 lines
3.4 KiB
C#
140 lines
3.4 KiB
C#
using System;
|
|
using System.Linq;
|
|
using xCommons.Extensions;
|
|
using xExceptions.Constants;
|
|
using System.Collections.Generic;
|
|
using xIdentityService.Interfaces;
|
|
using Microsoft.EntityFrameworkCore.Internal;
|
|
|
|
namespace xIdentityService.Providers
|
|
{
|
|
public class XPolicyHandler : IXPolicyHandler
|
|
{
|
|
private readonly static Dictionary<string, IEnumerable<string>> policies = [];
|
|
|
|
/// <summary>
|
|
/// Add Specified Role ...
|
|
/// </summary>
|
|
/// <param name="policy"></param>
|
|
/// <param name="requiredRoles"></param>
|
|
/// <returns></returns>
|
|
public bool AddPolicy(
|
|
string policy,
|
|
IEnumerable<string> requiredRoles
|
|
)
|
|
{
|
|
//
|
|
// Validate ...
|
|
if (policy.IsNullOrEmpty() ||
|
|
!requiredRoles.HasChild()
|
|
)
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
var result = !HasPolicy(policy);
|
|
if (!result)
|
|
{
|
|
return result;
|
|
}
|
|
|
|
//
|
|
policies[policy] = requiredRoles;
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Check Specified Role Exists or not ...
|
|
/// </summary>
|
|
/// <param name="policy"></param>
|
|
/// <returns></returns>
|
|
public bool HasPolicy(string policy)
|
|
{
|
|
//
|
|
var result =
|
|
policies.HasChild() &&
|
|
!policy.IsNullOrEmpty() &&
|
|
policies.Keys.Any(p => p
|
|
.Equals(policy, StringComparison.InvariantCultureIgnoreCase));
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Remove Specified Role ...
|
|
/// </summary>
|
|
/// <param name="policy"></param>
|
|
/// <returns></returns>
|
|
public bool RemovePolicy(string policy)
|
|
{
|
|
//
|
|
// Validate ...
|
|
if (policy.IsNullOrEmpty())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
var result = HasPolicy(policy);
|
|
if (!result)
|
|
{
|
|
return result;
|
|
}
|
|
|
|
//
|
|
result = policies.Remove(policy);
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Check Specified Policy passed or not ...
|
|
/// </summary>
|
|
/// <param name="policy"></param>
|
|
/// <param name="roles"></param>
|
|
/// <returns></returns>
|
|
public bool IsPolicyPassed(
|
|
string policy,
|
|
IEnumerable<string> roles
|
|
)
|
|
{
|
|
//
|
|
// Validate ...
|
|
if (!roles.HasChild() ||
|
|
policy.IsNullOrEmpty())
|
|
{
|
|
XException.InvalidArgs.Throw();
|
|
}
|
|
|
|
//
|
|
// Normalize ...
|
|
policy = policy.ToNormalString();
|
|
|
|
//
|
|
var result = HasPolicy(policy);
|
|
if (!result)
|
|
{
|
|
return result;
|
|
}
|
|
|
|
//
|
|
var requiredRoles = policies[policy];
|
|
result =
|
|
requiredRoles.HasChild() &&
|
|
roles.All(r => requiredRoles
|
|
.Any(rq => r.Equals(rq, StringComparison.InvariantCultureIgnoreCase)));
|
|
|
|
//
|
|
return result;
|
|
}
|
|
|
|
//
|
|
#region Private ...
|
|
#endregion
|
|
}
|
|
} |