Compare commits

..
8 Commits
Author SHA1 Message Date
saherelm 49483d1d39 last ... 2026-11-28 00:08:02 +03:30
saherelm 9d913146e1 last ... 2026-11-27 19:21:47 +03:30
saherelm 384cffac36 last ... 2026-11-26 19:37:19 +03:30
saherelm 869a0476a0 last ... 2026-11-16 11:20:12 +03:30
saherelm 1cf90dcd9e last ... 2026-11-15 21:25:02 +03:30
saherelm 3a556a329a last ... 2026-11-15 17:52:54 +03:30
saherelm 24363e89ae apply cleanup ... 2026-11-13 13:49:07 +03:30
saherelm 8d392b3d84 - Program.cs: Arrow → معمولی، +Telemetry
- Startup.cs: isDevelopmentEnvironment var، +logging middleware
- xIds.csproj: +xLoggingService reference
2026-11-09 12:53:24 +03:30
29 changed files with 4178 additions and 50 deletions
+1
View File
@@ -1,6 +1,7 @@
# #
bin bin
obj obj
Logs
# #
Db/* Db/*
+4 -1
View File
@@ -1,19 +1,22 @@
using xIds.Interfaces; using xIds.Interfaces;
using xCommons.Providers; using xCommons.Providers;
using xCommons.Attributes;
using xIds.Controllers.Base; using xIds.Controllers.Base;
using xCommons.Configurations; using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace xIds.Controllers namespace xIds.Controllers
{ {
/// <summary> /// <summary>
/// Provide all available tools for manipulating users and accounts /// Provide all available tools for manipulating users and accounts
/// </summary> /// </summary>
[Authorize]
[ApiController] [ApiController]
[RequireXPowered]
public partial class AccountController : XIBaseController public partial class AccountController : XIBaseController
{ {
public AccountController( public AccountController(
IXIdentityManager identityManager, IXIdentityManager identityManager,
ILogger<AccountController> logger, ILogger<AccountController> logger,
+4
View File
@@ -1,17 +1,21 @@
using xIds.Interfaces; using xIds.Interfaces;
using xCommons.Providers; using xCommons.Providers;
using xIds.Configurations; using xIds.Configurations;
using xCommons.Attributes;
using xIds.Controllers.Base; using xIds.Controllers.Base;
using xCommons.Configurations; using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace xIds.Controllers namespace xIds.Controllers
{ {
/// <summary> /// <summary>
/// Provide all available tools for manipulating users and accounts /// Provide all available tools for manipulating users and accounts
/// </summary> /// </summary>
[Authorize]
[ApiController] [ApiController]
[RequireXPowered]
public partial class ApplicationsController : XIBaseController public partial class ApplicationsController : XIBaseController
{ {
private readonly IXApplicationProvider provider; private readonly IXApplicationProvider provider;
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace xIds.Controllers
{
public partial class AuthorizationController
{
}
}
@@ -0,0 +1,59 @@
using System;
using xIdentityHelper;
using System.Threading;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
namespace xIds.Controllers
{
public partial class AuthorizationController
{
/// <summary>
/// Retrieve Specified Role By Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("Roles/{id}")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public virtual async Task<ActionResult<XRoleDefinitionDto>> Get(
[FromRoute] int id,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validate ...
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
//
var userInfo = await GetUserInfo();
//
var result = await roleProvider.GetAsync(
id: id,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken
);
//
return Ok(result.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
}
}
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace xIds.Controllers
{
public partial class AuthorizationController
{
}
}
+38
View File
@@ -0,0 +1,38 @@
using xIds.Interfaces;
using xCommons.Providers;
using xCommons.Attributes;
using xIds.Controllers.Base;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace xIds.Controllers
{
[Authorize]
[ApiController]
[RequireXPowered]
public partial class AuthorizationController : XIBaseController
{
private readonly IXRoleProvider roleProvider;
private readonly IXScopeProvider scopeProvider;
private readonly IXPolicyProvider policyProvider;
public AuthorizationController(
IXRoleProvider roleProvider,
IXScopeProvider scopeProvider,
IXPolicyProvider policyProvider,
IXIdentityManager identityManager,
XAppConfiguration appConfiguration,
XValidationProvider validationProvider,
ILogger<AuthorizationController> logger
) : base(logger, appConfiguration, identityManager, validationProvider)
{
//
this.roleProvider = roleProvider;
this.scopeProvider = scopeProvider;
this.policyProvider = policyProvider;
}
}
}
+27
View File
@@ -19,6 +19,8 @@ using xCommons.Authorization;
using System.Collections.Generic; using System.Collections.Generic;
using xMessageService.Interfaces; using xMessageService.Interfaces;
using xStorageService.Interfaces; using xStorageService.Interfaces;
using xIdentityService.Providers;
using xIdentityService.Extensions;
using xIdentityService.Interfaces; using xIdentityService.Interfaces;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -81,6 +83,27 @@ namespace xIds.DI
return config.GetConnectionString(connectionName); return config.GetConnectionString(connectionName);
} }
/// <summary>
/// Register Scope/Role/Policy Providers ...
/// </summary>
/// <param name="source"></param>
public static void AddXAuthorizationProviders(
this IServiceCollection source
)
{
//
source.AddScoped<IXRoleProvider, XRoleProvider>();
source.AddScoped<IXScopeProvider, XScopeProvider>();
source.AddScoped<IXPolicyProvider, XPolicyProvider>();
//
source.AddXAuthorizationCache();
source.AddScoped<IXRoleHierarchyResolver, XRoleHierarchyResolver>();
//
source.AddXAuthorizationProvider();
}
/// <summary> /// <summary>
/// Retrive XDataService Configurations ... /// Retrive XDataService Configurations ...
/// </summary> /// </summary>
@@ -531,6 +554,10 @@ namespace xIds.DI
// //
services.AddSingleton<IAuthorizationHandler, RequiredRolesHandler>(); services.AddSingleton<IAuthorizationHandler, RequiredRolesHandler>();
//
// Register Providers ...
services.AddXAuthorizationProviders();
} }
/// <summary> /// <summary>
+21
View File
@@ -20,6 +20,9 @@ namespace xIds.DbContext
public DbSet<XBannedDevice> BannedDevices { get; set; } public DbSet<XBannedDevice> BannedDevices { get; set; }
public DbSet<XFriendshipFollower> Followers { get; set; } public DbSet<XFriendshipFollower> Followers { get; set; }
public DbSet<XFriendshipFollowing> Followings { get; set; } public DbSet<XFriendshipFollowing> Followings { get; set; }
public DbSet<XRoleDefinition> RoleDefinitions { get; set; }
public DbSet<XScopeDefinition> ScopeDefinitions { get; set; }
public DbSet<XPolicyDefinition> PolicyDefinitions { get; set; }
public DbSet<XVerificationRequest> VerificationRequests { get; set; } public DbSet<XVerificationRequest> VerificationRequests { get; set; }
#endregion #endregion
@@ -73,6 +76,24 @@ namespace xIds.DbContext
e.HasIndex(k => k.KeyHash).IsUnique(); e.HasIndex(k => k.KeyHash).IsUnique();
e.HasIndex(k => k.ExpiresAt); e.HasIndex(k => k.ExpiresAt);
}); });
//
modelBuilder.Entity<XRoleDefinition>(e =>
{
e.HasIndex(p => p.Name).IsUnique();
});
//
modelBuilder.Entity<XScopeDefinition>(e =>
{
e.HasIndex(p => p.Name).IsUnique();
});
//
modelBuilder.Entity<XPolicyDefinition>(e =>
{
e.HasIndex(p => p.Name).IsUnique();
});
} }
} }
} }
+35
View File
@@ -1,5 +1,8 @@
using xIds.Providers; using xIds.Providers;
using xIds.Interfaces; using xIds.Interfaces;
using xCommons.Extensions;
using xExceptions.Constants;
using xIdentityService.Interfaces;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
namespace xIds.Extensions namespace xIds.Extensions
@@ -25,5 +28,37 @@ namespace xIds.Extensions
{ {
source.AddScoped<IXIdentityMessageProvider, XIdentityMessageProvider>(); source.AddScoped<IXIdentityMessageProvider, XIdentityMessageProvider>();
} }
/// <summary>
/// Register Authorization Provider ...
/// </summary>
/// <param name="source"></param>
public static void AddXAuthorizationProvider(
this IServiceCollection source
)
{
//
// Validate Requirements ...
var roles = source.GetRegisteredService<IXRoleProvider>();
var scopes = source.GetRegisteredService<IXScopeProvider>();
var policies = source.GetRegisteredService<IXPolicyProvider>();
var cache = source.GetRegisteredService<IXAuthorizationCache>();
var resolver = source.GetRegisteredService<IXRoleHierarchyResolver>();
//
var isInvalid =
roles.IsNull() ||
cache.IsNull() ||
scopes.IsNull() ||
policies.IsNull() ||
resolver.IsNull();
if (isInvalid)
{
XException.InvalidConfiguration.Throw();
}
//
source.AddScoped<IXAuthorizationProvider, XAuthorizationProvider>();
}
} }
} }
+315
View File
@@ -1,8 +1,13 @@
using System; using System;
using System.Linq; using System.Linq;
using xModels.Dtos;
using System.Reflection;
using xCommons.Extensions; using xCommons.Extensions;
using xExceptions.Constants;
using System.Threading.Tasks; using System.Threading.Tasks;
using xDataService.Constants;
using xIdentityModels.Models; using xIdentityModels.Models;
using System.Linq.Expressions;
using System.Collections.Generic; using System.Collections.Generic;
using xDataService.Configuration; using xDataService.Configuration;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@@ -32,6 +37,146 @@ namespace xIds.Extensions
return result; return result;
} }
// /// <summary>
// /// Apply Search Filter on a Enumerable
// /// </summary>
// /// <param name="source"></param>
// /// <param name="filter"></param>
// /// <typeparam name="T"></typeparam>
// /// <returns></returns>
// public static IEnumerable<T> ApplyFilter<T>(
// this IEnumerable<T> source,
// string filter
// )
// where T : class
// {
// //
// // Apply Filter ...
// return source.Where(r => r.PropValuesContains(filter));
// }
// /// <summary>
// /// Count Query Pages based on Specified Total Number ...
// /// </summary>
// /// <param name="source"></param>
// /// <param name="totalItems"></param>
// /// <returns></returns>
// public static int CountPages(
// this XQuery source,
// int totalItems
// )
// {
// //
// int result = 0;
// //
// // Validate and Calculate ...
// if (!source.IsNull() && source.PageSize > 0 && totalItems > 0)
// {
// //
// result = totalItems / source.PageSize;
// if (totalItems % source.PageSize > 0)
// {
// result++;
// }
// }
// //
// return result;
// }
// /// <summary>
// /// Apply Sorting on a Enumerable
// /// </summary>
// /// <param name="source"></param>
// /// <param name="sortBy"></param>
// /// <param name="isAscending"></param>
// /// <param name="columnsMap"></param>
// /// <typeparam name="T"></typeparam>
// /// <returns></returns>
// public static IEnumerable<T> ApplySorting<T>(
// this IEnumerable<T> source,
// string sortBy,
// bool isAscending,
// IDictionary<string, Expression<Func<T, object>>> columnsMap = null
// )
// where T : class
// {
// //
// if (columnsMap == null)
// {
// //
// columnsMap = source.FirstOrDefault()
// .GetDefaultColumnsMap();
// //
// if (columnsMap == null)
// {
// return source;
// }
// }
// //
// // Validate SortBy ...
// var sortByItem = columnsMap.Keys
// .FirstOrDefault(p =>
// p.ToNormalString() == sortBy.ToNormalString());
// if (sortByItem.IsNullOrEmpty())
// {
// return source;
// }
// //
// // Apply Sorting ...
// if (isAscending)
// {
// return source.OrderBy(sortByItem);
// }
// else
// {
// return source.OrderByDescending(sortByItem);
// }
// }
// /// <summary>
// /// Apply Paging on a Enumerable
// /// </summary>
// /// <param name="source"></param>
// /// <param name="page"></param>
// /// <param name="pageSize"></param>
// /// <typeparam name="T"></typeparam>
// /// <returns></returns>
// public static IEnumerable<T> ApplyPaging<T>(
// this IEnumerable<T> source,
// int? page,
// int? pageSize
// )
// {
// //
// if (!page.HasValue ||
// page <= 0)
// {
// page = 1;
// }
// //
// if (!pageSize.HasValue ||
// pageSize <= 0 ||
// pageSize > XDataServiceConstants.MAX_AVAILABLE_PAGE_SIZE)
// {
// pageSize = XDataServiceConstants.DEFAULT_PAGE_SIZE;
// }
// //
// var pageVal = page.GetValueOrDefault();
// var pageSizeVal = pageSize.GetValueOrDefault();
// //
// return source
// .Skip((pageVal - 1) * pageSizeVal)
// .Take(pageSizeVal);
// }
/// <summary> /// <summary>
/// Applying Filter to IQueryable /// Applying Filter to IQueryable
/// /// </summary> /// /// </summary>
@@ -87,5 +232,175 @@ namespace xIds.Extensions
// //
return result; return result;
} }
// /// <summary>
// /// provide a way to Order an IQueryable by string FieldName ...
// /// </summary>
// /// <param name="query"></param>
// /// <param name="propertyName"></param>
// /// <typeparam name="TSource"></typeparam>
// /// <returns></returns>
// public static IOrderedQueryable<TSource> OrderBy<TSource>(
// this IQueryable<TSource> query,
// string propertyName
// )
// {
// //
// var entityType = typeof(TSource);
// //
// // Create x => x.PropName
// var propertyInfo = entityType.GetProperty(propertyName);
// if (propertyInfo.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// ParameterExpression arg = Expression.Parameter(entityType, "x");
// MemberExpression property = Expression.Property(arg, propertyName);
// var selector = Expression.Lambda(property, new ParameterExpression[] { arg });
// //
// // Get System.Linq.Queryable.OrderBy() method.
// var enumarableType = typeof(System.Linq.Queryable);
// var method = enumarableType.GetMethods()
// .Where(m => m.Name == "OrderBy" && m.IsGenericMethodDefinition)
// .Where(m =>
// {
// //
// var parameters = m.GetParameters().ToList();
// //
// // Put more restriction here to ensure selecting the right overload
// return parameters.Count == 2; // overload that has 2 parameters
// }).Single();
// //
// // The linq's OrderBy<TSource, TKey> has two generic types, which provided here ...
// MethodInfo genericMethod = method
// .MakeGenericMethod(entityType, propertyInfo.PropertyType);
// /*
// Call query.OrderBy(selector), with query and selector: x=> x.PropName
// Note that we pass the selector as Expression to the method and we don't compile it.
// By doing so EF can extract "order by" columns and generate SQL for it.
// */
// var newQuery = (IOrderedQueryable<TSource>)genericMethod
// .Invoke(genericMethod, new object[] { query, selector });
// //
// return newQuery;
// }
// /// <summary>
// /// provide a way to Order an IEnumerable by string FieldName ...
// /// </summary>
// /// <param name="query"></param>
// /// <param name="propertyName"></param>
// /// <typeparam name="TSource"></typeparam>
// /// <returns></returns>
// public static IOrderedEnumerable<TSource> OrderBy<TSource>(
// this IEnumerable<TSource> query,
// string propertyName
// )
// {
// //
// var entityType = typeof(TSource);
// var propertyInfo = entityType.GetProperty(propertyName);
// if (propertyInfo.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// return query.OrderBy(x => propertyInfo.GetValue(x, null));
// }
// /// <summary>
// /// provide a way to Order an IQueryable by string FieldName ...
// /// </summary>
// /// <param name="query"></param>
// /// <param name="propertyName"></param>
// /// <typeparam name="TSource"></typeparam>
// /// <returns></returns>
// public static IOrderedQueryable<TSource> OrderByDescending<TSource>(
// this IQueryable<TSource> query,
// string propertyName
// )
// {
// //
// var entityType = typeof(TSource);
// //
// // Create x => x.PropName
// var propertyInfo = entityType.GetProperty(propertyName);
// if (propertyInfo.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// ParameterExpression arg = Expression.Parameter(entityType, "x");
// MemberExpression property = Expression.Property(arg, propertyName);
// var selector = Expression.Lambda(property, new ParameterExpression[] { arg });
// //
// // Get System.Linq.Queryable.OrderBy() method.
// var enumarableType = typeof(System.Linq.Queryable);
// var method = enumarableType.GetMethods()
// .Where(m => m.Name == "OrderByDescending" && m.IsGenericMethodDefinition)
// .Where(m =>
// {
// //
// var parameters = m.GetParameters().ToList();
// //
// // Put more restriction here to ensure selecting the right overload
// return parameters.Count == 2; // overload that has 2 parameters
// }).Single();
// //
// // The linq's OrderBy<TSource, TKey> has two generic types, which provided here ...
// MethodInfo genericMethod = method
// .MakeGenericMethod(entityType, propertyInfo.PropertyType);
// /*
// Call query.OrderBy(selector), with query and selector: x=> x.PropName
// Note that we pass the selector as Expression to the method and we don't compile it.
// By doing so EF can extract "order by" columns and generate SQL for it.
// */
// var newQuery = (IOrderedQueryable<TSource>)genericMethod
// .Invoke(genericMethod, new object[] { query, selector });
// //
// return newQuery;
// }
// /// <summary>
// /// provide a way to Order an IEnumerable by string FieldName ...
// /// </summary>
// /// <param name="query"></param>
// /// <param name="propertyName"></param>
// /// <typeparam name="TSource"></typeparam>
// /// <returns></returns>
// public static IOrderedEnumerable<TSource> OrderByDescending<TSource>(
// this IEnumerable<TSource> query,
// string propertyName
// )
// {
// //
// var entityType = typeof(TSource);
// var propertyInfo = entityType.GetProperty(propertyName);
// if (propertyInfo.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// return query.OrderByDescending(x => propertyInfo.GetValue(x, null));
// }
} }
} }
+4
View File
@@ -88,6 +88,10 @@ namespace xIds.Interfaces
); );
Task<IdentityResult> RemoveFromRoleAsync(XUser user, string roleName); Task<IdentityResult> RemoveFromRoleAsync(XUser user, string roleName);
Task<IdentityResult> RemoveFromRolesAsync(XUser user, IEnumerable<string> roleNames); Task<IdentityResult> RemoveFromRolesAsync(XUser user, IEnumerable<string> roleNames);
Task<IdentityResult> DeleteRoleAsync(
string roleName,
CancellationToken cancellationToken = default
);
#endregion #endregion
// //
+13 -3
View File
@@ -1,3 +1,4 @@
using xLoggingService.DI;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
@@ -10,11 +11,20 @@ namespace xIds
CreateHostBuilder(args).Build().Run(); CreateHostBuilder(args).Build().Run();
} }
public static IHostBuilder CreateHostBuilder(string[] args) => public static IHostBuilder CreateHostBuilder(string[] args)
Host.CreateDefaultBuilder(args) {
//
var result = Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
logging.AddXTelemetryLogger())
.ConfigureWebHostDefaults(webBuilder => .ConfigureWebHostDefaults(webBuilder =>
{ {
webBuilder.UseStartup<Startup>(); webBuilder.UseStartup<Startup>();
}); })
.AddXTelemetry();
//
return result;
}
} }
} }
+16 -17
View File
@@ -21,7 +21,7 @@ namespace xIds.Providers
AllowMultiple = false, AllowMultiple = false,
Inherited = true Inherited = true
)] )]
public class XApiKeyAccessAttribute : AuthorizeAttribute, IAuthorizationFilter public class XApiKeyAccessAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
{ {
/// <summary> /// <summary>
/// Optional allowed scopes. If empty, no scope enforcement. /// Optional allowed scopes. If empty, no scope enforcement.
@@ -46,21 +46,7 @@ namespace xIds.Providers
/// Authorization Filtering ... /// Authorization Filtering ...
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
public void OnAuthorization(AuthorizationFilterContext context) public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
Task.FromResult(OnAuthorizationAsync(context));
}
/// <summary>
/// Handle Authorization Filtering Using Tasks ...
/// </summary>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task OnAuthorizationAsync(
AuthorizationFilterContext context,
CancellationToken cancellationToken = default
)
{ {
// //
// Access HttpContext ... // Access HttpContext ...
@@ -125,7 +111,7 @@ namespace xIds.Providers
userInfo: null, userInfo: null,
clientIP: clientIP, clientIP: clientIP,
requiredScope: scopes, requiredScope: scopes,
cancellationToken: cancellationToken cancellationToken: default
); );
if (validationResult.Errors.HasChild()) if (validationResult.Errors.HasChild())
{ {
@@ -155,5 +141,18 @@ namespace xIds.Providers
context.Result = new UnauthorizedObjectResult(error); context.Result = new UnauthorizedObjectResult(error);
} }
} }
/// <summary>
/// Handle Authorization Filtering Using Tasks ...
/// </summary>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task OnAuthorizationAsync(
AuthorizationFilterContext context,
CancellationToken cancellationToken = default
)
{
}
} }
} }
+1 -1
View File
@@ -1,4 +1,5 @@
using System; using System;
using AutoMapper;
using System.Linq; using System.Linq;
using xModels.Dtos; using xModels.Dtos;
using xIds.DbContext; using xIds.DbContext;
@@ -14,7 +15,6 @@ using IdentityServer4.Extensions;
using xIdentityModels.Extensions; using xIdentityModels.Extensions;
using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using AutoMapper;
namespace xIds.Providers namespace xIds.Providers
{ {
+389
View File
@@ -0,0 +1,389 @@
using System;
using System.Linq;
using xIds.Interfaces;
using System.Threading;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityModels.Models;
using xIdentityService.Models;
using xIdentityModels.Constants;
using System.Collections.Generic;
using IdentityServer4.Extensions;
using xIdentityService.Interfaces;
using xIdentityService.Extensions;
using Microsoft.AspNetCore.Authorization;
namespace xIds.Providers
{
public partial class XAuthorizationProvider : IXAuthorizationProvider
{
//
private readonly IXRoleProvider roles;
private readonly IXScopeProvider scopes;
private readonly IXIdentityManager manager;
private readonly IXPolicyProvider policies;
private readonly IXAuthorizationCache cache;
private readonly IXRoleHierarchyResolver resolver;
public XAuthorizationProvider(
IXRoleProvider roles,
IXScopeProvider scopes,
IXIdentityManager manager,
IXPolicyProvider policies,
IXAuthorizationCache cache,
IXRoleHierarchyResolver resolver
)
{
//
this.roles = roles;
this.cache = cache;
this.scopes = scopes;
this.manager = manager;
this.policies = policies;
this.resolver = resolver;
}
//
#region Commons ...
/// <summary>
/// Clear Local Cache and Notify other Instances ...
/// </summary>
/// <param name="policyName"></param>
/// <returns></returns>
public async Task InvalidateAsync(string policyName = null)
{
//
if (policyName.IsNullOrEmpty())
{
cache.Clear();
}
else
{
cache.RemovePolicy(policyName);
}
}
/// <summary>
/// Build Authorization Policy ...
/// </summary>
/// <param name="policyName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<AuthorizationPolicy> BuildAuthorizationPolicyAsync(
string policyName,
CancellationToken cancellationToken = default
)
{
//
var effective = await GetEffectiveAuthorizationAsync(policyName, cancellationToken);
//
var result = effective.ToAuthorizationPolicy();
return result;
}
/// <summary>
/// Get Effective Authorization ...
/// </summary>
/// <param name="target"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XEffectiveAuthorizationDto> GetEffectiveAuthorizationAsync(
XUserClaimsInfoDto target,
CancellationToken cancellationToken = default
)
{
//
// Define Result ...
var result = new XEffectiveAuthorizationDto
{
EffectiveClaims = [],
RequireEnabledUser = !target.IsNull(),
RequireAuthenticatedUser = !target.IsNull(),
EffectiveRoles = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
EffectiveScopes = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
};
//
// Validate ...
if (target.IsNull())
{
return result;
}
//
// Effective roles = the user's actual roles (from RoleManager) ...
var userRoles = await GetUserRolesAsync(
cancellationToken: cancellationToken,
userId: target.GetUserSelectByParam(userSelectBy: XUserSelectBy.ID)
);
foreach (var role in userRoles)
{
result.EffectiveRoles.Add(role);
}
//
// NOTE: EffectiveScopes / EffectiveClaims aggregation is wired here from
// the user's scope / claim source on XUserClaimsInfoDto (xIdentityModels).
return result;
}
/// <summary>
/// Get Effective Authorization ...
/// </summary>
/// <param name="policyName"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XEffectiveAuthorizationDto> GetEffectiveAuthorizationAsync(
string policyName,
CancellationToken cancellationToken = default
)
{
//
if (policyName.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var policy = await FindPolicyOrThrowAsync(policyName, cancellationToken);
var effective = await ToDtoWithEffectiveRolesAsync(policy, cancellationToken);
if (effective.IsNull())
{
XException.InvalidConfiguration.Throw();
}
//
return effective;
}
#endregion
//
#region Private ...
private async Task ValidateReferencesAsync(
XPolicyDefinitionDto item,
CancellationToken cancellationToken
)
{
//
// Defensive guard ...
if (item.IsNull())
{
XException.InvalidArgs.Throw();
}
//
// The DTO stores RequiredRoles / RequiredScopes as CSV strings.
// Parse them into collections ONCE (ParseListString NREs on a null
// string, so guard first) ...
//
var requiredRoles = item.RequiredRoles.IsNullOrEmpty()
? []
: item.RequiredRoles.ParseListString<string>().ToList();
//
var requiredScopes = item.RequiredScopes.IsNullOrEmpty()
? []
: item.RequiredScopes.ParseListString<string>().ToList();
//
// Referenced Roles must exist ...
if (requiredRoles.HasChild())
{
//
var existingRoles = new HashSet<string>(
(await roles.GetAllAsync(cancellationToken: cancellationToken))
.Select(r => r.Name.ToNormalString()),
StringComparer.OrdinalIgnoreCase
);
if (requiredRoles.Any(r => !existingRoles.Contains(r.ToNormalString())))
{
XException.NotFound.Throw();
}
}
//
// Referenced Scopes must exist ...
if (requiredScopes.HasChild())
{
//
var existingScopes = new HashSet<string>(
(await scopes.GetAllAsync(cancellationToken: cancellationToken))
.Select(s => s.Name.ToNormalString()),
StringComparer.OrdinalIgnoreCase
);
if (requiredScopes.Any(s => !existingScopes.Contains(s.ToNormalString())))
{
XException.NotFound.Throw();
}
}
}
public async Task<IEnumerable<string>> GetUserRolesAsync(
string userId,
CancellationToken cancellationToken = default
)
{
//
if (userId.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
cancellationToken.ThrowIfCancellationRequested();
//
var user = await manager.UserManager.FindByIdAsync(userId);
if (user.IsNull())
{
XException.NotFound.Throw();
}
//
cancellationToken.ThrowIfCancellationRequested();
//
var result = await manager.UserManager.GetRolesAsync(user);
return result;
}
private async Task<XRoleDefinitionDto> FindRoleOrThrowAsync(
string name,
CancellationToken cancellationToken
)
{
//
if (name.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var normalized = name.ToNormalString();
var result = await roles.FindOneAsync(
predicate: r => r.Name.ToLower() == normalized,
cancellationToken: cancellationToken
);
if (result.IsNull())
{
XException.NotFound.Throw();
}
//
return result;
}
private async Task<XScopeDefinitionDto> FindScopeOrThrowAsync(
string name,
CancellationToken cancellationToken
)
{
//
if (name.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var normalized = name.ToNormalString();
var result = await scopes.FindOneAsync(
predicate: s => s.Name.ToLower() == normalized,
cancellationToken: cancellationToken
);
if (result.IsNull())
{
XException.NotFound.Throw();
}
//
return result;
}
private async Task<XPolicyDefinitionDto> FindPolicyOrThrowAsync(
string name,
CancellationToken cancellationToken
)
{
//
if (name.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var normalized = name.ToNormalString();
var result = await policies.FindOneAsync(
predicate: p => p.Name.ToLower() == normalized,
cancellationToken: cancellationToken
);
if (result.IsNull())
{
XException.NotFound.Throw();
}
//
return result;
}
private async Task<XEffectiveAuthorizationDto> ToDtoWithEffectiveRolesAsync(
XPolicyDefinitionDto item,
CancellationToken cancellationToken = default
)
{
//
// Null / nameless guard ...
if (item.IsNull() || item.Name.IsNullOrEmpty())
{
return null;
}
//
// Parse the DTO's CSV-string RequiredRoles. ParseListString NREs on a
// null string, so guard first; the resolver itself is null-safe on an
// empty explicitRoles set ...
var explicitRoles = item.RequiredRoles.IsNullOrEmpty()
? null
: item.RequiredRoles.ParseListString<string>();
//
// Resolve the effective role set
// (explicit RequiredRoles U roles by MinRoleWeight U parent chain) ...
var effectiveRoles = await resolver.ResolveEffectiveRolesAsync(
explicitRoles: explicitRoles,
minRoleWeight: item.MinRoleWeight,
cancellationToken: cancellationToken
);
//
// Project onto XEffectiveAuthorizationDto - the ONLY DTO that carries
// EffectiveRoles / EffectiveScopes / EffectiveClaims. Each CSV / JSON
// field is null-guarded here (the shared ToEffectiveAuthorization
// extension calls ParseListString on RequiredScopes without a null
// guard, so the projection is built inline to stay null-safe) ...
var result = new XEffectiveAuthorizationDto
{
PolicyName = item.Name,
RequireEnabledUser = item.RequireEnabledUser,
RequireAuthenticatedUser = item.RequireAuthenticatedUser,
EffectiveClaims = item.RequiredClaims.ToRequiredClaims(),
EffectiveScopes = item.RequiredScopes.IsNullOrEmpty()
? new HashSet<string>(StringComparer.OrdinalIgnoreCase)
: new HashSet<string>(
item.RequiredScopes.ParseListString<string>(),
StringComparer.OrdinalIgnoreCase
),
EffectiveRoles = effectiveRoles.HasChild()
? new HashSet<string>(effectiveRoles, StringComparer.OrdinalIgnoreCase)
: new HashSet<string>(StringComparer.OrdinalIgnoreCase),
};
//
return result;
}
#endregion
}
}
@@ -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
}
}
@@ -0,0 +1,249 @@
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
{
public partial class XAuthorizationProvider
{
//
#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,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (item.IsNull() ||
item.Name.IsNullOrEmpty() ||
userInfo.IsNullOrDefault()
)
{
XException.InvalidArgs.Throw();
}
//
// Duplicate check via repository (NOT AsQueryable) ...
var normalized = item.Name.ToNormalString();
var exists = await roles.FindOneAsync(
predicate: r => r.Name.ToLower() == normalized,
cancellationToken: cancellationToken
);
if (!exists.IsNull())
{
XException.Duplicate.Throw();
}
//
// Persist locally first
item.IsSystem = false;
var result = await roles.AddAsync(
item: item,
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
// Sync to IdentityServer — MUST check result
var identityResult = await manager.CreateRoleAsync(result.Name);
if (!identityResult.Succeeded)
{
//
// Rollback local insert to avoid permanent drift
await roles.RemoveAsync(
id: result.Id,
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
XException.ActionFailed.Throw();
}
//
await InvalidateAsync();
return result;
}
public async Task<XRoleDefinitionDto> UpdateRoleAsync(
string name,
XRoleDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
)
{
//
if (name.IsNullOrEmpty() || item.IsNull())
{
XException.InvalidArgs.Throw();
}
//
var existing = await FindRoleOrThrowAsync(name, cancellationToken);
if (existing.IsSystem)
{
XException.NotAllowed.Throw();
}
//
var updated = await roles.UpdateAsync(
item: item,
id: existing.Id,
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
// Sync to IdentityServer — rename requires delete+create in IdentityServer
if (!string.Equals(
existing.Name,
updated.Name,
StringComparison.OrdinalIgnoreCase)
)
{
//
var usersInRole = await manager.UserManager
.GetUsersInRoleAsync(existing.Name.ToNormalString());
//
await manager.DeleteRoleAsync(
existing.Name,
cancellationToken
);
//
var identityResult = await manager.CreateRoleAsync(updated.Name);
if (!identityResult.Succeeded)
{
XException.ActionFailed.Throw();
}
//
foreach (var user in usersInRole)
{
//
await manager.AddUserToRoleAsync(
user: user,
roleName: updated.Name
);
}
}
//
await InvalidateAsync();
return updated;
}
public async Task<IEnumerable<XRoleDefinitionDto>> GetRolesAsync(
CancellationToken cancellationToken = default
)
{
//
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.InvalidArgs.Throw();
}
//
var result = await roles.QueryAsync(
query: query,
cancellationToken: cancellationToken
);
//
return result;
}
#endregion
}
}
@@ -0,0 +1,156 @@
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
{
public partial class XAuthorizationProvider
{
//
#region Scope ...
public async Task<bool> RemoveScopeAsync(
string name,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
)
{
//
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(
string name,
CancellationToken cancellationToken = default
)
{
return await FindScopeOrThrowAsync(name, cancellationToken);
}
public async Task<XScopeDefinitionDto> AddScopeAsync(
XScopeDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
)
{
//
if (item.IsNull() || item.Name.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var normalized = item.Name.ToNormalString();
var exists = await scopes.FindOneAsync(
predicate: s => s.Name.ToLower() == normalized,
cancellationToken: cancellationToken);
if (!exists.IsNull())
{
XException.Duplicate.Throw();
}
//
item.IsSystem = false;
var result = await scopes.AddAsync(
item: item,
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
await InvalidateAsync();
return result;
}
public async Task<XScopeDefinitionDto> UpdateScopeAsync(
string name,
XScopeDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
)
{
//
if (name.IsNullOrEmpty() || item.IsNull())
{
XException.InvalidArgs.Throw();
}
//
var existing = await FindScopeOrThrowAsync(name, cancellationToken);
if (existing.IsSystem)
{
XException.NotAllowed.Throw();
}
//
var updated = await scopes.UpdateAsync(
item: item,
id: existing.Id,
userInfo: userInfo,
cancellationToken: cancellationToken
);
//
await InvalidateAsync();
return updated;
}
public async Task<IEnumerable<XScopeDefinitionDto>> GetScopesAsync(
CancellationToken cancellationToken = default
)
{
return await scopes
.GetAllAsync(cancellationToken: cancellationToken);
}
public async Task<XQueryResult<XScopeDefinitionDto>> QueryScopesAsync(
XQuery query,
CancellationToken cancellationToken = default
)
{
//
if (query.IsNull())
{
XException.InvalidArgs.Throw();
}
//
var result = await scopes.QueryAsync(
query: query,
cancellationToken: cancellationToken
);
//
return result;
}
#endregion
}
}
+99
View File
@@ -0,0 +1,99 @@
using xCommons.Extensions;
using System.Threading.Tasks;
using xIdentityService.Interfaces;
using xIdentityService.Extensions;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
namespace xIds.Providers
{
/// <summary>
/// Resolve Policies from Cache → Repository → Default (static) Provider ...
/// </summary>
public class XDynamicPolicyProvider : IAuthorizationPolicyProvider
{
private readonly IXAuthorizationCache cache;
private readonly IServiceScopeFactory scopeFactory;
private readonly DefaultAuthorizationPolicyProvider fallback;
public XDynamicPolicyProvider(
IXAuthorizationCache cache,
IServiceScopeFactory scopeFactory,
IOptions<AuthorizationOptions> options
)
{
//
this.cache = cache;
this.scopeFactory = scopeFactory;
fallback = new DefaultAuthorizationPolicyProvider(options);
}
public Task<AuthorizationPolicy> GetDefaultPolicyAsync() =>
fallback.GetDefaultPolicyAsync();
public async Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
{
//
if (policyName.IsNullOrEmpty())
{
return await fallback.GetPolicyAsync(policyName);
}
//
// 1. Cache ...
if (cache.TryGetPolicy(policyName, out var cached))
{
return cached;
}
//
// 2. Repository (needs a Scope because Provider is Singleton) ...
using (var scope = scopeFactory.CreateScope())
{
//
var repository = scope.ServiceProvider.GetService<IXPolicyProvider>();
var resolver = scope.ServiceProvider.GetService<IXRoleHierarchyResolver>();
//
if (!repository.IsNull() && !resolver.IsNull())
{
//
var normalized = policyName.ToNormalString();
var definition = await repository.FindOneAsync(
predicate: p => p.IsEnabled && p.Name.ToLower() == normalized
);
//
var requiredRoles = definition.RequiredRoles
.ParseListString<string>();
if (!definition.IsNull())
{
//
var roles = await resolver.ResolveEffectiveRolesAsync(
explicitRoles: requiredRoles,
minRoleWeight: definition.MinRoleWeight
);
//
var policy = definition.ToAuthorizationPolicy(roles);
if (!policy.IsNull())
{
cache.SetPolicy(policyName, policy);
return policy;
}
}
}
}
//
// 3. Fallback to Static Policies (LocalApi.PolicyName, XPolicies.*) ...
return await fallback.GetPolicyAsync(policyName);
}
public Task<AuthorizationPolicy> GetFallbackPolicyAsync()
{
return Task.FromResult<AuthorizationPolicy>(null);
}
}
}
@@ -1,11 +1,11 @@
using System; using System;
using System.Threading.Tasks; using xIdentityModels;
using Microsoft.AspNetCore.Http;
using xCommons.Extensions; using xCommons.Extensions;
using xExceptions.Constants; using xExceptions.Constants;
using xIdentityModels;
using xIdentityModels.Constants;
using xIdentityModels.Models; using xIdentityModels.Models;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using xIdentityModels.Constants;
using xIdentityModels.Navigations; using xIdentityModels.Navigations;
namespace xIds.Providers namespace xIds.Providers
@@ -1,5 +1,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using xCommons.Extensions; using xCommons.Extensions;
@@ -211,6 +212,55 @@ namespace xIds.Providers
return result; return result;
} }
/// <summary>
/// Delete a Role from Identity store (AspNetRoles) and cascade remove
/// all user assignments (AspNetUserRoles).
/// </summary>
/// <param name="roleName">role name</param>
/// <param name="cancellationToken">cancellation token (best-effort; Identity APIs are not cancellable)</param>
/// <returns>an instance of <see>IdentityResult</see></returns>
public async Task<IdentityResult> DeleteRoleAsync(
string roleName,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (roleName.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
// Honor cancellation at the entry point. RoleManager.DeleteAsync does not
// accept a CancellationToken, so this is a best-effort check before the call.
cancellationToken.ThrowIfCancellationRequested();
//
// Retrieve the role — throws XException.NotFound if it does not exist
var role = await GetRoleAsync(roleName);
//
var usersInRole = await UserManager.GetUsersInRoleAsync(roleName);
foreach(var user in usersInRole)
{
//
await UserManager.RemoveFromRoleAsync(
user: user,
role: roleName
);
}
//
// Persist deletion. EF cascades to AspNetUserRoles automatically
// under the default Identity configuration (IdentityUserRole<string>).
var result = await RoleManager.DeleteAsync(role);
//
// Return Result ...
return result;
}
/// <summary> /// <summary>
/// Check a User is Adminr not /// Check a User is Adminr not
/// </summary> /// </summary>
@@ -1,11 +1,11 @@
using System.Threading.Tasks;
using xCommons.Extensions;
using xExceptions.Constants;
using xIdentityModels.Dtos;
using xModels.Dtos;
using xDataService.Extensions;
using xIds.Extensions;
using System.Linq; using System.Linq;
using xModels.Dtos;
using xIds.Extensions;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xDataService.Extensions;
using xIdentityModels.Extensions; using xIdentityModels.Extensions;
namespace xIds.Providers namespace xIds.Providers
+794
View File
@@ -0,0 +1,794 @@
using System;
using AutoMapper;
using System.Linq;
using xModels.Dtos;
using xIds.DbContext;
using System.Threading;
using xCommons.Extensions;
using xIds.Configurations;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityModels.Models;
using System.Linq.Expressions;
using xDataService.Extensions;
using xIdentityModels.Extensions;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace xIds.Providers
{
public class XPolicyProvider : IXPolicyProvider
{
//
private readonly string permittedRole;
private readonly XIdentityDbContext dbContext;
private readonly XDataServiceConfiguration configuration;
private readonly Action<IMapperConfigurationExpression> mapperConfigurationExp;
public XPolicyProvider(
XIdentityDbContext dbContext,
XDataServiceConfiguration configuration,
string permittedRole = "admin"
)
{
//
this.dbContext = dbContext;
this.permittedRole = permittedRole;
this.configuration = configuration;
//
// Configure Mapper Options ...
mapperConfigurationExp = cfg =>
{
//
cfg.CreateMap<XRoleDefinition, XRoleDefinitionDto>()
.ReverseMap();
//
cfg.CreateMap<XScopeDefinition, XScopeDefinitionDto>()
.ReverseMap();
//
cfg.CreateMap<XPolicyDefinition, XPolicyDefinitionDto>()
.ReverseMap();
};
}
//
#region Permission ...
private bool HasPermission(
XUserClaimsInfoDto userInfo = null
)
{
//
var result = permittedRole.IsNullOrEmpty();
if (result)
{
return result;
}
//
result =
!userInfo.IsNullOrDefault() &&
userInfo.Roles
.Any(ur => ur.Equals(
permittedRole,
StringComparison.InvariantCultureIgnoreCase));
//
return result;
}
#endregion
//
#region Readers ...
/// <summary>
/// retrieve whole items as queryable ...
/// </summary>
/// <param name="asNoTracking">a flag for Tracking behaviour</param>
/// <param name="predicate">an Expression for Filter Items ...</param>
/// <param name="orderBuilder">an Order Builder expression for Ordering Query ...</param>
/// <returns></returns>
public virtual IQueryable<XPolicyDefinition> AsQueryable(
bool asNoTracking = true,
Expression<Func<XPolicyDefinition, bool>> predicate = null,
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null
)
{
//
var result = dbContext.PolicyDefinitions
.Where(predicate)
.AsQueryable();
if (asNoTracking)
{
result = result.AsNoTracking();
}
//
return result;
}
/// <summary>
/// retrieve an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> GetAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
//
var result = await FindOneAsync(x => x.Id.Equals(id));
if (result.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
return result;
}
/// <summary>
/// retrieve all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XPolicyDefinitionDto>> GetAllAsync(
bool ignoreSoftDeleteds = true,
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XPolicyDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
predicate: predicator,
orderBuilder: orderBuilder
);
//
var items = await queryable
.ToListAsync(cancellationToken);
var result = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// find an Entity by providing a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> FindOneAsync(
Expression<Func<XPolicyDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XPolicyDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
orderBuilder: null,
predicate: predicator
);
//
var item = await queryable
.FirstOrDefaultAsync(cancellationToken);
var result = await EnrichAsync(
source: item,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// find a collection of Entities by proving a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XPolicyDefinitionDto>> FindManyAsync(
Expression<Func<XPolicyDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XPolicyDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
predicate: predicator,
orderBuilder: orderBuilder
);
//
var items = await queryable
.ToListAsync(cancellationToken);
var result = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// count all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<int> CountAsync(
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XPolicyDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
orderBuilder: null,
predicate: predicator
);
//
var result = await queryable.CountAsync();
//
return result;
}
/// <summary>
/// count all exists Entities Pages by providing page size ...
/// </summary>
/// <param name="pageSize"></param>
/// <param name="totalItems"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<int> PagesCountAsync(
int pageSize,
int? totalItems = null,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
int count = totalItems.HasValue ? totalItems.Value : await CountAsync(
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
int pagesCount = count / pageSize;
//
if (count % pageSize > 0)
{
pagesCount++;
}
//
return pagesCount;
}
/// <summary>
/// Check an Entity exists or not ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> IsExistsAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
var result = false;
//
try
{
//
var exists = await GetAsync(
id: id,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
//
result = !exists.IsNullOrDefault();
}
catch
{ }
//
return result;
}
#endregion
//
#region Query ...
/// <summary>
/// retrieve Entities based on XQuery Pagination structure ...
/// </summary>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="predicate"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XQueryResult<XPolicyDefinitionDto>> QueryAsync(
XQuery query,
bool ignoreSoftDeleteds = true,
Expression<Func<XPolicyDefinition, bool>> predicate = null,
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Normalize Query ...
query = NormalizeQuery(
source: query,
configuration: configuration
);
//
var items = await GetAllAsync(
orderBuilder: orderBuilder,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
var totalItemsCount = items.Count();
//
// Apply Filter ...
if (!query.Filter.IsNullOrEmpty())
{
//
items = items
.ApplyFilter(query.Filter);
}
int filteredItemsCount = items.Count();
//
// Count Pages ...
var totalPagesCount = query.CountPages(totalItemsCount);
var filteredPagesCount = query.CountPages(filteredItemsCount);
//
// Apply Paging and Sorting ...
if (totalItemsCount > 0 &&
filteredItemsCount > 0)
{
//
// Apply Sorting ...
items = items
.ToList()
.ApplySorting(
query.SortBy,
query.IsAscending
);
//
// Apply Paging ...
items = items
.ToList()
.ApplyPaging(
query.Page,
query.PageSize
);
}
//
var resultItems = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
// Prepare Result ...
var result = new XQueryResult<XPolicyDefinitionDto>
{
Page = query.Page,
Items = [.. resultItems],
PageSize = query.PageSize,
TotalPages = totalPagesCount,
TotalItems = totalItemsCount,
TotalFilteredPages = filteredPagesCount,
TotalFilteredItems = filteredItemsCount
};
//
return result;
}
#endregion
//
#region Add/Update/Remove ...
/// <summary>
/// add a new Entity ...
/// </summary>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> AddAsync(
XPolicyDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!item.IsValidForAdd())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
var entity = item.MapConvert<XPolicyDefinition, XPolicyDefinitionDto>();
var entry = await dbContext.PolicyDefinitions.AddAsync(
entity: entity,
cancellationToken: cancellationToken
);
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
/// <summary>
/// Update an Entity values ...
/// </summary>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> UpdateAsync(
int id,
XPolicyDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (id != item.Id ||
!id.IsValidIntId() ||
!item.IsValidForAdd())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
// Retrieve Exists Entity ...
var exists = await dbContext.PolicyDefinitions
.FirstOrDefaultAsync(x => x.Id == id && !x.Deleted);
if (exists.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Update Data on Exists Entity ...
exists = exists.UpdateData(
updateWith: item,
propertyWhiteList: [],
propertyBlackList: [
nameof(XPolicyDefinition.Id),
]
);
//
var entry = dbContext.PolicyDefinitions.Attach(exists);
entry.State = EntityState.Modified;
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
/// <summary>
/// remove an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="softDelete"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> RemoveAsync(
int id,
bool softDelete = true,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
// Retrieve Exists Entity ...
var exists = await dbContext.PolicyDefinitions
.FirstOrDefaultAsync(x => x.Id == id && !x.Deleted);
if (exists.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
EntityEntry<XPolicyDefinition> entry = null;
if (softDelete)
{
//
exists.Deleted = true;
entry = dbContext.PolicyDefinitions.Update(exists);
}
else
{
entry = dbContext.PolicyDefinitions.Remove(exists);
}
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
#endregion
//
#region Custom ...
/// <summary>
/// Normalize an XQuery based on Data Service Configurations ...
/// </summary>
/// <param name="source"></param>
/// <param name="configuration"></param>
/// <returns></returns>
public XQuery NormalizeQuery(
XQuery source,
XDataServiceConfiguration configuration //
)
{
//
if (source.IsNull())
{
source = new XQuery();
}
//
// Page Size Normalization ...
if (source.PageSize < configuration.PagingConfiguration.MinAvailablePageSize)
{
source.PageSize = configuration.PagingConfiguration.MinAvailablePageSize;
}
if (source.PageSize > configuration.PagingConfiguration.MaxAvailablePageSize)
{
source.PageSize = configuration.PagingConfiguration.MaxAvailablePageSize;
}
//
return source;
}
#endregion
//
#region Enrichers ...
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> EnrichAsync(
XPolicyDefinition source,
CancellationToken cancellationToken = default
)
{
//
var result = source.MapConvert<XPolicyDefinitionDto, XPolicyDefinition>();
result = await EnrichAsync(
source: result,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XPolicyDefinitionDto> EnrichAsync(
XPolicyDefinitionDto source,
CancellationToken cancellationToken = default
)
{
//
var result = await Task.FromResult(source);
return result;
}
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XPolicyDefinitionDto>> EnrichRangeAsync(
IEnumerable<XPolicyDefinition> sources,
CancellationToken cancellationToken = default
)
{
//
var tasks = sources
.Select(s => EnrichAsync(s, cancellationToken));
//
var result = await Task.WhenAll(tasks);
//
return result;
}
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XPolicyDefinitionDto>> EnrichRangeAsync(
IEnumerable<XPolicyDefinitionDto> sources,
CancellationToken cancellationToken = default
)
{
//
var tasks = sources
.Select(s => EnrichAsync(s, cancellationToken));
//
var result = await Task.WhenAll(tasks);
//
return result;
}
#endregion
}
}
+794
View File
@@ -0,0 +1,794 @@
using System;
using AutoMapper;
using System.Linq;
using xModels.Dtos;
using xIds.DbContext;
using System.Threading;
using xIds.Configurations;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using xIdentityModels.Models;
using System.Threading.Tasks;
using xDataService.Extensions;
using System.Linq.Expressions;
using xIdentityModels.Extensions;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace xIds.Providers
{
public class XRoleProvider : IXRoleProvider
{
//
private readonly string permittedRole;
private readonly XIdentityDbContext dbContext;
private readonly XDataServiceConfiguration configuration;
private readonly Action<IMapperConfigurationExpression> mapperConfigurationExp;
public XRoleProvider(
XIdentityDbContext dbContext,
XDataServiceConfiguration configuration,
string permittedRole = "admin"
)
{
//
this.dbContext = dbContext;
this.permittedRole = permittedRole;
this.configuration = configuration;
//
// Configure Mapper Options ...
mapperConfigurationExp = cfg =>
{
//
cfg.CreateMap<XRoleDefinition, XRoleDefinitionDto>()
.ReverseMap();
//
cfg.CreateMap<XScopeDefinition, XScopeDefinitionDto>()
.ReverseMap();
//
cfg.CreateMap<XPolicyDefinition, XPolicyDefinitionDto>()
.ReverseMap();
};
}
//
#region Permission ...
private bool HasPermission(
XUserClaimsInfoDto userInfo = null
)
{
//
var result = permittedRole.IsNullOrEmpty();
if (result)
{
return result;
}
//
result =
!userInfo.IsNullOrDefault() &&
userInfo.Roles
.Any(ur => ur.Equals(
permittedRole,
StringComparison.InvariantCultureIgnoreCase));
//
return result;
}
#endregion
//
#region Readers ...
/// <summary>
/// retrieve whole items as queryable ...
/// </summary>
/// <param name="asNoTracking">a flag for Tracking behaviour</param>
/// <param name="predicate">an Expression for Filter Items ...</param>
/// <param name="orderBuilder">an Order Builder expression for Ordering Query ...</param>
/// <returns></returns>
public virtual IQueryable<XRoleDefinition> AsQueryable(
bool asNoTracking = true,
Expression<Func<XRoleDefinition, bool>> predicate = null,
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null
)
{
//
var result = dbContext.RoleDefinitions
.Where(predicate)
.AsQueryable();
if (asNoTracking)
{
result = result.AsNoTracking();
}
//
return result;
}
/// <summary>
/// retrieve an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> GetAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
//
var result = await FindOneAsync(x => x.Id.Equals(id));
if (result.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
return result;
}
/// <summary>
/// retrieve all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XRoleDefinitionDto>> GetAllAsync(
bool ignoreSoftDeleteds = true,
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XRoleDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
predicate: predicator,
orderBuilder: orderBuilder
);
//
var items = await queryable
.ToListAsync(cancellationToken);
var result = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// find an Entity by providing a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> FindOneAsync(
Expression<Func<XRoleDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XRoleDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
orderBuilder: null,
predicate: predicator
);
//
var item = await queryable
.FirstOrDefaultAsync(cancellationToken);
var result = await EnrichAsync(
source: item,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// find a collection of Entities by proving a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XRoleDefinitionDto>> FindManyAsync(
Expression<Func<XRoleDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XRoleDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
predicate: predicator,
orderBuilder: orderBuilder
);
//
var items = await queryable
.ToListAsync(cancellationToken);
var result = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// count all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<int> CountAsync(
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XRoleDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
orderBuilder: null,
predicate: predicator
);
//
var result = await queryable.CountAsync();
//
return result;
}
/// <summary>
/// count all exists Entities Pages by providing page size ...
/// </summary>
/// <param name="pageSize"></param>
/// <param name="totalItems"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<int> PagesCountAsync(
int pageSize,
int? totalItems = null,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
int count = totalItems.HasValue ? totalItems.Value : await CountAsync(
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
int pagesCount = count / pageSize;
//
if (count % pageSize > 0)
{
pagesCount++;
}
//
return pagesCount;
}
/// <summary>
/// Check an Entity exists or not ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> IsExistsAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
var result = false;
//
try
{
//
var exists = await GetAsync(
id: id,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
//
result = !exists.IsNullOrDefault();
}
catch
{ }
//
return result;
}
#endregion
//
#region Query ...
/// <summary>
/// retrieve Entities based on XQuery Pagination structure ...
/// </summary>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="predicate"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XQueryResult<XRoleDefinitionDto>> QueryAsync(
XQuery query,
bool ignoreSoftDeleteds = true,
Expression<Func<XRoleDefinition, bool>> predicate = null,
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Normalize Query ...
query = NormalizeQuery(
source: query,
configuration: configuration
);
//
var items = await GetAllAsync(
orderBuilder: orderBuilder,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
var totalItemsCount = items.Count();
//
// Apply Filter ...
if (!query.Filter.IsNullOrEmpty())
{
//
items = items
.ApplyFilter(query.Filter);
}
int filteredItemsCount = items.Count();
//
// Count Pages ...
var totalPagesCount = query.CountPages(totalItemsCount);
var filteredPagesCount = query.CountPages(filteredItemsCount);
//
// Apply Paging and Sorting ...
if (totalItemsCount > 0 &&
filteredItemsCount > 0)
{
//
// Apply Sorting ...
items = items
.ToList()
.ApplySorting(
query.SortBy,
query.IsAscending
);
//
// Apply Paging ...
items = items
.ToList()
.ApplyPaging(
query.Page,
query.PageSize
);
}
//
var resultItems = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
// Prepare Result ...
var result = new XQueryResult<XRoleDefinitionDto>
{
Page = query.Page,
Items = [.. resultItems],
PageSize = query.PageSize,
TotalPages = totalPagesCount,
TotalItems = totalItemsCount,
TotalFilteredPages = filteredPagesCount,
TotalFilteredItems = filteredItemsCount
};
//
return result;
}
#endregion
//
#region Add/Update/Remove ...
/// <summary>
/// add a new Entity ...
/// </summary>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> AddAsync(
XRoleDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!item.IsValidForAdd())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
var entity = item.MapConvert<XRoleDefinition, XRoleDefinitionDto>();
var entry = await dbContext.RoleDefinitions.AddAsync(
entity: entity,
cancellationToken: cancellationToken
);
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
/// <summary>
/// Update an Entity values ...
/// </summary>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> UpdateAsync(
int id,
XRoleDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (id != item.Id ||
!id.IsValidIntId() ||
!item.IsValidForAdd())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
// Retrieve Exists Entity ...
var exists = await dbContext.RoleDefinitions
.FirstOrDefaultAsync(x => x.Id == id && !x.Deleted);
if (exists.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Update Data on Exists Entity ...
exists = exists.UpdateData(
updateWith: item,
propertyWhiteList: [],
propertyBlackList: [
nameof(XPolicyDefinition.Id),
]
);
//
var entry = dbContext.RoleDefinitions.Attach(exists);
entry.State = EntityState.Modified;
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
/// <summary>
/// remove an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="softDelete"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> RemoveAsync(
int id,
bool softDelete = true,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
// Retrieve Exists Entity ...
var exists = await dbContext.RoleDefinitions
.FirstOrDefaultAsync(x => x.Id == id && !x.Deleted);
if (exists.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
EntityEntry<XRoleDefinition> entry = null;
if (softDelete)
{
//
exists.Deleted = true;
entry = dbContext.RoleDefinitions.Update(exists);
}
else
{
entry = dbContext.RoleDefinitions.Remove(exists);
}
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
#endregion
//
#region Custom ...
/// <summary>
/// Normalize an XQuery based on Data Service Configurations ...
/// </summary>
/// <param name="source"></param>
/// <param name="configuration"></param>
/// <returns></returns>
public XQuery NormalizeQuery(
XQuery source,
XDataServiceConfiguration configuration //
)
{
//
if (source.IsNull())
{
source = new XQuery();
}
//
// Page Size Normalization ...
if (source.PageSize < configuration.PagingConfiguration.MinAvailablePageSize)
{
source.PageSize = configuration.PagingConfiguration.MinAvailablePageSize;
}
if (source.PageSize > configuration.PagingConfiguration.MaxAvailablePageSize)
{
source.PageSize = configuration.PagingConfiguration.MaxAvailablePageSize;
}
//
return source;
}
#endregion
//
#region Enrichers ...
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> EnrichAsync(
XRoleDefinition source,
CancellationToken cancellationToken = default
)
{
//
var result = source.MapConvert<XRoleDefinitionDto, XRoleDefinition>();
result = await EnrichAsync(
source: result,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XRoleDefinitionDto> EnrichAsync(
XRoleDefinitionDto source,
CancellationToken cancellationToken = default
)
{
//
var result = await Task.FromResult(source);
return result;
}
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XRoleDefinitionDto>> EnrichRangeAsync(
IEnumerable<XRoleDefinition> sources,
CancellationToken cancellationToken = default
)
{
//
var tasks = sources
.Select(s => EnrichAsync(s, cancellationToken));
//
var result = await Task.WhenAll(tasks);
//
return result;
}
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XRoleDefinitionDto>> EnrichRangeAsync(
IEnumerable<XRoleDefinitionDto> sources,
CancellationToken cancellationToken = default
)
{
//
var tasks = sources
.Select(s => EnrichAsync(s, cancellationToken));
//
var result = await Task.WhenAll(tasks);
//
return result;
}
#endregion
}
}
+794
View File
@@ -0,0 +1,794 @@
using System;
using AutoMapper;
using System.Linq;
using xModels.Dtos;
using xIds.DbContext;
using System.Threading;
using xCommons.Extensions;
using xIds.Configurations;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityModels.Models;
using xDataService.Extensions;
using System.Linq.Expressions;
using xIdentityModels.Extensions;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace xIds.Providers
{
public class XScopeProvider : IXScopeProvider
{
//
private readonly string permittedRole;
private readonly XIdentityDbContext dbContext;
private readonly XDataServiceConfiguration configuration;
private readonly Action<IMapperConfigurationExpression> mapperConfigurationExp;
public XScopeProvider(
XIdentityDbContext dbContext,
XDataServiceConfiguration configuration,
string permittedRole = "admin"
)
{
//
this.dbContext = dbContext;
this.permittedRole = permittedRole;
this.configuration = configuration;
//
// Configure Mapper Options ...
mapperConfigurationExp = cfg =>
{
//
cfg.CreateMap<XRoleDefinition, XRoleDefinitionDto>()
.ReverseMap();
//
cfg.CreateMap<XScopeDefinition, XScopeDefinitionDto>()
.ReverseMap();
//
cfg.CreateMap<XPolicyDefinition, XPolicyDefinitionDto>()
.ReverseMap();
};
}
//
#region Permission ...
private bool HasPermission(
XUserClaimsInfoDto userInfo = null
)
{
//
var result = permittedRole.IsNullOrEmpty();
if (result)
{
return result;
}
//
result =
!userInfo.IsNullOrDefault() &&
userInfo.Roles
.Any(ur => ur.Equals(
permittedRole,
StringComparison.InvariantCultureIgnoreCase));
//
return result;
}
#endregion
//
#region Readers ...
/// <summary>
/// retrieve whole items as queryable ...
/// </summary>
/// <param name="asNoTracking">a flag for Tracking behaviour</param>
/// <param name="predicate">an Expression for Filter Items ...</param>
/// <param name="orderBuilder">an Order Builder expression for Ordering Query ...</param>
/// <returns></returns>
public virtual IQueryable<XScopeDefinition> AsQueryable(
bool asNoTracking = true,
Expression<Func<XScopeDefinition, bool>> predicate = null,
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null
)
{
//
var result = dbContext.ScopeDefinitions
.Where(predicate)
.AsQueryable();
if (asNoTracking)
{
result = result.AsNoTracking();
}
//
return result;
}
/// <summary>
/// retrieve an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> GetAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
//
var result = await FindOneAsync(x => x.Id.Equals(id));
if (result.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
return result;
}
/// <summary>
/// retrieve all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XScopeDefinitionDto>> GetAllAsync(
bool ignoreSoftDeleteds = true,
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XScopeDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
predicate: predicator,
orderBuilder: orderBuilder
);
//
var items = await queryable
.ToListAsync(cancellationToken);
var result = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// find an Entity by providing a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> FindOneAsync(
Expression<Func<XScopeDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XScopeDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
orderBuilder: null,
predicate: predicator
);
//
var item = await queryable
.FirstOrDefaultAsync(cancellationToken);
var result = await EnrichAsync(
source: item,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// find a collection of Entities by proving a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XScopeDefinitionDto>> FindManyAsync(
Expression<Func<XScopeDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XScopeDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
predicate: predicator,
orderBuilder: orderBuilder
);
//
var items = await queryable
.ToListAsync(cancellationToken);
var result = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// count all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<int> CountAsync(
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
// Prepare Predicate ...
Expression<Func<XScopeDefinition, bool>> predicator = null;
if (ignoreSoftDeleteds)
{
predicator = x => !x.Deleted;
}
//
var queryable = AsQueryable(
asNoTracking: true,
orderBuilder: null,
predicate: predicator
);
//
var result = await queryable.CountAsync();
//
return result;
}
/// <summary>
/// count all exists Entities Pages by providing page size ...
/// </summary>
/// <param name="pageSize"></param>
/// <param name="totalItems"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<int> PagesCountAsync(
int pageSize,
int? totalItems = null,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
int count = totalItems.HasValue ? totalItems.Value : await CountAsync(
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
int pagesCount = count / pageSize;
//
if (count % pageSize > 0)
{
pagesCount++;
}
//
return pagesCount;
}
/// <summary>
/// Check an Entity exists or not ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> IsExistsAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
)
{
//
var result = false;
//
try
{
//
var exists = await GetAsync(
id: id,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
//
result = !exists.IsNullOrDefault();
}
catch
{ }
//
return result;
}
#endregion
//
#region Query ...
/// <summary>
/// retrieve Entities based on XQuery Pagination structure ...
/// </summary>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="predicate"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XQueryResult<XScopeDefinitionDto>> QueryAsync(
XQuery query,
bool ignoreSoftDeleteds = true,
Expression<Func<XScopeDefinition, bool>> predicate = null,
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
)
{
//
// Normalize Query ...
query = NormalizeQuery(
source: query,
configuration: configuration
);
//
var items = await GetAllAsync(
orderBuilder: orderBuilder,
cancellationToken: cancellationToken,
ignoreSoftDeleteds: ignoreSoftDeleteds
);
var totalItemsCount = items.Count();
//
// Apply Filter ...
if (!query.Filter.IsNullOrEmpty())
{
//
items = items
.ApplyFilter(query.Filter);
}
int filteredItemsCount = items.Count();
//
// Count Pages ...
var totalPagesCount = query.CountPages(totalItemsCount);
var filteredPagesCount = query.CountPages(filteredItemsCount);
//
// Apply Paging and Sorting ...
if (totalItemsCount > 0 &&
filteredItemsCount > 0)
{
//
// Apply Sorting ...
items = items
.ToList()
.ApplySorting(
query.SortBy,
query.IsAscending
);
//
// Apply Paging ...
items = items
.ToList()
.ApplyPaging(
query.Page,
query.PageSize
);
}
//
var resultItems = await EnrichRangeAsync(
sources: items,
cancellationToken: cancellationToken
);
//
// Prepare Result ...
var result = new XQueryResult<XScopeDefinitionDto>
{
Page = query.Page,
Items = [.. resultItems],
PageSize = query.PageSize,
TotalPages = totalPagesCount,
TotalItems = totalItemsCount,
TotalFilteredPages = filteredPagesCount,
TotalFilteredItems = filteredItemsCount
};
//
return result;
}
#endregion
//
#region Add/Update/Remove ...
/// <summary>
/// add a new Entity ...
/// </summary>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> AddAsync(
XScopeDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!item.IsValidForAdd())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
var entity = item.MapConvert<XScopeDefinition, XScopeDefinitionDto>();
var entry = await dbContext.ScopeDefinitions.AddAsync(
entity: entity,
cancellationToken: cancellationToken
);
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
/// <summary>
/// Update an Entity values ...
/// </summary>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> UpdateAsync(
int id,
XScopeDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (id != item.Id ||
!id.IsValidIntId() ||
!item.IsValidForAdd())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
// Retrieve Exists Entity ...
var exists = await dbContext.ScopeDefinitions
.FirstOrDefaultAsync(x => x.Id == id && !x.Deleted);
if (exists.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
// Update Data on Exists Entity ...
exists = exists.UpdateData(
updateWith: item,
propertyWhiteList: [],
propertyBlackList: [
nameof(XPolicyDefinition.Id),
]
);
//
var entry = dbContext.ScopeDefinitions.Attach(exists);
entry.State = EntityState.Modified;
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
/// <summary>
/// remove an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="softDelete"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> RemoveAsync(
int id,
bool softDelete = true,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
//
// Permission ...
var hasPermission = HasPermission(userInfo);
if (!hasPermission)
{
XException.NotAuthorized.Throw();
}
//
// Retrieve Exists Entity ...
var exists = await dbContext.ScopeDefinitions
.FirstOrDefaultAsync(x => x.Id == id && !x.Deleted);
if (exists.IsNullOrDefault())
{
XException.NotFound.Throw();
}
//
EntityEntry<XScopeDefinition> entry = null;
if (softDelete)
{
//
exists.Deleted = true;
entry = dbContext.ScopeDefinitions.Update(exists);
}
else
{
entry = dbContext.ScopeDefinitions.Remove(exists);
}
//
var changes = await dbContext.SaveChangesAsync(cancellationToken);
var isChanged =
changes > 0 &&
!entry.IsNull() &&
!entry.Entity.IsNullOrDefault();
if (!isChanged)
{
XException.ActionFailed.Throw();
}
//
var result = await EnrichAsync(
source: entry.Entity,
cancellationToken: cancellationToken
);
return result;
}
#endregion
//
#region Custom ...
/// <summary>
/// Normalize an XQuery based on Data Service Configurations ...
/// </summary>
/// <param name="source"></param>
/// <param name="configuration"></param>
/// <returns></returns>
public XQuery NormalizeQuery(
XQuery source,
XDataServiceConfiguration configuration //
)
{
//
if (source.IsNull())
{
source = new XQuery();
}
//
// Page Size Normalization ...
if (source.PageSize < configuration.PagingConfiguration.MinAvailablePageSize)
{
source.PageSize = configuration.PagingConfiguration.MinAvailablePageSize;
}
if (source.PageSize > configuration.PagingConfiguration.MaxAvailablePageSize)
{
source.PageSize = configuration.PagingConfiguration.MaxAvailablePageSize;
}
//
return source;
}
#endregion
//
#region Enrichers ...
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> EnrichAsync(
XScopeDefinition source,
CancellationToken cancellationToken = default
)
{
//
var result = source.MapConvert<XScopeDefinitionDto, XScopeDefinition>();
result = await EnrichAsync(
source: result,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XScopeDefinitionDto> EnrichAsync(
XScopeDefinitionDto source,
CancellationToken cancellationToken = default
)
{
//
var result = await Task.FromResult(source);
return result;
}
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XScopeDefinitionDto>> EnrichRangeAsync(
IEnumerable<XScopeDefinition> sources,
CancellationToken cancellationToken = default
)
{
//
var tasks = sources
.Select(s => EnrichAsync(s, cancellationToken));
//
var result = await Task.WhenAll(tasks);
//
return result;
}
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IEnumerable<XScopeDefinitionDto>> EnrichRangeAsync(
IEnumerable<XScopeDefinitionDto> sources,
CancellationToken cancellationToken = default
)
{
//
var tasks = sources
.Select(s => EnrichAsync(s, cancellationToken));
//
var result = await Task.WhenAll(tasks);
//
return result;
}
#endregion
}
}
+9 -5
View File
@@ -90,13 +90,10 @@ namespace xIds
) )
{ {
// //
if (env.IsDevelopment()) var isDevelopmentEnvironment = env.IsDevelopment();
if (isDevelopmentEnvironment)
{ {
//
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
//
// app.UseXRequestLogger();
} }
// //
@@ -122,6 +119,13 @@ namespace xIds
// //
app.UseRouting(); app.UseRouting();
//
// Using Request Logging ...
if (!isDevelopmentEnvironment)
{
app.UseXRequestLogger();
}
// //
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
+2 -1
View File
@@ -1,8 +1,9 @@
{ {
"Version": "0.1", "Version": "0.1",
"XPoweredValue": "SaherElmITCenter",
"Name": "xIdentityServer", "Name": "xIdentityServer",
"XPoweredValue": "SaherElmITCenter",
"WelcomeMessage": "Welcome to xSaherElm Project's xIdentityServer", "WelcomeMessage": "Welcome to xSaherElm Project's xIdentityServer",
"DefaultCacheTtlMinutes": 10,
"AllowedOrigins": [ "AllowedOrigins": [
"https://saherelm.ir", "https://saherelm.ir",
"https://saherelmhub.ir", "https://saherelmhub.ir",
+13 -5
View File
@@ -1,4 +1,5 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<!-- Runtime Definitions --> <!-- Runtime Definitions -->
<PropertyGroup> <PropertyGroup>
<Version>1.0.0</Version> <Version>1.0.0</Version>
@@ -7,32 +8,38 @@
<PackageId>xSaherElm.xIds</PackageId> <PackageId>xSaherElm.xIds</PackageId>
<Company>SaherElm IT Center</Company> <Company>SaherElm IT Center</Company>
<TargetFramework>netcoreapp3.1</TargetFramework> <TargetFramework>netcoreapp3.1</TargetFramework>
<Description> <Description>
this project is an Identity Server for xSaherElm projects which provides Authentication and this project is an Identity Server for xSaherElm projects which provides Authentication and
Authorization of User's. Authorization of User's.
</Description> </Description>
<!-- Icon Definition --> <!-- Icon Definition -->
<PackageIcon>icon.png</PackageIcon> <PackageIcon>icon.png</PackageIcon>
<!-- Fix Duplicate TargetFramework Issue --> <!-- Fix Duplicate TargetFramework Issue -->
<GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute> <GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup> </PropertyGroup>
<!-- Icon Handling --> <!-- Icon Handling -->
<ItemGroup> <ItemGroup>
<None Include="../../Resources/Images/favicon.png" Link="icon.png" Pack="true" PackagePath="\icon.png" /> <None Include="../../Resources/Images/favicon.png" Link="icon.png" Pack="true" PackagePath="\icon.png" />
</ItemGroup> </ItemGroup>
<!-- Local Dependencies --> <!-- Local Dependencies -->
<ItemGroup> <ItemGroup>
<!-- <PackageReference Include="xDashboard.xMessageService" Version="1.0.0" />
<PackageReference Include="xDashboard.xStorageService" Version="1.0.0" /> -->
</ItemGroup> </ItemGroup>
<!-- Project Dependencies --> <!-- Project Dependencies -->
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Modules\xLoggingService\xLoggingService.csproj" />
<ProjectReference Include="..\Modules\xIdentityHelper\xIdentityHelper.csproj" /> <ProjectReference Include="..\Modules\xIdentityHelper\xIdentityHelper.csproj" />
<ProjectReference Include="..\Modules\xMessageService\xMessageService.csproj" /> <ProjectReference Include="..\Modules\xMessageService\xMessageService.csproj" />
<ProjectReference Include="..\Modules\xStorageService\xStorageService.csproj" /> <ProjectReference Include="..\Modules\xStorageService\xStorageService.csproj" />
<ProjectReference Include="..\Modules\xIdentityService\xIdentityService.csproj" /> <ProjectReference Include="..\Modules\xIdentityService\xIdentityService.csproj" />
</ItemGroup> </ItemGroup>
<!-- IdentityServer --> <!-- IdentityServer -->
<ItemGroup> <ItemGroup>
<PackageReference Include="IdentityServer4" Version="4.1.1" /> <PackageReference Include="IdentityServer4" Version="4.1.1" />
@@ -47,6 +54,7 @@
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.2" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.2" />
<PackageReference Include="IdentityModel.AspNetCore.AccessTokenValidation" Version="1.0.0-preview.3" /> <PackageReference Include="IdentityModel.AspNetCore.AccessTokenValidation" Version="1.0.0-preview.3" />
</ItemGroup> </ItemGroup>
<!-- Ef Core --> <!-- Ef Core -->
<ItemGroup> <ItemGroup>
<PackageReference Include="MySql.EntityFrameworkCore" Version="5.0.0" /> <PackageReference Include="MySql.EntityFrameworkCore" Version="5.0.0" />
@@ -62,17 +70,17 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
</PackageReference> </PackageReference>
</ItemGroup> </ItemGroup>
<!-- For XML Documentation Support --> <!-- For XML Documentation Support -->
<PropertyGroup> <PropertyGroup>
<NoWarn>$(NoWarn);1591</NoWarn> <NoWarn>$(NoWarn);1591</NoWarn>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup> </PropertyGroup>
<!-- Create Required Folders --> <!-- Create Required Folders -->
<Target Name="CreateRequiredFolder" AfterTargets="AfterPublish"> <Target Name="CreateRequiredFolder" AfterTargets="AfterPublish">
<MakeDir Directories="$(PublishDir)wwwroot" Condition="!Exists('$(PublishDir)wwwroot')" /> <MakeDir Directories="$(PublishDir)wwwroot" Condition="!Exists('$(PublishDir)wwwroot')" />
</Target> </Target>
<ItemGroup>
<ProjectReference Include="..\Modules\xLoggingService\xLoggingService.csproj" />
</ItemGroup>
</Project> </Project>