Compare commits

...
19 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
saherelm b311b1e391 add using XLoggingService ... 2026-11-08 22:55:19 +03:30
saherelm df3ed7868b last ... 2026-11-08 17:59:00 +03:30
saherelm 73a59f9181 fix ... 2026-11-05 23:15:42 +03:30
saherelm 3b099a3089 Sort Ordering Usings and Add Support for User ID in OpenActions ... 2026-10-30 00:15:51 +03:30
saherelm bc49b0aa86 refactor AddXCommons for Support File Type Detector ... 2026-10-23 00:12:58 +03:30
saherelm 018ef161a8 Complete Supports for XApiUsage Handling ... 2026-10-19 20:46:23 +03:30
saherelm 986025c44b last ... 2026-10-18 17:49:17 +03:30
saherelm 9b4453f4b1 last ... 2026-10-18 05:46:49 +03:30
saherelm 6203c7e084 last ... 2026-10-17 17:15:20 +03:30
saherelm 9fb70e14d7 Refactor and Test Application Controller and ApiKey Access Authorization Handling ... 2026-10-17 01:18:14 +03:30
saherelm 6b648ede44 last ... 2026-10-16 21:34:06 +03:30
43 changed files with 5009 additions and 586 deletions
+1
View File
@@ -1,6 +1,7 @@
# #
bin bin
obj obj
Logs
# #
Db/* Db/*
@@ -15,6 +15,12 @@ namespace xIds.Controllers
// //
#region Open Actions ... #region Open Actions ...
/// <summary>
/// Get Open Action ...
/// </summary>
/// <param name="token"></param>
/// <param name="request"></param>
/// <returns></returns>
[AllowAnonymous] [AllowAnonymous]
[RequireXPowered] [RequireXPowered]
[HttpGet("Open")] [HttpGet("Open")]
+31 -11
View File
@@ -15,7 +15,7 @@ namespace xIds.Controllers
// //
#region Test Actions ... #region Test Actions ...
/// <summary> /// <summary>
/// API Read Scope /// API Read Scope ...
/// </summary> /// </summary>
/// <returns>string message</returns> /// <returns>string message</returns>
[RequireXPowered] [RequireXPowered]
@@ -28,7 +28,7 @@ namespace xIds.Controllers
} }
/// <summary> /// <summary>
/// API Write Scope /// API Write Scope ...
/// </summary> /// </summary>
/// <returns>string message</returns> /// <returns>string message</returns>
[RequireXPowered] [RequireXPowered]
@@ -41,7 +41,7 @@ namespace xIds.Controllers
} }
/// <summary> /// <summary>
/// API Admin Scope /// API Admin Scope ...
/// </summary> /// </summary>
/// <returns>string message</returns> /// <returns>string message</returns>
[RequireXPowered] [RequireXPowered]
@@ -54,7 +54,7 @@ namespace xIds.Controllers
} }
/// <summary> /// <summary>
/// API Manage Scop /// API Manage Scop ...
/// </summary> /// </summary>
/// <returns>string message</returns> /// <returns>string message</returns>
[RequireXPowered] [RequireXPowered]
@@ -67,7 +67,7 @@ namespace xIds.Controllers
} }
/// <summary> /// <summary>
/// a simple Action which returns a List of Authenticated User Claims /// a simple Action which returns a List of Authenticated User Claims ...
/// </summary> /// </summary>
/// <returns>string message which represent current user's claims</returns> /// <returns>string message which represent current user's claims</returns>
[RequireXPowered] [RequireXPowered]
@@ -92,7 +92,7 @@ namespace xIds.Controllers
} }
/// <summary> /// <summary>
/// a simple Hello User for Checking Authentication and Policy /// a simple Hello User for Checking Authentication and Policy ...
/// </summary> /// </summary>
/// <returns>string message which contains authenticated user name</returns> /// <returns>string message which contains authenticated user name</returns>
[RequireXPowered] [RequireXPowered]
@@ -109,7 +109,7 @@ namespace xIds.Controllers
} }
/// <summary> /// <summary>
/// a simple Hello User for Checking Authentication and Policy /// a simple Hello User for Checking Authentication and Policy ...
/// </summary> /// </summary>
/// <returns>string message which contains authenticated user name</returns> /// <returns>string message which contains authenticated user name</returns>
[RequireXPowered] [RequireXPowered]
@@ -126,7 +126,7 @@ namespace xIds.Controllers
} }
/// <summary> /// <summary>
/// a simple Hello User for Checking Authentication and Policy /// a simple Hello User for Checking Authentication and Policy ...
/// </summary> /// </summary>
/// <returns>string message which contains authenticated user name</returns> /// <returns>string message which contains authenticated user name</returns>
[RequireXPowered] [RequireXPowered]
@@ -143,7 +143,7 @@ namespace xIds.Controllers
} }
/// <summary> /// <summary>
/// a simple Hello User for Checking Authentication and Policy /// a simple Hello User for Checking Authentication and Policy ...
/// </summary> /// </summary>
/// <returns>string message which contains authenticated user name</returns> /// <returns>string message which contains authenticated user name</returns>
[RequireXPowered] [RequireXPowered]
@@ -159,11 +159,15 @@ namespace xIds.Controllers
return Ok(result); return Ok(result);
} }
/// <summary>
/// a simple Hello for Accessing ApiKey Authorization ...
/// </summary>
/// <returns></returns>
[XApiKeyAccess]
[AllowAnonymous] [AllowAnonymous]
[RequireXPowered] [RequireXPowered]
[HttpGet("Test/HiApiKeyAccess")] [HttpGet("Test/HiApiKeyAccess")]
[Authorize(LocalApi.PolicyName)] [Authorize(LocalApi.PolicyName)]
[XApiKeyAccess(scopes: [XApiKeyScope.Manage])]
public ActionResult<string> HiApiKeyAccess() public ActionResult<string> HiApiKeyAccess()
{ {
// //
@@ -173,11 +177,15 @@ namespace xIds.Controllers
return Ok(result); return Ok(result);
} }
/// <summary>
/// a simple Hello for Accessing ApiKey Read Access ...
/// </summary>
/// <returns></returns>
[AllowAnonymous] [AllowAnonymous]
[RequireXPowered] [RequireXPowered]
[Authorize(LocalApi.PolicyName)] [Authorize(LocalApi.PolicyName)]
[HttpGet("Test/HiApiKeyReadAccess")] [HttpGet("Test/HiApiKeyReadAccess")]
[XApiKeyAccess(scopes: [XApiKeyScope.Read])] [XApiKeyAccess(Scopes = [XApiKeyScope.Read])]
public ActionResult<string> HiApiKeyReadAccess() public ActionResult<string> HiApiKeyReadAccess()
{ {
// //
@@ -187,6 +195,10 @@ namespace xIds.Controllers
return Ok(result); return Ok(result);
} }
/// <summary>
/// a simple Hello for Accessing ApiKey Write Access ...
/// </summary>
/// <returns></returns>
[AllowAnonymous] [AllowAnonymous]
[RequireXPowered] [RequireXPowered]
[Authorize(LocalApi.PolicyName)] [Authorize(LocalApi.PolicyName)]
@@ -201,6 +213,10 @@ namespace xIds.Controllers
return Ok(result); return Ok(result);
} }
/// <summary>
/// a simple Hello for Accessing ApiKey Manage Access ...
/// </summary>
/// <returns></returns>
[AllowAnonymous] [AllowAnonymous]
[RequireXPowered] [RequireXPowered]
[Authorize(LocalApi.PolicyName)] [Authorize(LocalApi.PolicyName)]
@@ -215,6 +231,10 @@ namespace xIds.Controllers
return Ok(result); return Ok(result);
} }
/// <summary>
/// a simple Hello for Accessing ApiKey Admin Access ...
/// </summary>
/// <returns></returns>
[AllowAnonymous] [AllowAnonymous]
[RequireXPowered] [RequireXPowered]
[Authorize(LocalApi.PolicyName)] [Authorize(LocalApi.PolicyName)]
+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,
@@ -1,8 +1,8 @@
using System; using System;
using System.Linq; using System.Linq;
using xModels.Dtos; using xModels.Dtos;
using System.Threading;
using xIdentityHelper; using xIdentityHelper;
using System.Threading;
using xCommons.Attributes; using xCommons.Attributes;
using xCommons.Extensions; using xCommons.Extensions;
using xIdentityModels.Dtos; using xIdentityModels.Dtos;
@@ -90,14 +90,16 @@ namespace xIds.Controllers
/// } /// }
/// ///
/// </remarks> /// </remarks>
/// <param name="id"></param>
/// <param name="item"></param> /// <param name="item"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
[HttpPut("")] [HttpPut("{id}")]
[RequireXPowered] [RequireXPowered]
[Authorize(LocalApi.PolicyName)] [Authorize(LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)] [Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XApplicationDto>> UpdateApplication( public async Task<ActionResult<XApplicationDto>> UpdateApplication(
[FromRoute] int id,
[FromBody] XApplicationDto item, [FromBody] XApplicationDto item,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
@@ -107,7 +109,10 @@ namespace xIds.Controllers
{ {
// //
// Validate ... // Validate ...
if (!item.IsValidForAdd()) if (!id.IsValidIntId() ||
!item.IsValidForAdd() ||
id != item.Id
)
{ {
XException.InvalidArgs.Throw(); XException.InvalidArgs.Throw();
} }
@@ -117,8 +122,8 @@ namespace xIds.Controllers
// //
var result = await provider.UpdateApplicationAsync( var result = await provider.UpdateApplicationAsync(
id: id,
item: item, item: item,
id: item.Id,
userInfo: userInfo, userInfo: userInfo,
cancellationToken: cancellationToken cancellationToken: cancellationToken
); );
@@ -18,6 +18,8 @@ namespace xIds.Controllers
{ {
public partial class ApplicationsController public partial class ApplicationsController
{ {
//
#region Custom ...
/// <summary> /// <summary>
/// Show Api Key ... /// Show Api Key ...
/// </summary> /// </summary>
@@ -510,6 +512,7 @@ namespace xIds.Controllers
/// <param name="request"></param> /// <param name="request"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
[AllowAnonymous]
[RequireXPowered] [RequireXPowered]
[HttpPost("ApiKeys/Validate")] [HttpPost("ApiKeys/Validate")]
[Authorize(LocalApi.PolicyName)] [Authorize(LocalApi.PolicyName)]
@@ -532,6 +535,19 @@ namespace xIds.Controllers
// //
var userInfo = await GetUserInfo(); var userInfo = await GetUserInfo();
var checksum = GetRequestChecksum();
if (checksum.IsNullOrEmpty())
{
XException.NotAuthorized.Throw();
}
//
// Validate Checksum ...
var requestChecksum = securityProvider.Encrypt(request.ToJSON()).ToMd5String();
if (checksum.ToNormalString() != requestChecksum.ToNormalString())
{
XException.NotAuthorized.Throw();
}
// //
var result = await provider.ValidateApiKey( var result = await provider.ValidateApiKey(
@@ -552,5 +568,6 @@ namespace xIds.Controllers
return result; return result;
} }
} }
#endregion
} }
} }
+8
View File
@@ -1,26 +1,32 @@
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;
private readonly IXSecurityProvider securityProvider;
private readonly XApiKeyConfiguration apiKeyConfiguration; private readonly XApiKeyConfiguration apiKeyConfiguration;
public ApplicationsController( public ApplicationsController(
IXApplicationProvider provider, IXApplicationProvider provider,
IXIdentityManager identityManager, IXIdentityManager identityManager,
XAppConfiguration appConfiguration, XAppConfiguration appConfiguration,
IXSecurityProvider securityProvider,
ILogger<ApplicationsController> logger, ILogger<ApplicationsController> logger,
XValidationProvider validationProvider, XValidationProvider validationProvider,
XApiKeyConfiguration apiKeyConfiguration XApiKeyConfiguration apiKeyConfiguration
@@ -31,7 +37,9 @@ namespace xIds.Controllers
validationProvider validationProvider
) )
{ {
//
this.provider = provider; this.provider = provider;
this.securityProvider = securityProvider;
this.apiKeyConfiguration = apiKeyConfiguration; this.apiKeyConfiguration = apiKeyConfiguration;
} }
} }
@@ -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;
}
}
}
+62 -13
View File
@@ -1,18 +1,19 @@
using System; using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using xCommons.Configurations;
using xCommons.Constants;
using xCommons.Controllers;
using xCommons.Extensions;
using xCommons.Providers;
using xExceptions.Constants;
using xIdentityModels.Constants;
using xIdentityModels.Models;
using xIds.Interfaces; using xIds.Interfaces;
using xCommons.Providers;
using xCommons.Constants;
using xCommons.Extensions;
using xCommons.Controllers;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityModels.Models;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using xIdentityModels.Constants;
using System.Collections.Generic;
using xIdentityService.Constants;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authentication;
namespace xIds.Controllers.Base namespace xIds.Controllers.Base
{ {
@@ -226,6 +227,54 @@ namespace xIds.Controllers.Base
// //
#region NonActions ... #region NonActions ...
/// <summary>
/// Extract Checksum From Headers ...
/// </summary>
/// <returns></returns>
[NonAction]
public string GetRequestChecksum()
{
//
var result = string.Empty;
//
var headerKey = XHeader.ChecksumDigest.GetStringValue();
//
// Check if Connection ID is Provided ...
if (Request.Headers.ContainsKey(headerKey))
{
result = Request.Headers[headerKey];
}
//
return result;
}
/// <summary>
/// Extract ApiKey From Headers ...
/// </summary>
/// <returns></returns>
[NonAction]
public string GetRequestApiKey()
{
//
var result = string.Empty;
//
var headerKey = XHeader.ApiKey.GetStringValue();
//
// Check if Connection ID is Provided ...
if (Request.Headers.ContainsKey(headerKey))
{
result = Request.Headers[headerKey];
}
//
return result;
}
/// <summary> /// <summary>
/// Convert an Exception to Propper Error Result /// Convert an Exception to Propper Error Result
/// </summary> /// </summary>
+75 -1
View File
@@ -1,13 +1,14 @@
using System.Linq;
using xIds.Helpers; using xIds.Helpers;
using xIds.Constants; using xIds.Constants;
using xIds.DbContext; using xIds.DbContext;
using xIds.Providers; using xIds.Providers;
using IdentityServer4;
using xIdentityHelper; using xIdentityHelper;
using xIdentityModels; using xIdentityModels;
using xIds.Extensions; using xIds.Extensions;
using xIds.Interfaces; using xIds.Interfaces;
using xIds.Validators; using xIds.Validators;
using IdentityServer4;
using xCommons.Constants; using xCommons.Constants;
using xMessageService.DI; using xMessageService.DI;
using xStorageService.DI; using xStorageService.DI;
@@ -18,6 +19,9 @@ 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 Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
@@ -79,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>
@@ -433,6 +458,7 @@ namespace xIds.DI
) )
{ {
// //
var policyHandler = services.GetRegisteredService<IXPolicyHandler>();
services.AddAuthorization(options => services.AddAuthorization(options =>
{ {
// //
@@ -446,6 +472,26 @@ namespace xIds.DI
{ {
var policyDescriptor = policiesEnumerator.Current; var policyDescriptor = policiesEnumerator.Current;
options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);
//
// Add Policy to Policy Handler ...
if (!policyHandler.IsNull())
{
//
// Check Policy is RequiredRole Policy ...
var roleRequirements = policyDescriptor.Value.Requirements
.OfType<RequiredRolesRequirement>()
.FirstOrDefault();
if (!roleRequirements.IsNull() &&
roleRequirements.Roles.HasChild())
{
//
policyHandler.AddPolicy(
policy: policyDescriptor.Key.ToNormalString(),
requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString())
);
}
}
} }
} }
} }
@@ -460,8 +506,32 @@ namespace xIds.DI
{ {
while (policiesEnumerator.MoveNext()) while (policiesEnumerator.MoveNext())
{ {
//
var policyDescriptor = policiesEnumerator.Current; var policyDescriptor = policiesEnumerator.Current;
//
// Add Policy to Authorization ...
options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value); options.AddPolicy(policyDescriptor.Key, policyDescriptor.Value);
//
// Add Policy to Policy Handler ...
if (!policyHandler.IsNull())
{
//
// Check Policy is RequiredRole Policy ...
var roleRequirements = policyDescriptor.Value.Requirements
.OfType<RequiredRolesRequirement>()
.FirstOrDefault();
if (!roleRequirements.IsNull() &&
roleRequirements.Roles.HasChild())
{
//
policyHandler.AddPolicy(
policy: policyDescriptor.Key.ToNormalString(),
requiredRoles: roleRequirements.Roles.Select(r => r.ToNormalString())
);
}
}
} }
} }
} }
@@ -484,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();
});
} }
} }
} }
+6 -6
View File
@@ -1,15 +1,15 @@
using System; using System;
using xIds.Models;
using xIds.Constants;
using System.Reflection; using System.Reflection;
using xIds.Configurations;
using xCommons.Extensions;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure; using xIdentityModels.Configurations;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using MySql.EntityFrameworkCore.Infrastructure; using MySql.EntityFrameworkCore.Infrastructure;
using xCommons.Extensions; using Microsoft.EntityFrameworkCore.Infrastructure;
using xIdentityModels.Configurations;
using xIds.Configurations;
using xIds.Constants;
using xIds.Models;
namespace xIds.Extensions namespace xIds.Extensions
{ {
@@ -1,11 +1,11 @@
using xIds.Constants;
using xCommons.Models;
using System.Reflection; using System.Reflection;
using System.Security.Cryptography.X509Certificates; using xCommons.Extensions;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using xCommons.Extensions; using System.Security.Cryptography.X509Certificates;
using xCommons.Models;
using xIds.Constants;
namespace xIds.Extensions namespace xIds.Extensions
{ {
-18
View File
@@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using xCommons.Extensions;
using xExceptions.Constants;
using xModels.Base;
using xIds.Constants;
namespace xIds.Extensions
{
public static class IQueryableExtensions
{
}
}
+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>();
}
} }
} }
+10 -10
View File
@@ -1,20 +1,20 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using xIds.Models;
using xIds.Constants;
using xIds.Interfaces;
using xCommons.Extensions;
using System.Threading.Tasks; using System.Threading.Tasks;
using IdentityServer4.EntityFramework.DbContexts; using System.Collections.Generic;
using IdentityServer4.EntityFramework.Mappers; using xIdentityModels.Extensions;
using xIdentityModels.Descriptors;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using IdentityServer4.EntityFramework.Mappers;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using IdentityServer4.EntityFramework.DbContexts;
using xCommons.Extensions;
using xIdentityModels.Descriptors;
using xIdentityModels.Extensions;
using xIds.Constants;
using xIds.Interfaces;
using xIds.Models;
namespace xIds.Extensions namespace xIds.Extensions
{ {
+319 -4
View File
@@ -1,11 +1,16 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using xModels.Dtos;
using Microsoft.EntityFrameworkCore; using System.Reflection;
using xCommons.Extensions; using xCommons.Extensions;
using xDataService.Configuration; using xExceptions.Constants;
using System.Threading.Tasks;
using xDataService.Constants;
using xIdentityModels.Models; using xIdentityModels.Models;
using System.Linq.Expressions;
using System.Collections.Generic;
using xDataService.Configuration;
using Microsoft.EntityFrameworkCore;
namespace xIds.Extensions namespace xIds.Extensions
{ {
@@ -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));
// }
} }
} }
+2 -2
View File
@@ -87,9 +87,9 @@ namespace xIds.Helpers
var result = new TokenValidationParameters var result = new TokenValidationParameters
{ {
ValidIssuer = issuer, ValidIssuer = issuer,
ValidAudience = audience, IssuerSigningKey = key,
ValidateLifetime = true, ValidateLifetime = true,
IssuerSigningKey = key ValidAudience = audience,
}; };
// //
+27 -12
View File
@@ -1,22 +1,23 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using xModels.Dtos;
using xIds.DbContext;
using System.Net.Http; using System.Net.Http;
using xIdentityModels;
using System.Threading;
using xCommons.Providers;
using IdentityModel.Client;
using xIdentityModels.Dtos;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using xCommons.Providers;
using xIdentityModels;
using xIdentityModels.Constants;
using xIdentityModels.Descriptors;
using xIdentityModels.Dtos;
using xIdentityModels.Models; using xIdentityModels.Models;
using Microsoft.AspNetCore.Http;
using xIdentityModels.Constants;
using System.Collections.Generic;
using xIdentityModels.Descriptors;
using xIdentityModels.Navigations; using xIdentityModels.Navigations;
using xIds.DbContext; using Microsoft.Extensions.Logging;
using xModels.Dtos; using Microsoft.AspNetCore.Identity;
namespace xIds.Interfaces namespace xIds.Interfaces
{ {
@@ -87,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
// //
@@ -462,6 +467,16 @@ namespace xIds.Interfaces
); );
#endregion #endregion
Task<Guid> GetApiKey(
XOpenActionRequestDto dto,
CancellationToken cancellationToken = default
);
Task<bool> UseApiKey(
XOpenActionRequestDto dto,
CancellationToken cancellationToken = default
);
Task<XOpenActionUserInfoDto> GetUserInfo( Task<XOpenActionUserInfoDto> GetUserInfo(
XOpenActionRequestDto dto XOpenActionRequestDto dto
); );
+16 -6
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) {
.ConfigureWebHostDefaults(webBuilder => //
{ var result = Host.CreateDefaultBuilder(args)
webBuilder.UseStartup<Startup>(); .ConfigureLogging(logging =>
}); logging.AddXTelemetryLogger())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.AddXTelemetry();
//
return result;
}
} }
} }
+28 -52
View File
@@ -1,7 +1,6 @@
using System; using System;
using IdentityModel;
using xIds.Interfaces; using xIds.Interfaces;
using xCommons.Constants; using System.Threading;
using xCommons.Extensions; using xCommons.Extensions;
using xExceptions.Constants; using xExceptions.Constants;
using System.Security.Claims; using System.Security.Claims;
@@ -10,10 +9,10 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using xIdentityModels.Constants; using xIdentityModels.Constants;
using xIdentityService.Constants; using xIdentityService.Constants;
using System.Collections.Generic; using xIdentityModels.Extensions;
using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using System.Threading; using Microsoft.Extensions.DependencyInjection;
namespace xIds.Providers namespace xIds.Providers
{ {
@@ -22,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.
@@ -36,7 +35,7 @@ namespace xIds.Providers
// //
if (!scopes.HasChild()) if (!scopes.HasChild())
{ {
scopes = [XApiKeyScope.Manage]; scopes = [XApiKeyScope.Read];
} }
// //
@@ -47,20 +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>
/// <returns></returns>
private async Task OnAuthorizationAsync(
AuthorizationFilterContext context,
CancellationToken cancellationToken = default
)
{ {
// //
// Access HttpContext ... // Access HttpContext ...
@@ -78,13 +64,12 @@ namespace xIds.Providers
// //
// Retrieve the application provider from DI ... // Retrieve the application provider from DI ...
var applicationProvider = http.RequestServices var applicationProvider = http.RequestServices
.GetService(typeof(IXApplicationProvider)) .GetService<IXApplicationProvider>();
as IXApplicationProvider;
if (applicationProvider.IsNull()) if (applicationProvider.IsNull())
{ {
// //
error.Message = "Api Key Service not Registered ..."; error.Message = "Api Key Service not Registered ...";
context.Result = new UnauthorizedObjectResult(error.ToJSON()); context.Result = new UnauthorizedObjectResult(error);
return; return;
} }
@@ -95,7 +80,7 @@ namespace xIds.Providers
{ {
// //
error.Message = "ApiKey not Exists ..."; error.Message = "ApiKey not Exists ...";
context.Result = new UnauthorizedObjectResult(error.ToJSON()); context.Result = new UnauthorizedObjectResult(error);
return; return;
} }
@@ -106,7 +91,7 @@ namespace xIds.Providers
{ {
// //
error.Message = "ApiKey not Provided ..."; error.Message = "ApiKey not Provided ...";
context.Result = new UnauthorizedObjectResult(error.ToJSON()); context.Result = new UnauthorizedObjectResult(error);
return; return;
} }
@@ -126,42 +111,20 @@ 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())
{ {
// //
var message = validationResult.Errors.ToListString('\n'); var message = validationResult.Errors.ToListString(',');
error.Message = message; error.Message = message;
context.Result = new UnauthorizedObjectResult(error.ToJSON()); context.Result = new UnauthorizedObjectResult(error);
return; return;
} }
// //
// Creating Claims ... // Creating Claims ...
var claims = new List<Claim> { var claims = validationResult.ToXClaims();
//
// Owner Identifier of API Key ...
new(ClaimTypes.Name, validationResult.OwnerId),
new(JwtClaimTypes.Subject, validationResult.OwnerId),
//
// Application Id ...
new(XCustomClaims.ApplicationId, validationResult.ApplicationId.ToString()),
//
// Authentication Type ...
new(XCustomClaims.AuthType, apiKeyAuthentication),
};
//
// Add Scopes ...
if (validationResult.Scopes != null)
{
//
foreach (var scope in validationResult.Scopes)
{
claims.Add(new Claim(JwtClaimTypes.Scope, scope));
}
}
// //
// Create Principal and Ticket ... // Create Principal and Ticket ...
@@ -175,8 +138,21 @@ namespace xIds.Providers
{ {
// //
error.Message = "ApiKey authorization failed ..."; error.Message = "ApiKey authorization failed ...";
context.Result = new UnauthorizedObjectResult(error.ToJSON()); 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
{ {
@@ -304,8 +304,8 @@ namespace xIds.Providers
newExpiration = TimeSpan newExpiration = TimeSpan
.FromMinutes(apiKeyConfiguration.DefaultExpirationMinutes); .FromMinutes(apiKeyConfiguration.DefaultExpirationMinutes);
} }
expiredDate = DateTime.UtcNow.Add(newExpiration.Value); expiredDate = DateTime.UtcNow.Add(newExpiration.Value);
// //
if (!expiredDate.HasValue) if (!expiredDate.HasValue)
{ {
@@ -431,8 +431,8 @@ namespace xIds.Providers
// //
// Here we Have to Parse Allowed Ips and Scopes ... // Here we Have to Parse Allowed Ips and Scopes ...
var allowedIps = keyModel.AllowedIPs.IsNullOrEmpty() var allowedIps = keyModel.AllowedIPs.IsNullOrEmpty()
? [] ? []
: keyModel.AllowedIPs.ParseListString<string>(); : keyModel.AllowedIPs.ParseListString<string>();
var allowedScopes = keyModel.AllowedScopes.IsNullOrEmpty() var allowedScopes = keyModel.AllowedScopes.IsNullOrEmpty()
? [] ? []
@@ -499,25 +499,17 @@ namespace xIds.Providers
} }
// //
var requiredScopes = var requiredScopes =
requiredScope.IsNullOrEmpty() requiredScope.IsNullOrEmpty()
? [] ? []
: requiredScope.ParseListString<string>(); : requiredScope.ParseListString<string>();
//
// Audit Log ...
// //
// Check Scope and IP is Valid or not ... // Check Scope and IP is Valid or not ...
var isIpValid = var isIpValid = allowedIps.IsClientIpPassed(clientIP);
!allowedIps.HasChild() ||
allowedIps.Contains(clientIP);
var isScopeValid = var isScopeValid =
!allowedScopes.HasChild() || allowedScopes
requiredScope.IsNullOrEmpty() || .IsScopePassed(requiredScopes);
requiredScopes
.All(ts => allowedScopes
.Any(asc => asc.ToNormalString() == ts.ToNormalString()));
var isScopeIpValid = var isScopeIpValid =
isIpValid && isIpValid &&
isScopeValid isScopeValid
@@ -545,6 +537,27 @@ namespace xIds.Providers
isApplicationActive; isApplicationActive;
if (isValid) if (isValid)
{ {
//
// Handle Attach Owner ...
try
{
//
var user = await identityManager.GetUserAsync(
containsDetail: true,
userSelectByParam: application.OwnerId
);
//
var owner = user.ToXPerson();
result.Owner = owner;
}
catch (Exception ex)
{
//
result.Errors.Add($"exception occured: {ex.Message}");
return result;
}
result.Errors.Clear(); result.Errors.Clear();
} }
+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,10 +1,13 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading;
using xCommons.Extensions; using xCommons.Extensions;
using xExceptions.Constants;
using xIdentityModels.Dtos; using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using xIdentityModels.Models;
namespace xIds.Providers namespace xIds.Providers
{ {
@@ -12,6 +15,11 @@ namespace xIds.Providers
{ {
// //
#region OpenGet ... #region OpenGet ...
/// <summary>
/// Get Open Action ...
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public async Task<XOpenActionInnerDto> OpenGet( public async Task<XOpenActionInnerDto> OpenGet(
XOpenActionInnerDto model XOpenActionInnerDto model
) )
@@ -32,7 +40,12 @@ namespace xIds.Providers
); );
} }
// /// <summary>
/// Get Open Action ...
/// </summary>
/// <param name="token"></param>
/// <param name="actionRequest"></param>
/// <returns></returns>
public async Task<XOpenActionInnerDto> OpenGet( public async Task<XOpenActionInnerDto> OpenGet(
string token, string token,
string actionRequest string actionRequest
@@ -61,6 +74,22 @@ namespace xIds.Providers
var responseJson = string.Empty; var responseJson = string.Empty;
switch (requestModel.Action) switch (requestModel.Action)
{ {
//
case XOpenActions.GetApiKey:
//
ValidationProvider.NotEmpty(requestModel.Payload);
var apiKeyId = await GetApiKey(requestModel);
responseJson = apiKeyId.ToString();
break;
//
case XOpenActions.UseApiKey:
//
ValidationProvider.NotEmpty(requestModel.Payload);
var isUsed = await UseApiKey(requestModel);
responseJson = isUsed.ToString();
break;
// //
case XOpenActions.GetUserInfo: case XOpenActions.GetUserInfo:
// //
@@ -119,6 +148,86 @@ namespace xIds.Providers
} }
#endregion #endregion
/// <summary>
/// Get Specified Api Key ...
/// </summary>
/// <param name="model"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<Guid> GetApiKey(
XOpenActionRequestDto model,
CancellationToken cancellationToken = default
)
{
//
var apiKey = await DbContext.ApiKeys
.FirstOrDefaultAsync(x =>
x.Key == model.Payload,
cancellationToken: cancellationToken
);
var result = Guid.Empty;
if (!apiKey.IsNullOrDefault())
{
result = apiKey.Id;
}
//
return result;
}
/// <summary>
/// Use Specified Api Key ...
/// </summary>
/// <param name="model"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<bool> UseApiKey(
XOpenActionRequestDto model,
CancellationToken cancellationToken = default
)
{
//
// Load Model from Request ...
var apiKeyUsage = model.Payload.FromJSON<XApiKeyUsageDto>();
var result = !apiKeyUsage.IsNullOrDefault();
if (!result)
{
return result;
}
//
// Reading ApiKey ...
var apiKey = await DbContext.ApiKeys
.FirstOrDefaultAsync(x => x.Id == apiKeyUsage.ApiKeyId);
apiKey.LastUsedAt = DateTime.UtcNow;
DbContext.ApiKeys.Update(apiKey);
await DbContext.SaveChangesAsync();
//
// Prepare Entity ...
var entiy = new XApiKeyUsage
{
ApiKeyId = apiKeyUsage.ApiKeyId,
Endpoint = apiKeyUsage.Endpoint,
ClientIP = apiKeyUsage.ClientIP,
HttpMethod = apiKeyUsage.HttpMethod,
StatusCode = apiKeyUsage.StatusCode,
RequestedOn = apiKeyUsage.RequestedOn,
ResponseTimeMs = apiKeyUsage.ResponseTimeMs,
};
await DbContext.ApiKeyUsages.AddAsync(entiy);
var changes = await DbContext.SaveChangesAsync();
result = changes > 0;
//
return result;
}
/// <summary>
/// Get User Info For Open Actions ...
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public async Task<XOpenActionUserInfoDto> GetUserInfo( public async Task<XOpenActionUserInfoDto> GetUserInfo(
XOpenActionRequestDto model XOpenActionRequestDto model
) )
@@ -137,16 +246,22 @@ namespace xIds.Providers
// Generate a Dynamic Object ... // Generate a Dynamic Object ...
var result = new XOpenActionUserInfoDto var result = new XOpenActionUserInfoDto
{ {
UserId = userProfile.UserId,
Avatar = userProfile.Avatar,
Username = userProfile.UserName, Username = userProfile.UserName,
Firstname = userProfile.FirstName,
Lastname = userProfile.LastName, Lastname = userProfile.LastName,
Avatar = userProfile.Avatar Firstname = userProfile.FirstName,
}; };
// //
return result; return result;
} }
/// <summary>
/// Retrieve a Collection of Open Actions User Info by Providing Ids ...
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public async Task<IEnumerable<XOpenActionUserInfoDto>> GetUserInfos( public async Task<IEnumerable<XOpenActionUserInfoDto>> GetUserInfos(
XOpenActionRequestDto model XOpenActionRequestDto model
) )
@@ -162,6 +277,7 @@ namespace xIds.Providers
); );
var result = profiles.Select(x => new XOpenActionUserInfoDto var result = profiles.Select(x => new XOpenActionUserInfoDto
{ {
UserId = x.UserId,
Avatar = x.Avatar, Avatar = x.Avatar,
Username = x.UserName, Username = x.UserName,
Lastname = x.LastName, Lastname = x.LastName,
@@ -174,6 +290,12 @@ namespace xIds.Providers
// //
#region Private ... #region Private ...
/// <summary>
/// Parse Models ...
/// </summary>
/// <param name="token"></param>
/// <param name="request"></param>
/// <returns></returns>
private XOpenActionRequestDto ParseModel( private XOpenActionRequestDto ParseModel(
string token, string token,
string request string request
@@ -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
}
}
+24 -8
View File
@@ -6,6 +6,7 @@ using xIds.Providers;
using Newtonsoft.Json; using Newtonsoft.Json;
using xIds.Interfaces; using xIds.Interfaces;
using System.Reflection; using System.Reflection;
using xLoggingService.DI;
using xStorageService.DI; using xStorageService.DI;
using xCommons.Extensions; using xCommons.Extensions;
using xCommons.Configurations; using xCommons.Configurations;
@@ -31,13 +32,17 @@ namespace xIds
{ {
// //
// Register Validation Provider and all XCommons Module Services ... // Register Validation Provider and all XCommons Module Services ...
services.AddXCommons(); services.AddXCommons(Configuration);
// //
// Register App Configuration ... // Register App Configuration ...
services.AddXAppConfiguration(Configuration); services.AddXAppConfiguration(Configuration);
var appConfiguration = services.GetRegisteredService<XAppConfiguration>(); var appConfiguration = services.GetRegisteredService<XAppConfiguration>();
//
// Register Logging Service ...
services.AddXLoggingService(Configuration);
// //
// Register XDataService Configuration ... // Register XDataService Configuration ...
services.AddXDataServiceConfiguration(Configuration, ConnectionStringNames.IDENTITY_CONNECTION_NAME); services.AddXDataServiceConfiguration(Configuration, ConnectionStringNames.IDENTITY_CONNECTION_NAME);
@@ -75,19 +80,20 @@ namespace xIds
// //
// Register Security Provider ... // Register Security Provider ...
services.AddSingleton<IXSecurityProvider, XSecurityProvider>(); services.AddSingleton<IXSecurityProvider, XSecurityProvider>();
} }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) public void Configure(
IApplicationBuilder app,
IWebHostEnvironment env,
ILogger<Startup> logger
)
{ {
// //
if (env.IsDevelopment()) var isDevelopmentEnvironment = env.IsDevelopment();
if (isDevelopmentEnvironment)
{ {
//
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
//
// app.UseXRequestLogger();
} }
// //
@@ -113,6 +119,13 @@ namespace xIds
// //
app.UseRouting(); app.UseRouting();
//
// Using Request Logging ...
if (!isDevelopmentEnvironment)
{
app.UseXRequestLogger();
}
// //
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
@@ -125,3 +138,6 @@ namespace xIds
} }
} }
} }
+4 -4
View File
@@ -1,11 +1,11 @@
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.Models; using IdentityServer4.Models;
using IdentityServer4.Stores; using IdentityServer4.Stores;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.EntityFramework.DbContexts;
namespace xIds.Stores namespace xIds.Stores
{ {
+430 -390
View File
@@ -1,397 +1,437 @@
{ {
"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",
"AllowedOrigins": [ "DefaultCacheTtlMinutes": 10,
"https://saherelm.ir", "AllowedOrigins": [
"https://saherelmhub.ir", "https://saherelm.ir",
"https://api.saherelm.ir", "https://saherelmhub.ir",
"https://api.saherelmhub.ir" "https://api.saherelm.ir",
], "https://api.saherelmhub.ir"
"SwaggerConfiguration": { ],
"Version": "v1.0", "SwaggerConfiguration": {
"Title": "xSaherElm Identity Server API", "Version": "v1.0",
"Description": "Complete API Documentation", "Title": "xSaherElm Identity Server API",
"Contact": { "Description": "Complete API Documentation",
"Name": "Hadi Khazaee Asl", "Contact": {
"Email": "hadi_khazaee_asl@yahoo.com", "Name": "Hadi Khazaee Asl",
"Url": "https://www.saherelm.ir" "Email": "hadi_khazaee_asl@yahoo.com",
} "Url": "https://www.saherelm.ir"
}, }
"DbProvider": "SQLite", },
"ConnectionStrings": { "DbProvider": "SQLite",
"IdentityDb": "Filename=./Db/XIdentity.db;Foreign Keys=False", "ConnectionStrings": {
"ConfigurationDb": "Filename=./Db/XConfigurations.db", "IdentityDb": "Filename=./Db/XIdentity.db;Foreign Keys=False",
"PersistedGrantDb": "Filename=./Db/XPersistedGrants.db" "ConfigurationDb": "Filename=./Db/XConfigurations.db",
}, "PersistedGrantDb": "Filename=./Db/XPersistedGrants.db"
"DataServiceConfiguration": { },
"PagingConfiguration": { "DataServiceConfiguration": {
"DefaultPageSize": 20, "PagingConfiguration": {
"MaxAvailablePageSize": 400, "DefaultPageSize": 20,
"MinAvailablePageSize": 20 "MaxAvailablePageSize": 400,
} "MinAvailablePageSize": 20
}, }
"Certificates": { },
"IdentityServerSigning": { "Certificates": {
"Path": "Certificate/xIds.pfx", "IdentityServerSigning": {
"Secret": "s@1694056" "Path": "Certificate/xIds.pfx",
} "Secret": "s@1694056"
}, }
"IdentityConfiguration": { },
"IdentityIssuer": "SaherElm Identity Server", "IdentityConfiguration": {
"IdentityAudience": "SaherElmIdentityAPI", "IdentityIssuer": "SaherElm Identity Server",
"IdentitySecretKey": "SaherElmITCenter@1694056", "IdentityAudience": "SaherElmIdentityAPI",
"ActionTokenExpirationDateProvider": "20m", "IdentitySecretKey": "SaherElmITCenter@1694056",
"IdentityRoles": [ "ActionTokenExpirationDateProvider": "20m",
"admin", "IdentityRoles": [
"responsible_manager", "admin",
"journalist", "responsible_manager",
"chief_clerk", "journalist",
"chief_clerk_assistant", "chief_clerk",
"actuary", "chief_clerk_assistant",
"actuary_assistant", "actuary",
"reporter", "actuary_assistant",
"reporter_assistant", "reporter",
"agent", "reporter_assistant",
"user" "agent",
], "user"
"AutoConfirmNewUsersEmail": false, ],
"AutoConfirmNewUsersPhoneNumber": false, "AutoConfirmNewUsersEmail": false,
"RegistrationJustWithInvite": false, "AutoConfirmNewUsersPhoneNumber": false,
"RequireRegistrationConfirm": true, "RegistrationJustWithInvite": false,
"MaxNumberOfVerificationCodeSend": 3, "RequireRegistrationConfirm": true,
"DeleyBetweenTwoVerificationCode": 180, "MaxNumberOfVerificationCodeSend": 3,
"NewUsersRole": "user", "DeleyBetweenTwoVerificationCode": 180,
"Policy": { "NewUsersRole": "user",
"Lockout": { "Policy": {
"LockoutTimeSpanProvider": "15m", "Lockout": {
"MaxFailedAccessAttempts": 5, "LockoutTimeSpanProvider": "15m",
"AllowedForNewUsers": true "MaxFailedAccessAttempts": 5,
}, "AllowedForNewUsers": true
"Password": { },
"RequireDigit": true, "Password": {
"RequiredLength": 6, "RequireDigit": true,
"RequiredUniqueChars": 1, "RequiredLength": 6,
"RequireLowercase": true, "RequiredUniqueChars": 1,
"RequireNonAlphanumeric": true, "RequireLowercase": true,
"RequireUppercase": true "RequireNonAlphanumeric": true,
}, "RequireUppercase": true
"SignIn": { },
"RequiredEnabled": true, "SignIn": {
"RequireConfirmedEmail": true, "RequiredEnabled": true,
"RequireConfirmedPhoneNumber": false "RequireConfirmedEmail": true,
}, "RequireConfirmedPhoneNumber": false
"User": { },
"AllowedUserNameCharacters": "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._", "User": {
"RequireUniqueEmail": true, "AllowedUserNameCharacters": "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._",
"MinLength": 6, "RequireUniqueEmail": true,
"MaxLength": 20, "MinLength": 6,
"MinAgeForRegistration": 18, "MaxLength": 20,
"MaxAgeForRegistration": 60, "MinAgeForRegistration": 18,
"InvalidUserNames": [ "MaxAgeForRegistration": 60,
"InvalidUserNames": [
"saherelm", "saherelm",
"admin", "admin",
"responsible_manager", "responsible_manager",
"journalist", "journalist",
"chief_clerk", "chief_clerk",
"chief_clerk_assistant", "chief_clerk_assistant",
"actuary", "actuary",
"actuary_assistant", "actuary_assistant",
"reporter", "reporter",
"reporter_assistant", "reporter_assistant",
"agent", "agent",
"user" "user"
] ]
}, },
"Profile": { "Profile": {
"ContainsEmail": false, "ContainsEmail": false,
"ContainsPhoneNumber": false, "ContainsPhoneNumber": false,
"ContainsRoles": true, "ContainsRoles": true,
"ContainsLastLogin": false, "ContainsLastLogin": false,
"ContainsDateOfBirth": false, "ContainsDateOfBirth": false,
"ContainsCreationDate": true "ContainsCreationDate": true
} }
}, },
"IdentityMessages": [ "IdentityMessages": [
{ {
"Language": "fa-IR", "Language": "fa-IR",
"ResourceTitle": "user_invite_msg", "ResourceTitle": "user_invite_msg",
"TranslatedValue": "شما دعوت شده اید تا در سامانه ثبت نام کنید" "TranslatedValue": "شما دعوت شده اید تا در سامانه ثبت نام کنید"
}, },
{ {
"Language": "en-US", "Language": "en-US",
"ResourceTitle": "user_invite_msg", "ResourceTitle": "user_invite_msg",
"TranslatedValue": "You are Invited to Register at Dashboard" "TranslatedValue": "You are Invited to Register at Dashboard"
}, },
{ {
"Language": "fa-IR", "Language": "fa-IR",
"ResourceTitle": "registration_approve_msg", "ResourceTitle": "registration_approve_msg",
"TranslatedValue": "شما باید حساب کاربری خود را با ورود به پیوند زیر فعال کنید" "TranslatedValue": "شما باید حساب کاربری خود را با ورود به پیوند زیر فعال کنید"
}, },
{ {
"Language": "en-US", "Language": "en-US",
"ResourceTitle": "registration_approve_msg", "ResourceTitle": "registration_approve_msg",
"TranslatedValue": "you must activate your account by going to this link" "TranslatedValue": "you must activate your account by going to this link"
}, },
{ {
"Language": "fa-IR", "Language": "fa-IR",
"ResourceTitle": "registered_msg", "ResourceTitle": "registered_msg",
"TranslatedValue": "ثبت نام شما در سامانه با موفقیت پایان یافت" "TranslatedValue": "ثبت نام شما در سامانه با موفقیت پایان یافت"
}, },
{ {
"Language": "en-US", "Language": "en-US",
"ResourceTitle": "registered_msg", "ResourceTitle": "registered_msg",
"TranslatedValue": "you successfully registered at Dashboard" "TranslatedValue": "you successfully registered at Dashboard"
}, },
{ {
"Language": "fa-IR", "Language": "fa-IR",
"ResourceTitle": "verification_code_msg", "ResourceTitle": "verification_code_msg",
"TranslatedValue": "کد اعتبار سنجی شما در سامانه" "TranslatedValue": "کد اعتبار سنجی شما در سامانه"
}, },
{ {
"Language": "en-US", "Language": "en-US",
"ResourceTitle": "verification_code_msg", "ResourceTitle": "verification_code_msg",
"TranslatedValue": "Your Verification Code at Dashboard" "TranslatedValue": "Your Verification Code at Dashboard"
}, },
{ {
"Language": "fa-IR", "Language": "fa-IR",
"ResourceTitle": "change_password_msg", "ResourceTitle": "change_password_msg",
"TranslatedValue": "برای تغییر کلمه عبور پیوند زیر را دنبال کنید" "TranslatedValue": "برای تغییر کلمه عبور پیوند زیر را دنبال کنید"
}, },
{ {
"Language": "en-US", "Language": "en-US",
"ResourceTitle": "change_password_msg", "ResourceTitle": "change_password_msg",
"TranslatedValue": "for change password please follow this link" "TranslatedValue": "for change password please follow this link"
}, },
{ {
"Language": "fa-IR", "Language": "fa-IR",
"ResourceTitle": "password_changed_msg", "ResourceTitle": "password_changed_msg",
"TranslatedValue": "کلمه عبور شما در سامانه تغییر یافت" "TranslatedValue": "کلمه عبور شما در سامانه تغییر یافت"
}, },
{ {
"Language": "en-US", "Language": "en-US",
"ResourceTitle": "password_changed_msg", "ResourceTitle": "password_changed_msg",
"TranslatedValue": "your password at Dashboard changed" "TranslatedValue": "your password at Dashboard changed"
}, },
{ {
"Language": "fa-IR", "Language": "fa-IR",
"ResourceTitle": "new_device_logged_in_msg", "ResourceTitle": "new_device_logged_in_msg",
"TranslatedValue": "ابزار جدیدی با مشخصات ذیل در سامانه با حساب کاربری شما وارد شده است" "TranslatedValue": "ابزار جدیدی با مشخصات ذیل در سامانه با حساب کاربری شما وارد شده است"
}, },
{ {
"Language": "en-US", "Language": "en-US",
"ResourceTitle": "new_device_logged_in_msg", "ResourceTitle": "new_device_logged_in_msg",
"TranslatedValue": "new device with following details loggedin with your account in Dashboard" "TranslatedValue": "new device with following details loggedin with your account in Dashboard"
} }
] ]
}, },
"IdentityResourceConfiguration": { "IdentityResourceConfiguration": {
"Authority": "https://172.18.0.151", "Authority": "https://172.18.0.151",
"ApiName": "xSaherElmAPI", "ApiName": "xSaherElmAPI",
"ApiSecret": "s@H@1694056", "ApiSecret": "s@H@1694056",
"ClientId": "xSaherElmAPIClient", "ClientId": "xSaherElmAPIClient",
"ClientSecret": "s@H@1694056", "ClientSecret": "s@H@1694056",
"XPoweredValue": "SaherElmITCenter", "XPoweredValue": "SaherElmITCenter",
"XRevisionSecretKey": "SaherElmITCenter@1694056" "XRevisionSecretKey": "SaherElmITCenter@1694056"
}, },
"StorageConfiguration": { "StorageConfiguration": {
"Authority": "https://ids.saherelm.ir", "Authority": "https://ids.saherelm.ir",
"IdentityAuthority": "https://ids.saherelm.ir", "IdentityAuthority": "https://ids.saherelm.ir",
"Storage": "Storage", "Storage": "Storage",
"Temp": "Temp", "Temp": "Temp",
"Thumb": "Thumb", "Thumb": "Thumb",
"Uploads": "Uploads", "Uploads": "Uploads",
"Widgets": "Widgets", "Widgets": "Widgets",
"Image": "Image", "Image": "Image",
"Audio": "Audio", "Audio": "Audio",
"Video": "Video", "Video": "Video",
"Document": "Document", "Document": "Document",
"FilePrefix": "xSaherElm_", "FilePrefix": "xSaherElm_",
"ThumbPrefix": "Thumb_", "ThumbPrefix": "Thumb_",
"ThumbSize": 512, "ThumbSize": 512,
"ThumbQuality": 72, "ThumbQuality": 72,
"MaxFileSize": 41943040 "MaxFileSize": 41943040
}, },
"MessageConfiguration": { "MessageConfiguration": {
"MailConfigurations": { "MailConfigurations": {
"gmail": { "gmail": {
"Title": "SaherElm Dashboard", "Title": "SaherElm Dashboard",
"Host": "smtp.gmail.com", "Host": "smtp.gmail.com",
"Port": 587, "Port": 587,
"EnableSsl": true, "EnableSsl": true,
"Username": "saherelm@gmail.com", "Username": "saherelm@gmail.com",
"Password": "vzuz gtrk tndb ctbc" "Password": "vzuz gtrk tndb ctbc"
} }
}, },
"SmsConfigurations": { "SmsConfigurations": {
"yoursms": { "yoursms": {
"ServiceUrl": "http://sms.yourprovider.ir", "ServiceUrl": "http://sms.yourprovider.ir",
"Username": "user", "Username": "user",
"Password": "psw", "Password": "psw",
"LineNumber": "linenumber", "LineNumber": "linenumber",
"UserApiKey": "", "UserApiKey": "",
"SecretKey": "" "SecretKey": ""
} }
} }
}, },
"DbSeeder": { "DbSeeder": {
"UpdateExists": false, "UpdateExists": false,
"Clients": [ "Clients": [
{ {
"ClientId": "xSaherElmAPIClient", "ClientId": "xSaherElmAPIClient",
"ClientName": "Web Client of xMabsut API", "ClientName": "Web Client of xMabsut API",
"ClientSecrets": [ "ClientSecrets": [
{ {
"Description": null, "Description": null,
"Value": "NKaAKXeE9Ws+VVGGHsmM9DUO84cla4+hvx8swP1uuEg=", "Value": "NKaAKXeE9Ws+VVGGHsmM9DUO84cla4+hvx8swP1uuEg=",
"Expiration": null, "Expiration": null,
"Type": "SharedSecret" "Type": "SharedSecret"
} }
], ],
"Enabled": true, "Enabled": true,
"RedirectUris": ["https://localhost:5001/signin-oidc"], "RedirectUris": [
"AllowedGrantTypes": [ "https://localhost:5001/signin-oidc"
"hybrid", ],
"password", "AllowedGrantTypes": [
"client_credentials" "hybrid",
], "password",
"AllowedScopes": [ "client_credentials"
"IdentityServerApi", ],
"openid", "AllowedScopes": [
"profile", "IdentityServerApi",
"XAPI.read", "openid",
"XAPI.write", "profile",
"XAPI.admin", "XAPI.read",
"manage", "XAPI.write",
"offline_access" "XAPI.admin",
], "manage",
"AllowedCorsOrigins": [ "offline_access"
"http://saherelm.ir", ],
"AllowedCorsOrigins": [
"http://saherelm.ir",
"https://saherelm.ir", "https://saherelm.ir",
"http://saherelmhub.ir", "http://saherelmhub.ir",
"https://saherelmhub.ir" "https://saherelmhub.ir"
], ],
"AllowOfflineAccess": true, "AllowOfflineAccess": true,
"RefreshTokenUsage": 1, "RefreshTokenUsage": 1,
"AccessTokenType": 1, "AccessTokenType": 1,
"RefreshTokenExpiration": 0, "RefreshTokenExpiration": 0,
"AbsoluteRefreshTokenLifetime": 2592000, "AbsoluteRefreshTokenLifetime": 2592000,
"SlidingRefreshTokenLifetime": 1296000, "SlidingRefreshTokenLifetime": 1296000,
"UpdateAccessTokenClaimsOnRefresh": true, "UpdateAccessTokenClaimsOnRefresh": true,
"IdentityTokenLifetime": 300, "IdentityTokenLifetime": 300,
"AccessTokenLifetime": 3600, "AccessTokenLifetime": 3600,
"AuthorizationCodeLifetime": 300, "AuthorizationCodeLifetime": 300,
"DeviceCodeLifetime": 300 "DeviceCodeLifetime": 300
} }
], ],
"IdentityResources": ["openid", "profile", "email", "role"], "IdentityResources": [
"ApiResources": [ "openid",
{ "profile",
"Name": "IdentityServerApi" "email",
}, "role"
{ ],
"Name": "xSaherElmAPI", "ApiResources": [
"DisplayName": "xSaherElm API", {
"Description": "Protected by IdentityServer API Access", "Name": "IdentityServerApi"
"ApiSecrets": [ },
{ {
"Description": null, "Name": "xSaherElmAPI",
"Value": "NKaAKXeE9Ws+VVGGHsmM9DUO84cla4+hvx8swP1uuEg=", "DisplayName": "xSaherElm API",
"Expiration": null, "Description": "Protected by IdentityServer API Access",
"Type": "SharedSecret" "ApiSecrets": [
} {
], "Description": null,
"Enabled": true, "Value": "NKaAKXeE9Ws+VVGGHsmM9DUO84cla4+hvx8swP1uuEg=",
"Scopes": [ "Expiration": null,
"openid", "Type": "SharedSecret"
"profile", }
"XAPI.read", ],
"XAPI.write", "Enabled": true,
"XAPI.admin", "Scopes": [
"manage" "openid",
], "profile",
"UserClaims": [ "XAPI.read",
"name", "XAPI.write",
"role", "XAPI.admin",
"unique_name", "manage"
"gender", ],
"birthdate", "UserClaims": [
"picture", "name",
"email", "role",
"phone_number", "unique_name",
"email_verified", "gender",
"phone_number_verified", "birthdate",
"is_enabled", "picture",
"is_banned", "email",
"creation_date", "phone_number",
"last_login", "email_verified",
"given_name", "phone_number_verified",
"family_name" "is_enabled",
] "is_banned",
} "creation_date",
], "last_login",
"ApiScopes": [ "given_name",
{ "family_name"
"Name": "IdentityServerApi" ]
}, }
{ ],
"Name": "xSaherElmAPI" "ApiScopes": [
}, {
{ "Name": "IdentityServerApi"
"Name": "XAPI.read", },
"DisplayName": "Read Access for XAPI" {
}, "Name": "xSaherElmAPI"
{ },
"Name": "XAPI.write", {
"DisplayName": "Write Access for XAPI" "Name": "XAPI.read",
}, "DisplayName": "Read Access for XAPI"
{ },
"Name": "XAPI.admin", {
"DisplayName": "Admin Access for XAPI" "Name": "XAPI.write",
}, "DisplayName": "Write Access for XAPI"
{ },
"Name": "manage", {
"DisplayName": "Admin Access for All APIs" "Name": "XAPI.admin",
} "DisplayName": "Admin Access for XAPI"
], },
"Users": [ {
{ "Name": "manage",
"Id": "b5713f9f-34f4-49b2-9680-b71e2b2de969", "DisplayName": "Admin Access for All APIs"
"FirstName": "Hadi", }
"LastName": "Khazaee Asl", ],
"UserName": "admin", "Users": [
"Email": "hadi_khazaee_asl@yahoo.com", {
"EmailConfirmed": true, "Id": "b5713f9f-34f4-49b2-9680-b71e2b2de969",
"PhoneNumber": "+989121694056", "FirstName": "Hadi",
"PhoneNumberConfirmed": true, "LastName": "Khazaee Asl",
"Password": "s@H@1694056", "UserName": "admin",
"Role": "admin", "Email": "hadi_khazaee_asl@yahoo.com",
"DateOfBirth": "1982-09-17 20:30:00.0000000", "EmailConfirmed": true,
"IsEnable": true "PhoneNumber": "+989121694056",
}, "PhoneNumberConfirmed": true,
{ "Password": "s@H@1694056",
"Id": "83b09f5e-edd2-4e9a-8c5f-c4c129ee9d52", "Role": "admin",
"FirstName": "Hadi", "DateOfBirth": "1982-09-17 20:30:00.0000000",
"LastName": "Khazaee Asl", "IsEnable": true
"UserName": "agent", },
"Email": "hadi.khazaee.asl@gmail.com", {
"EmailConfirmed": true, "Id": "83b09f5e-edd2-4e9a-8c5f-c4c129ee9d52",
"PhoneNumber": "+989101879789", "FirstName": "Hadi",
"PhoneNumberConfirmed": true, "LastName": "Khazaee Asl",
"Password": "a@A@1694056", "UserName": "agent",
"Role": "agent", "Email": "hadi.khazaee.asl@gmail.com",
"DateOfBirth": "1982-09-17 20:30:00.0000000", "EmailConfirmed": true,
"IsEnable": true "PhoneNumber": "+989101879789",
} "PhoneNumberConfirmed": true,
] "Password": "a@A@1694056",
}, "Role": "agent",
"Logging": { "DateOfBirth": "1982-09-17 20:30:00.0000000",
"LogLevel": { "IsEnable": true
"Default": "Information", }
"Microsoft": "Warning", ]
"Microsoft.Hosting.Lifetime": "Information" },
} "LoggingServiceConfiguration": {
}, "Enabled": true,
"AllowedHosts": "*" "MinimumLevel": "Information",
"Queue": {
"Enabled": true,
"Capacity": 10000,
"ShutdownTimeoutSeconds": 10
},
"File": {
"Enabled": true,
"Format": "Json",
"Directory": "./Logs",
"FileName": "xIds-.log",
"MinimumLevel": "Information",
"RetainedFileCountLimit": 30
},
"Database": {
"Enabled": false,
"TableName": "XLogs",
"AutoCreateTable": true,
"MinimumLevel": "Warning",
"Provider": "Microsoft.Data.Sqlite",
"ConnectionString": "Filename=./Db/XLogs.db"
},
"Event": {
"Enabled": false,
"Sender": "xIds",
"MinimumLevel": "Error",
"Topic": "application-logs",
"Action": "ApplicationLogCreated"
}
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
} }
+5 -6
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>
@@ -23,18 +24,16 @@
<!-- Icon Handling --> <!-- Icon Handling -->
<ItemGroup> <ItemGroup>
<None Include="../../Resources/Images/favicon.png" Link="icon.png" Pack="true" <None Include="../../Resources/Images/favicon.png" Link="icon.png" Pack="true" PackagePath="\icon.png" />
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" />
@@ -53,8 +52,7 @@
<PackageReference Include="IdentityModel.AspNetCore.OAuth2Introspection" Version="5.0.0" /> <PackageReference Include="IdentityModel.AspNetCore.OAuth2Introspection" Version="5.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.12" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.12" />
<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" <PackageReference Include="IdentityModel.AspNetCore.AccessTokenValidation" Version="1.0.0-preview.3" />
Version="1.0.0-preview.3" />
</ItemGroup> </ItemGroup>
<!-- Ef Core --> <!-- Ef Core -->
@@ -84,4 +82,5 @@
<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>
</Project> </Project>