diff --git a/DI/XDIHelperExtension.cs b/DI/XDIHelperExtension.cs index f23f812..9dc37dc 100644 --- a/DI/XDIHelperExtension.cs +++ b/DI/XDIHelperExtension.cs @@ -19,6 +19,7 @@ using xCommons.Authorization; using System.Collections.Generic; using xMessageService.Interfaces; using xStorageService.Interfaces; +using xIdentityModels.Interfaces; using xIdentityService.Interfaces; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Logging; @@ -81,6 +82,20 @@ namespace xIds.DI return config.GetConnectionString(connectionName); } + /// + /// Register Scope/Role/Policy Providers ... + /// + /// + public static void AddXAuthorizationProviders( + this IServiceCollection source + ) + { + // + source.AddScoped(); + source.AddScoped(); + source.AddScoped(); + } + /// /// Retrive XDataService Configurations ... /// @@ -531,6 +546,10 @@ namespace xIds.DI // services.AddSingleton(); + + // + // Register Providers ... + services.AddXAuthorizationProviders(); } /// diff --git a/DbContext/XIdentityDbContext.cs b/DbContext/XIdentityDbContext.cs index 5efe4c7..67ef105 100644 --- a/DbContext/XIdentityDbContext.cs +++ b/DbContext/XIdentityDbContext.cs @@ -20,6 +20,9 @@ namespace xIds.DbContext public DbSet BannedDevices { get; set; } public DbSet Followers { get; set; } public DbSet Followings { get; set; } + public DbSet RoleDefinitions { get; set; } + public DbSet ScopeDefinitions { get; set; } + public DbSet PolicyDefinitions { get; set; } public DbSet VerificationRequests { get; set; } #endregion diff --git a/Extensions/XModelExtensions.cs b/Extensions/XModelExtensions.cs index ca2c404..095c993 100644 --- a/Extensions/XModelExtensions.cs +++ b/Extensions/XModelExtensions.cs @@ -1,8 +1,13 @@ using System; using System.Linq; +using xModels.Dtos; +using System.Reflection; using xCommons.Extensions; +using xExceptions.Constants; using System.Threading.Tasks; +using xDataService.Constants; using xIdentityModels.Models; +using System.Linq.Expressions; using System.Collections.Generic; using xDataService.Configuration; using Microsoft.EntityFrameworkCore; @@ -32,6 +37,146 @@ namespace xIds.Extensions return result; } + // /// + // /// Apply Search Filter on a Enumerable + // /// + // /// + // /// + // /// + // /// + // public static IEnumerable ApplyFilter( + // this IEnumerable source, + // string filter + // ) + // where T : class + // { + // // + // // Apply Filter ... + // return source.Where(r => r.PropValuesContains(filter)); + // } + + // /// + // /// Count Query Pages based on Specified Total Number ... + // /// + // /// + // /// + // /// + // 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; + // } + + // /// + // /// Apply Sorting on a Enumerable + // /// + // /// + // /// + // /// + // /// + // /// + // /// + // public static IEnumerable ApplySorting( + // this IEnumerable source, + // string sortBy, + // bool isAscending, + // IDictionary>> 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); + // } + // } + + // /// + // /// Apply Paging on a Enumerable + // /// + // /// + // /// + // /// + // /// + // /// + // public static IEnumerable ApplyPaging( + // this IEnumerable 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); + // } + /// /// Applying Filter to IQueryable /// /// @@ -87,5 +232,175 @@ namespace xIds.Extensions // return result; } + + // /// + // /// provide a way to Order an IQueryable by string FieldName ... + // /// + // /// + // /// + // /// + // /// + // public static IOrderedQueryable OrderBy( + // this IQueryable 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 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)genericMethod + // .Invoke(genericMethod, new object[] { query, selector }); + + // // + // return newQuery; + // } + + // /// + // /// provide a way to Order an IEnumerable by string FieldName ... + // /// + // /// + // /// + // /// + // /// + // public static IOrderedEnumerable OrderBy( + // this IEnumerable 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)); + // } + + // /// + // /// provide a way to Order an IQueryable by string FieldName ... + // /// + // /// + // /// + // /// + // /// + // public static IOrderedQueryable OrderByDescending( + // this IQueryable 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 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)genericMethod + // .Invoke(genericMethod, new object[] { query, selector }); + + // // + // return newQuery; + // } + + // /// + // /// provide a way to Order an IEnumerable by string FieldName ... + // /// + // /// + // /// + // /// + // /// + // public static IOrderedEnumerable OrderByDescending( + // this IEnumerable 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)); + // } } } \ No newline at end of file diff --git a/Providers/XApplicationProvider.cs b/Providers/XApplicationProvider.cs index 9522698..44304d3 100644 --- a/Providers/XApplicationProvider.cs +++ b/Providers/XApplicationProvider.cs @@ -1,4 +1,5 @@ using System; +using AutoMapper; using System.Linq; using xModels.Dtos; using xIds.DbContext; @@ -14,7 +15,6 @@ using IdentityServer4.Extensions; using xIdentityModels.Extensions; using Microsoft.EntityFrameworkCore.Query; using Microsoft.Extensions.Caching.Memory; -using AutoMapper; namespace xIds.Providers { diff --git a/Providers/XIdentityManager/XIdentityManager+Search.cs b/Providers/XIdentityManager/XIdentityManager+Search.cs index 8e5baf6..4a79d3f 100644 --- a/Providers/XIdentityManager/XIdentityManager+Search.cs +++ b/Providers/XIdentityManager/XIdentityManager+Search.cs @@ -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 xModels.Dtos; +using xIds.Extensions; +using xCommons.Extensions; +using xIdentityModels.Dtos; +using xExceptions.Constants; +using System.Threading.Tasks; +using xDataService.Extensions; using xIdentityModels.Extensions; namespace xIds.Providers diff --git a/Providers/XPolicyProvider.cs b/Providers/XPolicyProvider.cs new file mode 100644 index 0000000..157d08a --- /dev/null +++ b/Providers/XPolicyProvider.cs @@ -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 xIdentityModels.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 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() + .ReverseMap(); + + // + cfg.CreateMap() + .ReverseMap(); + + // + cfg.CreateMap() + .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 ... + /// + /// retrieve whole items as queryable ... + /// + /// a flag for Tracking behaviour + /// an Expression for Filter Items ... + /// an Order Builder expression for Ordering Query ... + /// + public virtual IQueryable AsQueryable( + bool asNoTracking = true, + Expression> predicate = null, + Func, IOrderedQueryable> orderBuilder = null + ) + { + // + var result = dbContext.PolicyDefinitions + .Where(predicate) + .AsQueryable(); + if (asNoTracking) + { + result = result.AsNoTracking(); + } + + // + return result; + } + + /// + /// retrieve an Entity by it's Id ... + /// + /// + /// + /// + /// + public virtual async Task 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; + } + + /// + /// retrieve all exists Entities ... + /// + /// + /// + /// + /// + public virtual async Task> GetAllAsync( + bool ignoreSoftDeleteds = true, + Func, IOrderedQueryable> orderBuilder = null, + CancellationToken cancellationToken = default + ) + { + // + // Prepare Predicate ... + Expression> 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; + } + + /// + /// find an Entity by providing a Conditional Expression ... + /// + /// + /// + /// + /// + public virtual async Task FindOneAsync( + Expression> predicate, + bool ignoreSoftDeleteds = true, + CancellationToken cancellationToken = default + ) + { + // + // Prepare Predicate ... + Expression> 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; + } + + /// + /// find a collection of Entities by proving a Conditional Expression ... + /// + /// + /// + /// + /// + /// + public virtual async Task> FindManyAsync( + Expression> predicate, + bool ignoreSoftDeleteds = true, + Func, IOrderedQueryable> orderBuilder = null, + CancellationToken cancellationToken = default + ) + { + // + // Prepare Predicate ... + Expression> 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; + } + + /// + /// count all exists Entities ... + /// + /// + /// + /// + public virtual async Task CountAsync( + bool ignoreSoftDeleteds = true, + CancellationToken cancellationToken = default + ) + { + // + // Prepare Predicate ... + Expression> predicator = null; + if (ignoreSoftDeleteds) + { + predicator = x => !x.Deleted; + } + + // + var queryable = AsQueryable( + asNoTracking: true, + orderBuilder: null, + predicate: predicator + ); + + // + var result = await queryable.CountAsync(); + + // + return result; + } + + /// + /// count all exists Entities Pages by providing page size ... + /// + /// + /// + /// + /// + /// + public virtual async Task 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; + } + + /// + /// Check an Entity exists or not ... + /// + /// + /// + /// + /// + public virtual async Task 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 ... + /// + /// retrieve Entities based on XQuery Pagination structure ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task> QueryAsync( + XQuery query, + bool ignoreSoftDeleteds = true, + Expression> predicate = null, + Func, IOrderedQueryable> 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 + { + Page = query.Page, + Items = [.. resultItems], + PageSize = query.PageSize, + TotalPages = totalPagesCount, + TotalItems = totalItemsCount, + TotalFilteredPages = filteredPagesCount, + TotalFilteredItems = filteredItemsCount + }; + + // + return result; + } + #endregion + + // + #region Add/Update/Remove ... + /// + /// add a new Entity ... + /// + /// + /// + /// + /// + /// + public virtual async Task 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(); + 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; + } + + /// + /// Update an Entity values ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task 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; + } + + /// + /// remove an Entity by it's Id ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task 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 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 ... + /// + /// Normalize an XQuery based on Data Service Configurations ... + /// + /// + /// + /// + 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 ... + /// + /// Enrich Item ... + /// + /// + /// + /// + public virtual async Task EnrichAsync( + XPolicyDefinition source, + CancellationToken cancellationToken = default + ) + { + // + var result = source.MapConvert(); + result = await EnrichAsync( + source: result, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Item ... + /// + /// + /// + /// + public virtual async Task EnrichAsync( + XPolicyDefinitionDto source, + CancellationToken cancellationToken = default + ) + { + // + var result = await Task.FromResult(source); + return result; + } + + /// + /// Enrich a Collection of Items(s) ... + /// + /// + /// + /// + public virtual async Task> EnrichRangeAsync( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(s => EnrichAsync(s, cancellationToken)); + + // + var result = await Task.WhenAll(tasks); + + // + return result; + } + + /// + /// Enrich a Collection of Items(s) ... + /// + /// + /// + /// + public virtual async Task> EnrichRangeAsync( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(s => EnrichAsync(s, cancellationToken)); + + // + var result = await Task.WhenAll(tasks); + + // + return result; + } + #endregion + } +} \ No newline at end of file diff --git a/Providers/XRoleProvider.cs b/Providers/XRoleProvider.cs new file mode 100644 index 0000000..bc95ab4 --- /dev/null +++ b/Providers/XRoleProvider.cs @@ -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 xIdentityModels.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 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() + .ReverseMap(); + + // + cfg.CreateMap() + .ReverseMap(); + + // + cfg.CreateMap() + .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 ... + /// + /// retrieve whole items as queryable ... + /// + /// a flag for Tracking behaviour + /// an Expression for Filter Items ... + /// an Order Builder expression for Ordering Query ... + /// + public virtual IQueryable AsQueryable( + bool asNoTracking = true, + Expression> predicate = null, + Func, IOrderedQueryable> orderBuilder = null + ) + { + // + var result = dbContext.RoleDefinitions + .Where(predicate) + .AsQueryable(); + if (asNoTracking) + { + result = result.AsNoTracking(); + } + + // + return result; + } + + /// + /// retrieve an Entity by it's Id ... + /// + /// + /// + /// + /// + public virtual async Task 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; + } + + /// + /// retrieve all exists Entities ... + /// + /// + /// + /// + /// + public virtual async Task> GetAllAsync( + bool ignoreSoftDeleteds = true, + Func, IOrderedQueryable> orderBuilder = null, + CancellationToken cancellationToken = default + ) + { + // + // Prepare Predicate ... + Expression> 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; + } + + /// + /// find an Entity by providing a Conditional Expression ... + /// + /// + /// + /// + /// + public virtual async Task FindOneAsync( + Expression> predicate, + bool ignoreSoftDeleteds = true, + CancellationToken cancellationToken = default + ) + { + // + // Prepare Predicate ... + Expression> 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; + } + + /// + /// find a collection of Entities by proving a Conditional Expression ... + /// + /// + /// + /// + /// + /// + public virtual async Task> FindManyAsync( + Expression> predicate, + bool ignoreSoftDeleteds = true, + Func, IOrderedQueryable> orderBuilder = null, + CancellationToken cancellationToken = default + ) + { + // + // Prepare Predicate ... + Expression> 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; + } + + /// + /// count all exists Entities ... + /// + /// + /// + /// + public virtual async Task CountAsync( + bool ignoreSoftDeleteds = true, + CancellationToken cancellationToken = default + ) + { + // + // Prepare Predicate ... + Expression> predicator = null; + if (ignoreSoftDeleteds) + { + predicator = x => !x.Deleted; + } + + // + var queryable = AsQueryable( + asNoTracking: true, + orderBuilder: null, + predicate: predicator + ); + + // + var result = await queryable.CountAsync(); + + // + return result; + } + + /// + /// count all exists Entities Pages by providing page size ... + /// + /// + /// + /// + /// + /// + public virtual async Task 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; + } + + /// + /// Check an Entity exists or not ... + /// + /// + /// + /// + /// + public virtual async Task 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 ... + /// + /// retrieve Entities based on XQuery Pagination structure ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task> QueryAsync( + XQuery query, + bool ignoreSoftDeleteds = true, + Expression> predicate = null, + Func, IOrderedQueryable> 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 + { + Page = query.Page, + Items = [.. resultItems], + PageSize = query.PageSize, + TotalPages = totalPagesCount, + TotalItems = totalItemsCount, + TotalFilteredPages = filteredPagesCount, + TotalFilteredItems = filteredItemsCount + }; + + // + return result; + } + #endregion + + // + #region Add/Update/Remove ... + /// + /// add a new Entity ... + /// + /// + /// + /// + /// + /// + public virtual async Task 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(); + 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; + } + + /// + /// Update an Entity values ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task 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; + } + + /// + /// remove an Entity by it's Id ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task 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 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 ... + /// + /// Normalize an XQuery based on Data Service Configurations ... + /// + /// + /// + /// + 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 ... + /// + /// Enrich Item ... + /// + /// + /// + /// + public virtual async Task EnrichAsync( + XRoleDefinition source, + CancellationToken cancellationToken = default + ) + { + // + var result = source.MapConvert(); + result = await EnrichAsync( + source: result, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Item ... + /// + /// + /// + /// + public virtual async Task EnrichAsync( + XRoleDefinitionDto source, + CancellationToken cancellationToken = default + ) + { + // + var result = await Task.FromResult(source); + return result; + } + + /// + /// Enrich a Collection of Items(s) ... + /// + /// + /// + /// + public virtual async Task> EnrichRangeAsync( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(s => EnrichAsync(s, cancellationToken)); + + // + var result = await Task.WhenAll(tasks); + + // + return result; + } + + /// + /// Enrich a Collection of Items(s) ... + /// + /// + /// + /// + public virtual async Task> EnrichRangeAsync( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(s => EnrichAsync(s, cancellationToken)); + + // + var result = await Task.WhenAll(tasks); + + // + return result; + } + #endregion + } +} \ No newline at end of file diff --git a/Providers/XScopeProvider.cs b/Providers/XScopeProvider.cs new file mode 100644 index 0000000..2dfffeb --- /dev/null +++ b/Providers/XScopeProvider.cs @@ -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 xIdentityModels.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 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() + .ReverseMap(); + + // + cfg.CreateMap() + .ReverseMap(); + + // + cfg.CreateMap() + .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 ... + /// + /// retrieve whole items as queryable ... + /// + /// a flag for Tracking behaviour + /// an Expression for Filter Items ... + /// an Order Builder expression for Ordering Query ... + /// + public virtual IQueryable AsQueryable( + bool asNoTracking = true, + Expression> predicate = null, + Func, IOrderedQueryable> orderBuilder = null + ) + { + // + var result = dbContext.ScopeDefinitions + .Where(predicate) + .AsQueryable(); + if (asNoTracking) + { + result = result.AsNoTracking(); + } + + // + return result; + } + + /// + /// retrieve an Entity by it's Id ... + /// + /// + /// + /// + /// + public virtual async Task 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; + } + + /// + /// retrieve all exists Entities ... + /// + /// + /// + /// + /// + public virtual async Task> GetAllAsync( + bool ignoreSoftDeleteds = true, + Func, IOrderedQueryable> orderBuilder = null, + CancellationToken cancellationToken = default + ) + { + // + // Prepare Predicate ... + Expression> 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; + } + + /// + /// find an Entity by providing a Conditional Expression ... + /// + /// + /// + /// + /// + public virtual async Task FindOneAsync( + Expression> predicate, + bool ignoreSoftDeleteds = true, + CancellationToken cancellationToken = default + ) + { + // + // Prepare Predicate ... + Expression> 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; + } + + /// + /// find a collection of Entities by proving a Conditional Expression ... + /// + /// + /// + /// + /// + /// + public virtual async Task> FindManyAsync( + Expression> predicate, + bool ignoreSoftDeleteds = true, + Func, IOrderedQueryable> orderBuilder = null, + CancellationToken cancellationToken = default + ) + { + // + // Prepare Predicate ... + Expression> 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; + } + + /// + /// count all exists Entities ... + /// + /// + /// + /// + public virtual async Task CountAsync( + bool ignoreSoftDeleteds = true, + CancellationToken cancellationToken = default + ) + { + // + // Prepare Predicate ... + Expression> predicator = null; + if (ignoreSoftDeleteds) + { + predicator = x => !x.Deleted; + } + + // + var queryable = AsQueryable( + asNoTracking: true, + orderBuilder: null, + predicate: predicator + ); + + // + var result = await queryable.CountAsync(); + + // + return result; + } + + /// + /// count all exists Entities Pages by providing page size ... + /// + /// + /// + /// + /// + /// + public virtual async Task 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; + } + + /// + /// Check an Entity exists or not ... + /// + /// + /// + /// + /// + public virtual async Task 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 ... + /// + /// retrieve Entities based on XQuery Pagination structure ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task> QueryAsync( + XQuery query, + bool ignoreSoftDeleteds = true, + Expression> predicate = null, + Func, IOrderedQueryable> 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 + { + Page = query.Page, + Items = [.. resultItems], + PageSize = query.PageSize, + TotalPages = totalPagesCount, + TotalItems = totalItemsCount, + TotalFilteredPages = filteredPagesCount, + TotalFilteredItems = filteredItemsCount + }; + + // + return result; + } + #endregion + + // + #region Add/Update/Remove ... + /// + /// add a new Entity ... + /// + /// + /// + /// + /// + /// + public virtual async Task 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(); + 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; + } + + /// + /// Update an Entity values ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task 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; + } + + /// + /// remove an Entity by it's Id ... + /// + /// + /// + /// + /// + /// + /// + public virtual async Task 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 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 ... + /// + /// Normalize an XQuery based on Data Service Configurations ... + /// + /// + /// + /// + 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 ... + /// + /// Enrich Item ... + /// + /// + /// + /// + public virtual async Task EnrichAsync( + XScopeDefinition source, + CancellationToken cancellationToken = default + ) + { + // + var result = source.MapConvert(); + result = await EnrichAsync( + source: result, + cancellationToken: cancellationToken + ); + + // + return result; + } + + /// + /// Enrich Item ... + /// + /// + /// + /// + public virtual async Task EnrichAsync( + XScopeDefinitionDto source, + CancellationToken cancellationToken = default + ) + { + // + var result = await Task.FromResult(source); + return result; + } + + /// + /// Enrich a Collection of Items(s) ... + /// + /// + /// + /// + public virtual async Task> EnrichRangeAsync( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(s => EnrichAsync(s, cancellationToken)); + + // + var result = await Task.WhenAll(tasks); + + // + return result; + } + + /// + /// Enrich a Collection of Items(s) ... + /// + /// + /// + /// + public virtual async Task> EnrichRangeAsync( + IEnumerable sources, + CancellationToken cancellationToken = default + ) + { + // + var tasks = sources + .Select(s => EnrichAsync(s, cancellationToken)); + + // + var result = await Task.WhenAll(tasks); + + // + return result; + } + #endregion + } +} \ No newline at end of file