This commit is contained in:
2026-11-27 19:21:47 +03:30
parent 384cffac36
commit 9d913146e1
6 changed files with 619 additions and 111 deletions
@@ -0,0 +1,250 @@
using xModels.Dtos;
using System.Threading;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using xIdentityModels.Models;
using System.Threading.Tasks;
using xIdentityService.Models;
using System.Collections.Generic;
namespace xIds.Providers
{
public partial class XAuthorizationProvider
{
//
#region Policy ...
public async Task<bool> RemovePolicyAsync(
string name,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
)
{
//
var existing = await FindPolicyOrThrowAsync(name, cancellationToken);
if (existing.IsSystem)
{
XException.NotAllowed.Throw();
}
//
await policies.RemoveAsync(
id: existing.Id,
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
await InvalidateAsync(existing.Name);
return true;
}
public async Task<XPolicyDefinitionDto> GetPolicyAsync(
string name,
CancellationToken cancellationToken = default
)
{
//
var result = await FindPolicyOrThrowAsync(name, cancellationToken);
//
return result;
}
public async Task<XPolicyDefinitionDto> AddPolicyAsync(
XPolicyDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
)
{
//
if (item.IsNull() || item.Name.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var normalized = item.Name.ToNormalString();
var exists = await policies.FindOneAsync(
predicate: p => p.Name.ToLower() == normalized,
cancellationToken: cancellationToken
);
if (!exists.IsNull())
{
XException.Duplicate.Throw();
}
//
// ⚠️ CRITICAL: مقصد همه Role/Scopeها وجود داشته باشند
await ValidateReferencesAsync(item, cancellationToken);
//
item.IsSystem = false;
var result = await policies.AddAsync(
item: item,
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
await InvalidateAsync();
return result;
}
public async Task<XPolicyDefinitionDto> UpdatePolicyAsync(
string name,
XPolicyDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
)
{
//
if (name.IsNullOrEmpty() || item.IsNull())
{
XException.InvalidArgs.Throw();
}
//
var existing = await FindPolicyOrThrowAsync(name, cancellationToken);
if (existing.IsSystem)
{
XException.NotAllowed.Throw();
}
//
// Reference validation BEFORE update — same as Add
await ValidateReferencesAsync(item, cancellationToken);
//
var updated = await policies.UpdateAsync(
id: existing.Id,
item: item,
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
await InvalidateAsync(existing.Name);
return updated;
}
public async Task<XPolicyEvaluationResultDto> EvaluatePolicyAsync(
string name,
XUserClaimsInfoDto target,
CancellationToken cancellationToken = default
)
{
//
// Load the policy (throws NotFound when missing) ...
var dto = await FindPolicyOrThrowAsync(name, cancellationToken);
//
var result = new XPolicyEvaluationResultDto
{
Passed = true,
Policy = dto.Name,
FailedRequirements = []
};
//
// Build the policy's effective authorization via the shared helper
// (resolver + projection onto XEffectiveAuthorizationDto) ...
var auth = await ToDtoWithEffectiveRolesAsync(dto, cancellationToken);
if (auth.IsNull())
{
//
result.Passed = false;
result.FailedRequirements.Add("PolicyNotBuilt");
//
return result;
}
//
// Anonymous user fails any policy that requires authentication ...
if (target.IsNull())
{
//
if (auth.RequireAuthenticatedUser)
{
//
result.Passed = false;
result.FailedRequirements.Add("RequireAuthenticatedUser");
}
//
return result;
}
//
// Effective Roles: the user must hold at least one ...
if (auth.EffectiveRoles.HasChild())
{
// //
// var userSelectByParam = target.GetUserSelectByParam();
// //
// var userRoles = await roles.FindManyAsync(
// predicate: x => x.
// cancellationToken: cancellationToken
// );
// //
// var matched = auth.EffectiveRoles.Any(er =>
// userRoles.Any(ur =>
// string.Equals(ur, er, StringComparison.OrdinalIgnoreCase)
// )
// );
//
// if (!matched)
// {
// //
// result.Passed = false;
// result.FailedRequirements.Add("RequiredRoles");
// }
}
//
// NOTE: RequireEnabledUser (IsEnabled / !IsBanned), EffectiveScopes and
// EffectiveClaims checks are layered on here once the matching flags /
// collections on XUserClaimsInfoDto (xIdentityModels) are wired.
return result;
}
public async Task<IEnumerable<XPolicyDefinitionDto>> GetPoliciesAsync(
CancellationToken cancellationToken = default
)
{
//
var result = await policies
.GetAllAsync(cancellationToken: cancellationToken);
//
return result;
}
public async Task<XQueryResult<XPolicyDefinitionDto>> QueryPoliciesAsync(
XQuery query,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (query.IsNull())
{
XException.InvalidArgs.Throw();
}
//
var result = await policies.QueryAsync(
query: query,
cancellationToken: cancellationToken
);
//
return result;
}
#endregion
}
}
@@ -1,11 +1,13 @@
using System;
using System.Linq;
using xModels.Dtos;
using System.Threading;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityModels.Models;
using System.Collections.Generic;
namespace xIds.Providers
{
@@ -13,6 +15,74 @@ namespace xIds.Providers
{
//
#region Role ...
public async Task<bool> RemoveRoleAsync(
string name,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
)
{
//
var existing = await FindRoleOrThrowAsync(name, cancellationToken);
if (existing.IsSystem)
{
XException.NotAllowed.Throw();
}
//
// ⚠️ CRITICAL: capture affected users BEFORE delete.
// After DeleteRoleAsync, AspNetUserRoles rows are gone.
var affectedUsers = await manager.UserManager.GetUsersInRoleAsync(existing.Name);
var affectedUserIds = affectedUsers.Select(u => u.Id).ToList();
//
// Delete from local DB
await roles.RemoveAsync(
id: existing.Id,
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
// Delete from IdentityServer — this cascades AspNetUserRoles
await manager.DeleteRoleAsync(existing.Name, cancellationToken);
//
await InvalidateAsync();
return true;
}
public async Task<int> CountUsersInRoleAsync(
string name,
CancellationToken cancellationToken = default
)
{
//
// Fail fast if the role itself does not exist ...
await FindRoleOrThrowAsync(name, cancellationToken);
//
var usersInRole = await manager
.UserManager.GetUsersInRoleAsync(name);
//
var result = usersInRole.Count();
//
return result;
}
public async Task<XRoleDefinitionDto> GetRoleAsync(
string name,
CancellationToken cancellationToken = default
)
{
//
var result = await FindRoleOrThrowAsync(name, cancellationToken);
//
return result;
}
public async Task<XRoleDefinitionDto> AddRoleAsync(
XRoleDefinitionDto item,
XUserClaimsInfoDto userInfo,
@@ -73,7 +143,7 @@ namespace xIds.Providers
}
public async Task<XRoleDefinitionDto> UpdateRoleAsync(
string name,
string name,
XRoleDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
@@ -126,7 +196,7 @@ namespace xIds.Providers
}
//
foreach(var user in usersInRole)
foreach (var user in usersInRole)
{
//
await manager.AddUserToRoleAsync(
@@ -141,41 +211,39 @@ namespace xIds.Providers
return updated;
}
public async Task<bool> RemoveRoleAsync(
string name,
XUserClaimsInfoDto userInfo,
public async Task<IEnumerable<XRoleDefinitionDto>> GetRolesAsync(
CancellationToken cancellationToken = default
)
{
//
var existing = await FindRoleOrThrowAsync(name, cancellationToken);
if (existing.IsSystem)
var result = await roles
.GetAllAsync(cancellationToken: cancellationToken);
//
return result;
}
public async Task<XQueryResult<XRoleDefinitionDto>> QueryRolesAsync(
XQuery query,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (query.IsNull())
{
XException.NotAllowed.Throw();
XException.InvalidArgs.Throw();
}
//
// ⚠️ CRITICAL: capture affected users BEFORE delete.
// After DeleteRoleAsync, AspNetUserRoles rows are gone.
var affectedUsers = await manager.UserManager.GetUsersInRoleAsync(existing.Name);
var affectedUserIds = affectedUsers.Select(u => u.Id).ToList();
//
// Delete from local DB
await roles.RemoveAsync(
id: existing.Id,
userInfo: userInfo,
var result = await roles.QueryAsync(
query: query,
cancellationToken: cancellationToken
);
//
// Delete from IdentityServer — this cascades AspNetUserRoles
await manager.DeleteRoleAsync(existing.Name, cancellationToken);
//
await InvalidateAsync();
return true;
}
return result;
}
#endregion
}
}
@@ -1,5 +1,6 @@
using System;
using System.Linq;
using xModels.Dtos;
using System.Threading;
using xCommons.Extensions;
using xIdentityModels.Dtos;
@@ -14,12 +15,36 @@ namespace xIds.Providers
{
//
#region Scope ...
public async Task<IEnumerable<XScopeDefinitionDto>> GetScopesAsync(
public async Task<bool> RemoveScopeAsync(
string name,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
)
{
return await scopes
.GetAllAsync(cancellationToken: cancellationToken);
//
var existing = await FindScopeOrThrowAsync(name, cancellationToken);
if (existing.IsSystem) {
XException.NotAllowed.Throw();
}
//
var affectedPolicies = (await policies.GetAllAsync(cancellationToken: cancellationToken))
.Where(p => !p.RequiredScopes.IsNullOrEmpty()
&& p.RequiredScopes.ParseListString<string>()
.Any(s => string.Equals(s, existing.Name,
StringComparison.OrdinalIgnoreCase)))
.ToList();
//
await scopes.RemoveAsync(
id: existing.Id,
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
await InvalidateAsync();
return true;
}
public async Task<XScopeDefinitionDto> GetScopeAsync(
@@ -97,38 +122,35 @@ namespace xIds.Providers
await InvalidateAsync();
return updated;
}
public async Task<IEnumerable<XScopeDefinitionDto>> GetScopesAsync(
CancellationToken cancellationToken = default
)
{
return await scopes
.GetAllAsync(cancellationToken: cancellationToken);
}
public async Task<bool> RemoveScopeAsync(
string name,
XUserClaimsInfoDto userInfo,
public async Task<XQueryResult<XScopeDefinitionDto>> QueryScopesAsync(
XQuery query,
CancellationToken cancellationToken = default
)
{
//
var existing = await FindScopeOrThrowAsync(name, cancellationToken);
if (existing.IsSystem) {
XException.NotAllowed.Throw();
if (query.IsNull())
{
XException.InvalidArgs.Throw();
}
//
var affectedPolicies = (await policies.GetAllAsync(cancellationToken: cancellationToken))
.Where(p => !p.RequiredScopes.IsNullOrEmpty()
&& p.RequiredScopes.ParseListString<string>()
.Any(s => string.Equals(s, existing.Name,
StringComparison.OrdinalIgnoreCase)))
.ToList();
//
await scopes.RemoveAsync(
id: existing.Id,
userInfo: userInfo,
var result = await scopes.QueryAsync(
query: query,
cancellationToken: cancellationToken
);
//
await InvalidateAsync();
return true;
}
return result;
}
#endregion
}
}