Compare commits
19
Commits
be3fd31b4e
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49483d1d39 | ||
|
|
9d913146e1 | ||
|
|
384cffac36 | ||
|
|
869a0476a0 | ||
|
|
1cf90dcd9e | ||
|
|
3a556a329a | ||
|
|
24363e89ae | ||
|
|
8d392b3d84 | ||
|
|
b311b1e391 | ||
|
|
df3ed7868b | ||
|
|
73a59f9181 | ||
|
|
3b099a3089 | ||
|
|
bc49b0aa86 | ||
|
|
018ef161a8 | ||
|
|
986025c44b | ||
|
|
9b4453f4b1 | ||
|
|
6203c7e084 | ||
|
|
9fb70e14d7 | ||
|
|
6b648ede44 |
@@ -1,6 +1,7 @@
|
||||
#
|
||||
bin
|
||||
obj
|
||||
Logs
|
||||
|
||||
#
|
||||
Db/*
|
||||
|
||||
@@ -15,6 +15,12 @@ namespace xIds.Controllers
|
||||
|
||||
//
|
||||
#region Open Actions ...
|
||||
/// <summary>
|
||||
/// Get Open Action ...
|
||||
/// </summary>
|
||||
/// <param name="token"></param>
|
||||
/// <param name="request"></param>
|
||||
/// <returns></returns>
|
||||
[AllowAnonymous]
|
||||
[RequireXPowered]
|
||||
[HttpGet("Open")]
|
||||
|
||||
@@ -15,7 +15,7 @@ namespace xIds.Controllers
|
||||
//
|
||||
#region Test Actions ...
|
||||
/// <summary>
|
||||
/// API Read Scope
|
||||
/// API Read Scope ...
|
||||
/// </summary>
|
||||
/// <returns>string message</returns>
|
||||
[RequireXPowered]
|
||||
@@ -28,7 +28,7 @@ namespace xIds.Controllers
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// API Write Scope
|
||||
/// API Write Scope ...
|
||||
/// </summary>
|
||||
/// <returns>string message</returns>
|
||||
[RequireXPowered]
|
||||
@@ -41,7 +41,7 @@ namespace xIds.Controllers
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// API Admin Scope
|
||||
/// API Admin Scope ...
|
||||
/// </summary>
|
||||
/// <returns>string message</returns>
|
||||
[RequireXPowered]
|
||||
@@ -54,7 +54,7 @@ namespace xIds.Controllers
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// API Manage Scop
|
||||
/// API Manage Scop ...
|
||||
/// </summary>
|
||||
/// <returns>string message</returns>
|
||||
[RequireXPowered]
|
||||
@@ -67,7 +67,7 @@ namespace xIds.Controllers
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// a simple Action which returns a List of Authenticated User Claims
|
||||
/// a simple Action which returns a List of Authenticated User Claims ...
|
||||
/// </summary>
|
||||
/// <returns>string message which represent current user's claims</returns>
|
||||
[RequireXPowered]
|
||||
@@ -92,7 +92,7 @@ namespace xIds.Controllers
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// a simple Hello User for Checking Authentication and Policy
|
||||
/// a simple Hello User for Checking Authentication and Policy ...
|
||||
/// </summary>
|
||||
/// <returns>string message which contains authenticated user name</returns>
|
||||
[RequireXPowered]
|
||||
@@ -109,7 +109,7 @@ namespace xIds.Controllers
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// a simple Hello User for Checking Authentication and Policy
|
||||
/// a simple Hello User for Checking Authentication and Policy ...
|
||||
/// </summary>
|
||||
/// <returns>string message which contains authenticated user name</returns>
|
||||
[RequireXPowered]
|
||||
@@ -126,7 +126,7 @@ namespace xIds.Controllers
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// a simple Hello User for Checking Authentication and Policy
|
||||
/// a simple Hello User for Checking Authentication and Policy ...
|
||||
/// </summary>
|
||||
/// <returns>string message which contains authenticated user name</returns>
|
||||
[RequireXPowered]
|
||||
@@ -143,7 +143,7 @@ namespace xIds.Controllers
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// a simple Hello User for Checking Authentication and Policy
|
||||
/// a simple Hello User for Checking Authentication and Policy ...
|
||||
/// </summary>
|
||||
/// <returns>string message which contains authenticated user name</returns>
|
||||
[RequireXPowered]
|
||||
@@ -159,11 +159,15 @@ namespace xIds.Controllers
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// a simple Hello for Accessing ApiKey Authorization ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[XApiKeyAccess]
|
||||
[AllowAnonymous]
|
||||
[RequireXPowered]
|
||||
[HttpGet("Test/HiApiKeyAccess")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[XApiKeyAccess(scopes: [XApiKeyScope.Manage])]
|
||||
public ActionResult<string> HiApiKeyAccess()
|
||||
{
|
||||
//
|
||||
@@ -173,11 +177,15 @@ namespace xIds.Controllers
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// a simple Hello for Accessing ApiKey Read Access ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[AllowAnonymous]
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpGet("Test/HiApiKeyReadAccess")]
|
||||
[XApiKeyAccess(scopes: [XApiKeyScope.Read])]
|
||||
[XApiKeyAccess(Scopes = [XApiKeyScope.Read])]
|
||||
public ActionResult<string> HiApiKeyReadAccess()
|
||||
{
|
||||
//
|
||||
@@ -187,6 +195,10 @@ namespace xIds.Controllers
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// a simple Hello for Accessing ApiKey Write Access ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[AllowAnonymous]
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
@@ -201,6 +213,10 @@ namespace xIds.Controllers
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// a simple Hello for Accessing ApiKey Manage Access ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[AllowAnonymous]
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
@@ -215,6 +231,10 @@ namespace xIds.Controllers
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// a simple Hello for Accessing ApiKey Admin Access ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[AllowAnonymous]
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
using xIds.Interfaces;
|
||||
using xCommons.Providers;
|
||||
using xCommons.Attributes;
|
||||
using xIds.Controllers.Base;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace xIds.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Provide all available tools for manipulating users and accounts
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
[RequireXPowered]
|
||||
public partial class AccountController : XIBaseController
|
||||
{
|
||||
|
||||
public AccountController(
|
||||
IXIdentityManager identityManager,
|
||||
ILogger<AccountController> logger,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using xModels.Dtos;
|
||||
using System.Threading;
|
||||
using xIdentityHelper;
|
||||
using System.Threading;
|
||||
using xCommons.Attributes;
|
||||
using xCommons.Extensions;
|
||||
using xIdentityModels.Dtos;
|
||||
|
||||
@@ -90,14 +90,16 @@ namespace xIds.Controllers
|
||||
/// }
|
||||
///
|
||||
/// </remarks>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="item"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPut("")]
|
||||
[HttpPut("{id}")]
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XApplicationDto>> UpdateApplication(
|
||||
[FromRoute] int id,
|
||||
[FromBody] XApplicationDto item,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
@@ -107,7 +109,10 @@ namespace xIds.Controllers
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (!item.IsValidForAdd())
|
||||
if (!id.IsValidIntId() ||
|
||||
!item.IsValidForAdd() ||
|
||||
id != item.Id
|
||||
)
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
@@ -117,8 +122,8 @@ namespace xIds.Controllers
|
||||
|
||||
//
|
||||
var result = await provider.UpdateApplicationAsync(
|
||||
id: id,
|
||||
item: item,
|
||||
id: item.Id,
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
@@ -18,6 +18,8 @@ namespace xIds.Controllers
|
||||
{
|
||||
public partial class ApplicationsController
|
||||
{
|
||||
//
|
||||
#region Custom ...
|
||||
/// <summary>
|
||||
/// Show Api Key ...
|
||||
/// </summary>
|
||||
@@ -510,6 +512,7 @@ namespace xIds.Controllers
|
||||
/// <param name="request"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[AllowAnonymous]
|
||||
[RequireXPowered]
|
||||
[HttpPost("ApiKeys/Validate")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
@@ -532,6 +535,19 @@ namespace xIds.Controllers
|
||||
|
||||
//
|
||||
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(
|
||||
@@ -552,5 +568,6 @@ namespace xIds.Controllers
|
||||
return result;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,32 @@
|
||||
using xIds.Interfaces;
|
||||
using xCommons.Providers;
|
||||
using xIds.Configurations;
|
||||
using xCommons.Attributes;
|
||||
using xIds.Controllers.Base;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace xIds.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Provide all available tools for manipulating users and accounts
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
[RequireXPowered]
|
||||
public partial class ApplicationsController : XIBaseController
|
||||
{
|
||||
private readonly IXApplicationProvider provider;
|
||||
private readonly IXSecurityProvider securityProvider;
|
||||
private readonly XApiKeyConfiguration apiKeyConfiguration;
|
||||
|
||||
public ApplicationsController(
|
||||
IXApplicationProvider provider,
|
||||
IXIdentityManager identityManager,
|
||||
XAppConfiguration appConfiguration,
|
||||
IXSecurityProvider securityProvider,
|
||||
ILogger<ApplicationsController> logger,
|
||||
XValidationProvider validationProvider,
|
||||
XApiKeyConfiguration apiKeyConfiguration
|
||||
@@ -31,7 +37,9 @@ namespace xIds.Controllers
|
||||
validationProvider
|
||||
)
|
||||
{
|
||||
//
|
||||
this.provider = provider;
|
||||
this.securityProvider = securityProvider;
|
||||
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
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,19 @@
|
||||
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 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
|
||||
{
|
||||
@@ -226,6 +227,54 @@ namespace xIds.Controllers.Base
|
||||
|
||||
//
|
||||
#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>
|
||||
/// Convert an Exception to Propper Error Result
|
||||
/// </summary>
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
using System.Linq;
|
||||
using xIds.Helpers;
|
||||
using xIds.Constants;
|
||||
using xIds.DbContext;
|
||||
using xIds.Providers;
|
||||
using IdentityServer4;
|
||||
using xIdentityHelper;
|
||||
using xIdentityModels;
|
||||
using xIds.Extensions;
|
||||
using xIds.Interfaces;
|
||||
using xIds.Validators;
|
||||
using IdentityServer4;
|
||||
using xCommons.Constants;
|
||||
using xMessageService.DI;
|
||||
using xStorageService.DI;
|
||||
@@ -18,6 +19,9 @@ using xCommons.Authorization;
|
||||
using System.Collections.Generic;
|
||||
using xMessageService.Interfaces;
|
||||
using xStorageService.Interfaces;
|
||||
using xIdentityService.Providers;
|
||||
using xIdentityService.Extensions;
|
||||
using xIdentityService.Interfaces;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
@@ -79,6 +83,27 @@ namespace xIds.DI
|
||||
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>
|
||||
/// Retrive XDataService Configurations ...
|
||||
/// </summary>
|
||||
@@ -433,6 +458,7 @@ namespace xIds.DI
|
||||
)
|
||||
{
|
||||
//
|
||||
var policyHandler = services.GetRegisteredService<IXPolicyHandler>();
|
||||
services.AddAuthorization(options =>
|
||||
{
|
||||
//
|
||||
@@ -446,6 +472,26 @@ namespace xIds.DI
|
||||
{
|
||||
var policyDescriptor = policiesEnumerator.Current;
|
||||
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())
|
||||
{
|
||||
//
|
||||
var policyDescriptor = policiesEnumerator.Current;
|
||||
|
||||
//
|
||||
// Add Policy to Authorization ...
|
||||
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>();
|
||||
|
||||
//
|
||||
// Register Providers ...
|
||||
services.AddXAuthorizationProviders();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -20,6 +20,9 @@ namespace xIds.DbContext
|
||||
public DbSet<XBannedDevice> BannedDevices { get; set; }
|
||||
public DbSet<XFriendshipFollower> Followers { 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; }
|
||||
#endregion
|
||||
|
||||
@@ -73,6 +76,24 @@ namespace xIds.DbContext
|
||||
e.HasIndex(k => k.KeyHash).IsUnique();
|
||||
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();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
using System;
|
||||
using xIds.Models;
|
||||
using xIds.Constants;
|
||||
using System.Reflection;
|
||||
using xIds.Configurations;
|
||||
using xCommons.Extensions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using xIdentityModels.Configurations;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using MySql.EntityFrameworkCore.Infrastructure;
|
||||
using xCommons.Extensions;
|
||||
using xIdentityModels.Configurations;
|
||||
using xIds.Configurations;
|
||||
using xIds.Constants;
|
||||
using xIds.Models;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
|
||||
namespace xIds.Extensions
|
||||
{
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
using xIds.Constants;
|
||||
using xCommons.Models;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using xCommons.Extensions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using xCommons.Extensions;
|
||||
using xCommons.Models;
|
||||
using xIds.Constants;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
namespace xIds.Extensions
|
||||
{
|
||||
|
||||
@@ -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
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
using xIds.Providers;
|
||||
using xIds.Interfaces;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using xIdentityService.Interfaces;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace xIds.Extensions
|
||||
@@ -25,5 +28,37 @@ namespace xIds.Extensions
|
||||
{
|
||||
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>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using xIds.Models;
|
||||
using xIds.Constants;
|
||||
using xIds.Interfaces;
|
||||
using xCommons.Extensions;
|
||||
using System.Threading.Tasks;
|
||||
using IdentityServer4.EntityFramework.DbContexts;
|
||||
using IdentityServer4.EntityFramework.Mappers;
|
||||
using System.Collections.Generic;
|
||||
using xIdentityModels.Extensions;
|
||||
using xIdentityModels.Descriptors;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using IdentityServer4.EntityFramework.Mappers;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using xCommons.Extensions;
|
||||
using xIdentityModels.Descriptors;
|
||||
using xIdentityModels.Extensions;
|
||||
using xIds.Constants;
|
||||
using xIds.Interfaces;
|
||||
using xIds.Models;
|
||||
using IdentityServer4.EntityFramework.DbContexts;
|
||||
|
||||
namespace xIds.Extensions
|
||||
{
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using xModels.Dtos;
|
||||
using System.Reflection;
|
||||
using xCommons.Extensions;
|
||||
using xDataService.Configuration;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using xDataService.Constants;
|
||||
using xIdentityModels.Models;
|
||||
using System.Linq.Expressions;
|
||||
using System.Collections.Generic;
|
||||
using xDataService.Configuration;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace xIds.Extensions
|
||||
{
|
||||
@@ -32,6 +37,146 @@ namespace xIds.Extensions
|
||||
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>
|
||||
/// Applying Filter to IQueryable
|
||||
/// /// </summary>
|
||||
@@ -87,5 +232,175 @@ namespace xIds.Extensions
|
||||
//
|
||||
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));
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -87,9 +87,9 @@ namespace xIds.Helpers
|
||||
var result = new TokenValidationParameters
|
||||
{
|
||||
ValidIssuer = issuer,
|
||||
ValidAudience = audience,
|
||||
IssuerSigningKey = key,
|
||||
ValidateLifetime = true,
|
||||
IssuerSigningKey = key
|
||||
ValidAudience = audience,
|
||||
};
|
||||
|
||||
//
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using xModels.Dtos;
|
||||
using xIds.DbContext;
|
||||
using System.Net.Http;
|
||||
using xIdentityModels;
|
||||
using System.Threading;
|
||||
using xCommons.Providers;
|
||||
using IdentityModel.Client;
|
||||
using xIdentityModels.Dtos;
|
||||
using System.Security.Claims;
|
||||
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 Microsoft.AspNetCore.Http;
|
||||
using xIdentityModels.Constants;
|
||||
using System.Collections.Generic;
|
||||
using xIdentityModels.Descriptors;
|
||||
using xIdentityModels.Navigations;
|
||||
using xIds.DbContext;
|
||||
using xModels.Dtos;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace xIds.Interfaces
|
||||
{
|
||||
@@ -87,6 +88,10 @@ namespace xIds.Interfaces
|
||||
);
|
||||
Task<IdentityResult> RemoveFromRoleAsync(XUser user, string roleName);
|
||||
Task<IdentityResult> RemoveFromRolesAsync(XUser user, IEnumerable<string> roleNames);
|
||||
Task<IdentityResult> DeleteRoleAsync(
|
||||
string roleName,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
#endregion
|
||||
|
||||
//
|
||||
@@ -462,6 +467,16 @@ namespace xIds.Interfaces
|
||||
);
|
||||
#endregion
|
||||
|
||||
Task<Guid> GetApiKey(
|
||||
XOpenActionRequestDto dto,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
Task<bool> UseApiKey(
|
||||
XOpenActionRequestDto dto,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
Task<XOpenActionUserInfoDto> GetUserInfo(
|
||||
XOpenActionRequestDto dto
|
||||
);
|
||||
|
||||
+16
-6
@@ -1,3 +1,4 @@
|
||||
using xLoggingService.DI;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
@@ -10,11 +11,20 @@ namespace xIds
|
||||
CreateHostBuilder(args).Build().Run();
|
||||
}
|
||||
|
||||
public static IHostBuilder CreateHostBuilder(string[] args) =>
|
||||
Host.CreateDefaultBuilder(args)
|
||||
.ConfigureWebHostDefaults(webBuilder =>
|
||||
{
|
||||
webBuilder.UseStartup<Startup>();
|
||||
});
|
||||
public static IHostBuilder CreateHostBuilder(string[] args)
|
||||
{
|
||||
//
|
||||
var result = Host.CreateDefaultBuilder(args)
|
||||
.ConfigureLogging(logging =>
|
||||
logging.AddXTelemetryLogger())
|
||||
.ConfigureWebHostDefaults(webBuilder =>
|
||||
{
|
||||
webBuilder.UseStartup<Startup>();
|
||||
})
|
||||
.AddXTelemetry();
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
using System;
|
||||
using IdentityModel;
|
||||
using xIds.Interfaces;
|
||||
using xCommons.Constants;
|
||||
using System.Threading;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using System.Security.Claims;
|
||||
@@ -10,10 +9,10 @@ using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using xIdentityModels.Constants;
|
||||
using xIdentityService.Constants;
|
||||
using System.Collections.Generic;
|
||||
using xIdentityModels.Extensions;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using System.Threading;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace xIds.Providers
|
||||
{
|
||||
@@ -22,7 +21,7 @@ namespace xIds.Providers
|
||||
AllowMultiple = false,
|
||||
Inherited = true
|
||||
)]
|
||||
public class XApiKeyAccessAttribute : AuthorizeAttribute, IAuthorizationFilter
|
||||
public class XApiKeyAccessAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
|
||||
{
|
||||
/// <summary>
|
||||
/// Optional allowed scopes. If empty, no scope enforcement.
|
||||
@@ -36,7 +35,7 @@ namespace xIds.Providers
|
||||
//
|
||||
if (!scopes.HasChild())
|
||||
{
|
||||
scopes = [XApiKeyScope.Manage];
|
||||
scopes = [XApiKeyScope.Read];
|
||||
}
|
||||
|
||||
//
|
||||
@@ -47,20 +46,7 @@ namespace xIds.Providers
|
||||
/// Authorization Filtering ...
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
public void OnAuthorization(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
|
||||
)
|
||||
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
|
||||
{
|
||||
//
|
||||
// Access HttpContext ...
|
||||
@@ -78,13 +64,12 @@ namespace xIds.Providers
|
||||
//
|
||||
// Retrieve the application provider from DI ...
|
||||
var applicationProvider = http.RequestServices
|
||||
.GetService(typeof(IXApplicationProvider))
|
||||
as IXApplicationProvider;
|
||||
.GetService<IXApplicationProvider>();
|
||||
if (applicationProvider.IsNull())
|
||||
{
|
||||
//
|
||||
error.Message = "Api Key Service not Registered ...";
|
||||
context.Result = new UnauthorizedObjectResult(error.ToJSON());
|
||||
context.Result = new UnauthorizedObjectResult(error);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -95,7 +80,7 @@ namespace xIds.Providers
|
||||
{
|
||||
//
|
||||
error.Message = "ApiKey not Exists ...";
|
||||
context.Result = new UnauthorizedObjectResult(error.ToJSON());
|
||||
context.Result = new UnauthorizedObjectResult(error);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -106,7 +91,7 @@ namespace xIds.Providers
|
||||
{
|
||||
//
|
||||
error.Message = "ApiKey not Provided ...";
|
||||
context.Result = new UnauthorizedObjectResult(error.ToJSON());
|
||||
context.Result = new UnauthorizedObjectResult(error);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -126,42 +111,20 @@ namespace xIds.Providers
|
||||
userInfo: null,
|
||||
clientIP: clientIP,
|
||||
requiredScope: scopes,
|
||||
cancellationToken: cancellationToken
|
||||
cancellationToken: default
|
||||
);
|
||||
if (validationResult.Errors.HasChild())
|
||||
{
|
||||
//
|
||||
var message = validationResult.Errors.ToListString('\n');
|
||||
var message = validationResult.Errors.ToListString(',');
|
||||
error.Message = message;
|
||||
context.Result = new UnauthorizedObjectResult(error.ToJSON());
|
||||
context.Result = new UnauthorizedObjectResult(error);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Creating Claims ...
|
||||
var claims = new List<Claim> {
|
||||
//
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
var claims = validationResult.ToXClaims();
|
||||
|
||||
//
|
||||
// Create Principal and Ticket ...
|
||||
@@ -175,8 +138,21 @@ namespace xIds.Providers
|
||||
{
|
||||
//
|
||||
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,4 +1,5 @@
|
||||
using System;
|
||||
using AutoMapper;
|
||||
using System.Linq;
|
||||
using xModels.Dtos;
|
||||
using xIds.DbContext;
|
||||
@@ -14,7 +15,6 @@ using IdentityServer4.Extensions;
|
||||
using xIdentityModels.Extensions;
|
||||
using Microsoft.EntityFrameworkCore.Query;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using AutoMapper;
|
||||
|
||||
namespace xIds.Providers
|
||||
{
|
||||
|
||||
@@ -304,8 +304,8 @@ namespace xIds.Providers
|
||||
newExpiration = TimeSpan
|
||||
.FromMinutes(apiKeyConfiguration.DefaultExpirationMinutes);
|
||||
}
|
||||
expiredDate = DateTime.UtcNow.Add(newExpiration.Value);
|
||||
|
||||
expiredDate = DateTime.UtcNow.Add(newExpiration.Value);
|
||||
|
||||
//
|
||||
if (!expiredDate.HasValue)
|
||||
{
|
||||
@@ -431,8 +431,8 @@ namespace xIds.Providers
|
||||
|
||||
//
|
||||
// Here we Have to Parse Allowed Ips and Scopes ...
|
||||
var allowedIps = keyModel.AllowedIPs.IsNullOrEmpty()
|
||||
? []
|
||||
var allowedIps = keyModel.AllowedIPs.IsNullOrEmpty()
|
||||
? []
|
||||
: keyModel.AllowedIPs.ParseListString<string>();
|
||||
var allowedScopes = keyModel.AllowedScopes.IsNullOrEmpty()
|
||||
? []
|
||||
@@ -499,25 +499,17 @@ namespace xIds.Providers
|
||||
}
|
||||
|
||||
//
|
||||
var requiredScopes =
|
||||
var requiredScopes =
|
||||
requiredScope.IsNullOrEmpty()
|
||||
? []
|
||||
: requiredScope.ParseListString<string>();
|
||||
|
||||
//
|
||||
// Audit Log ...
|
||||
|
||||
//
|
||||
// Check Scope and IP is Valid or not ...
|
||||
var isIpValid =
|
||||
!allowedIps.HasChild() ||
|
||||
allowedIps.Contains(clientIP);
|
||||
var isIpValid = allowedIps.IsClientIpPassed(clientIP);
|
||||
var isScopeValid =
|
||||
!allowedScopes.HasChild() ||
|
||||
requiredScope.IsNullOrEmpty() ||
|
||||
requiredScopes
|
||||
.All(ts => allowedScopes
|
||||
.Any(asc => asc.ToNormalString() == ts.ToNormalString()));
|
||||
allowedScopes
|
||||
.IsScopePassed(requiredScopes);
|
||||
var isScopeIpValid =
|
||||
isIpValid &&
|
||||
isScopeValid
|
||||
@@ -545,6 +537,27 @@ namespace xIds.Providers
|
||||
isApplicationActive;
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Threading;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using xIdentityModels.Dtos;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using xIdentityModels.Models;
|
||||
|
||||
namespace xIds.Providers
|
||||
{
|
||||
@@ -12,6 +15,11 @@ namespace xIds.Providers
|
||||
{
|
||||
//
|
||||
#region OpenGet ...
|
||||
/// <summary>
|
||||
/// Get Open Action ...
|
||||
/// </summary>
|
||||
/// <param name="model"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<XOpenActionInnerDto> OpenGet(
|
||||
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(
|
||||
string token,
|
||||
string actionRequest
|
||||
@@ -61,6 +74,22 @@ namespace xIds.Providers
|
||||
var responseJson = string.Empty;
|
||||
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:
|
||||
//
|
||||
@@ -119,6 +148,86 @@ namespace xIds.Providers
|
||||
}
|
||||
#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(
|
||||
XOpenActionRequestDto model
|
||||
)
|
||||
@@ -137,16 +246,22 @@ namespace xIds.Providers
|
||||
// Generate a Dynamic Object ...
|
||||
var result = new XOpenActionUserInfoDto
|
||||
{
|
||||
UserId = userProfile.UserId,
|
||||
Avatar = userProfile.Avatar,
|
||||
Username = userProfile.UserName,
|
||||
Firstname = userProfile.FirstName,
|
||||
Lastname = userProfile.LastName,
|
||||
Avatar = userProfile.Avatar
|
||||
Firstname = userProfile.FirstName,
|
||||
};
|
||||
|
||||
//
|
||||
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(
|
||||
XOpenActionRequestDto model
|
||||
)
|
||||
@@ -162,6 +277,7 @@ namespace xIds.Providers
|
||||
);
|
||||
var result = profiles.Select(x => new XOpenActionUserInfoDto
|
||||
{
|
||||
UserId = x.UserId,
|
||||
Avatar = x.Avatar,
|
||||
Username = x.UserName,
|
||||
Lastname = x.LastName,
|
||||
@@ -174,6 +290,12 @@ namespace xIds.Providers
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
/// <summary>
|
||||
/// Parse Models ...
|
||||
/// </summary>
|
||||
/// <param name="token"></param>
|
||||
/// <param name="request"></param>
|
||||
/// <returns></returns>
|
||||
private XOpenActionRequestDto ParseModel(
|
||||
string token,
|
||||
string request
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using xIdentityModels;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using xIdentityModels;
|
||||
using xIdentityModels.Constants;
|
||||
using xIdentityModels.Models;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using xIdentityModels.Constants;
|
||||
using xIdentityModels.Navigations;
|
||||
|
||||
namespace xIds.Providers
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using xCommons.Extensions;
|
||||
@@ -211,6 +212,55 @@ namespace xIds.Providers
|
||||
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>
|
||||
/// Check a User is Adminr not
|
||||
/// </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 xModels.Dtos;
|
||||
using xIds.Extensions;
|
||||
using xCommons.Extensions;
|
||||
using xIdentityModels.Dtos;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using xDataService.Extensions;
|
||||
using xIdentityModels.Extensions;
|
||||
|
||||
namespace xIds.Providers
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -6,6 +6,7 @@ using xIds.Providers;
|
||||
using Newtonsoft.Json;
|
||||
using xIds.Interfaces;
|
||||
using System.Reflection;
|
||||
using xLoggingService.DI;
|
||||
using xStorageService.DI;
|
||||
using xCommons.Extensions;
|
||||
using xCommons.Configurations;
|
||||
@@ -31,13 +32,17 @@ namespace xIds
|
||||
{
|
||||
//
|
||||
// Register Validation Provider and all XCommons Module Services ...
|
||||
services.AddXCommons();
|
||||
services.AddXCommons(Configuration);
|
||||
|
||||
//
|
||||
// Register App Configuration ...
|
||||
services.AddXAppConfiguration(Configuration);
|
||||
var appConfiguration = services.GetRegisteredService<XAppConfiguration>();
|
||||
|
||||
//
|
||||
// Register Logging Service ...
|
||||
services.AddXLoggingService(Configuration);
|
||||
|
||||
//
|
||||
// Register XDataService Configuration ...
|
||||
services.AddXDataServiceConfiguration(Configuration, ConnectionStringNames.IDENTITY_CONNECTION_NAME);
|
||||
@@ -75,19 +80,20 @@ namespace xIds
|
||||
|
||||
//
|
||||
// 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.UseXRequestLogger();
|
||||
}
|
||||
|
||||
//
|
||||
@@ -113,6 +119,13 @@ namespace xIds
|
||||
//
|
||||
app.UseRouting();
|
||||
|
||||
//
|
||||
// Using Request Logging ...
|
||||
if (!isDevelopmentEnvironment)
|
||||
{
|
||||
app.UseXRequestLogger();
|
||||
}
|
||||
|
||||
//
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
@@ -125,3 +138,6 @@ namespace xIds
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using IdentityServer4.EntityFramework.DbContexts;
|
||||
using IdentityServer4.EntityFramework.Mappers;
|
||||
using IdentityServer4.Models;
|
||||
using IdentityServer4.Stores;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using IdentityServer4.EntityFramework.Mappers;
|
||||
using IdentityServer4.EntityFramework.DbContexts;
|
||||
|
||||
namespace xIds.Stores
|
||||
{
|
||||
|
||||
+430
-390
@@ -1,397 +1,437 @@
|
||||
{
|
||||
"Version": "0.1",
|
||||
"XPoweredValue": "SaherElmITCenter",
|
||||
"Name": "xIdentityServer",
|
||||
"WelcomeMessage": "Welcome to xSaherElm Project's xIdentityServer",
|
||||
"AllowedOrigins": [
|
||||
"https://saherelm.ir",
|
||||
"https://saherelmhub.ir",
|
||||
"https://api.saherelm.ir",
|
||||
"https://api.saherelmhub.ir"
|
||||
],
|
||||
"SwaggerConfiguration": {
|
||||
"Version": "v1.0",
|
||||
"Title": "xSaherElm Identity Server API",
|
||||
"Description": "Complete API Documentation",
|
||||
"Contact": {
|
||||
"Name": "Hadi Khazaee Asl",
|
||||
"Email": "hadi_khazaee_asl@yahoo.com",
|
||||
"Url": "https://www.saherelm.ir"
|
||||
}
|
||||
},
|
||||
"DbProvider": "SQLite",
|
||||
"ConnectionStrings": {
|
||||
"IdentityDb": "Filename=./Db/XIdentity.db;Foreign Keys=False",
|
||||
"ConfigurationDb": "Filename=./Db/XConfigurations.db",
|
||||
"PersistedGrantDb": "Filename=./Db/XPersistedGrants.db"
|
||||
},
|
||||
"DataServiceConfiguration": {
|
||||
"PagingConfiguration": {
|
||||
"DefaultPageSize": 20,
|
||||
"MaxAvailablePageSize": 400,
|
||||
"MinAvailablePageSize": 20
|
||||
}
|
||||
},
|
||||
"Certificates": {
|
||||
"IdentityServerSigning": {
|
||||
"Path": "Certificate/xIds.pfx",
|
||||
"Secret": "s@1694056"
|
||||
}
|
||||
},
|
||||
"IdentityConfiguration": {
|
||||
"IdentityIssuer": "SaherElm Identity Server",
|
||||
"IdentityAudience": "SaherElmIdentityAPI",
|
||||
"IdentitySecretKey": "SaherElmITCenter@1694056",
|
||||
"ActionTokenExpirationDateProvider": "20m",
|
||||
"IdentityRoles": [
|
||||
"admin",
|
||||
"responsible_manager",
|
||||
"journalist",
|
||||
"chief_clerk",
|
||||
"chief_clerk_assistant",
|
||||
"actuary",
|
||||
"actuary_assistant",
|
||||
"reporter",
|
||||
"reporter_assistant",
|
||||
"agent",
|
||||
"user"
|
||||
],
|
||||
"AutoConfirmNewUsersEmail": false,
|
||||
"AutoConfirmNewUsersPhoneNumber": false,
|
||||
"RegistrationJustWithInvite": false,
|
||||
"RequireRegistrationConfirm": true,
|
||||
"MaxNumberOfVerificationCodeSend": 3,
|
||||
"DeleyBetweenTwoVerificationCode": 180,
|
||||
"NewUsersRole": "user",
|
||||
"Policy": {
|
||||
"Lockout": {
|
||||
"LockoutTimeSpanProvider": "15m",
|
||||
"MaxFailedAccessAttempts": 5,
|
||||
"AllowedForNewUsers": true
|
||||
},
|
||||
"Password": {
|
||||
"RequireDigit": true,
|
||||
"RequiredLength": 6,
|
||||
"RequiredUniqueChars": 1,
|
||||
"RequireLowercase": true,
|
||||
"RequireNonAlphanumeric": true,
|
||||
"RequireUppercase": true
|
||||
},
|
||||
"SignIn": {
|
||||
"RequiredEnabled": true,
|
||||
"RequireConfirmedEmail": true,
|
||||
"RequireConfirmedPhoneNumber": false
|
||||
},
|
||||
"User": {
|
||||
"AllowedUserNameCharacters": "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._",
|
||||
"RequireUniqueEmail": true,
|
||||
"MinLength": 6,
|
||||
"MaxLength": 20,
|
||||
"MinAgeForRegistration": 18,
|
||||
"MaxAgeForRegistration": 60,
|
||||
"InvalidUserNames": [
|
||||
"Version": "0.1",
|
||||
"Name": "xIdentityServer",
|
||||
"XPoweredValue": "SaherElmITCenter",
|
||||
"WelcomeMessage": "Welcome to xSaherElm Project's xIdentityServer",
|
||||
"DefaultCacheTtlMinutes": 10,
|
||||
"AllowedOrigins": [
|
||||
"https://saherelm.ir",
|
||||
"https://saherelmhub.ir",
|
||||
"https://api.saherelm.ir",
|
||||
"https://api.saherelmhub.ir"
|
||||
],
|
||||
"SwaggerConfiguration": {
|
||||
"Version": "v1.0",
|
||||
"Title": "xSaherElm Identity Server API",
|
||||
"Description": "Complete API Documentation",
|
||||
"Contact": {
|
||||
"Name": "Hadi Khazaee Asl",
|
||||
"Email": "hadi_khazaee_asl@yahoo.com",
|
||||
"Url": "https://www.saherelm.ir"
|
||||
}
|
||||
},
|
||||
"DbProvider": "SQLite",
|
||||
"ConnectionStrings": {
|
||||
"IdentityDb": "Filename=./Db/XIdentity.db;Foreign Keys=False",
|
||||
"ConfigurationDb": "Filename=./Db/XConfigurations.db",
|
||||
"PersistedGrantDb": "Filename=./Db/XPersistedGrants.db"
|
||||
},
|
||||
"DataServiceConfiguration": {
|
||||
"PagingConfiguration": {
|
||||
"DefaultPageSize": 20,
|
||||
"MaxAvailablePageSize": 400,
|
||||
"MinAvailablePageSize": 20
|
||||
}
|
||||
},
|
||||
"Certificates": {
|
||||
"IdentityServerSigning": {
|
||||
"Path": "Certificate/xIds.pfx",
|
||||
"Secret": "s@1694056"
|
||||
}
|
||||
},
|
||||
"IdentityConfiguration": {
|
||||
"IdentityIssuer": "SaherElm Identity Server",
|
||||
"IdentityAudience": "SaherElmIdentityAPI",
|
||||
"IdentitySecretKey": "SaherElmITCenter@1694056",
|
||||
"ActionTokenExpirationDateProvider": "20m",
|
||||
"IdentityRoles": [
|
||||
"admin",
|
||||
"responsible_manager",
|
||||
"journalist",
|
||||
"chief_clerk",
|
||||
"chief_clerk_assistant",
|
||||
"actuary",
|
||||
"actuary_assistant",
|
||||
"reporter",
|
||||
"reporter_assistant",
|
||||
"agent",
|
||||
"user"
|
||||
],
|
||||
"AutoConfirmNewUsersEmail": false,
|
||||
"AutoConfirmNewUsersPhoneNumber": false,
|
||||
"RegistrationJustWithInvite": false,
|
||||
"RequireRegistrationConfirm": true,
|
||||
"MaxNumberOfVerificationCodeSend": 3,
|
||||
"DeleyBetweenTwoVerificationCode": 180,
|
||||
"NewUsersRole": "user",
|
||||
"Policy": {
|
||||
"Lockout": {
|
||||
"LockoutTimeSpanProvider": "15m",
|
||||
"MaxFailedAccessAttempts": 5,
|
||||
"AllowedForNewUsers": true
|
||||
},
|
||||
"Password": {
|
||||
"RequireDigit": true,
|
||||
"RequiredLength": 6,
|
||||
"RequiredUniqueChars": 1,
|
||||
"RequireLowercase": true,
|
||||
"RequireNonAlphanumeric": true,
|
||||
"RequireUppercase": true
|
||||
},
|
||||
"SignIn": {
|
||||
"RequiredEnabled": true,
|
||||
"RequireConfirmedEmail": true,
|
||||
"RequireConfirmedPhoneNumber": false
|
||||
},
|
||||
"User": {
|
||||
"AllowedUserNameCharacters": "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._",
|
||||
"RequireUniqueEmail": true,
|
||||
"MinLength": 6,
|
||||
"MaxLength": 20,
|
||||
"MinAgeForRegistration": 18,
|
||||
"MaxAgeForRegistration": 60,
|
||||
"InvalidUserNames": [
|
||||
"saherelm",
|
||||
"admin",
|
||||
"responsible_manager",
|
||||
"journalist",
|
||||
"chief_clerk",
|
||||
"chief_clerk_assistant",
|
||||
"actuary",
|
||||
"actuary_assistant",
|
||||
"reporter",
|
||||
"reporter_assistant",
|
||||
"agent",
|
||||
"user"
|
||||
]
|
||||
},
|
||||
"Profile": {
|
||||
"ContainsEmail": false,
|
||||
"ContainsPhoneNumber": false,
|
||||
"ContainsRoles": true,
|
||||
"ContainsLastLogin": false,
|
||||
"ContainsDateOfBirth": false,
|
||||
"ContainsCreationDate": true
|
||||
}
|
||||
},
|
||||
"IdentityMessages": [
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "user_invite_msg",
|
||||
"TranslatedValue": "شما دعوت شده اید تا در سامانه ثبت نام کنید"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "user_invite_msg",
|
||||
"TranslatedValue": "You are Invited to Register at Dashboard"
|
||||
},
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "registration_approve_msg",
|
||||
"TranslatedValue": "شما باید حساب کاربری خود را با ورود به پیوند زیر فعال کنید"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "registration_approve_msg",
|
||||
"TranslatedValue": "you must activate your account by going to this link"
|
||||
},
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "registered_msg",
|
||||
"TranslatedValue": "ثبت نام شما در سامانه با موفقیت پایان یافت"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "registered_msg",
|
||||
"TranslatedValue": "you successfully registered at Dashboard"
|
||||
},
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "verification_code_msg",
|
||||
"TranslatedValue": "کد اعتبار سنجی شما در سامانه"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "verification_code_msg",
|
||||
"TranslatedValue": "Your Verification Code at Dashboard"
|
||||
},
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "change_password_msg",
|
||||
"TranslatedValue": "برای تغییر کلمه عبور پیوند زیر را دنبال کنید"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "change_password_msg",
|
||||
"TranslatedValue": "for change password please follow this link"
|
||||
},
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "password_changed_msg",
|
||||
"TranslatedValue": "کلمه عبور شما در سامانه تغییر یافت"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "password_changed_msg",
|
||||
"TranslatedValue": "your password at Dashboard changed"
|
||||
},
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "new_device_logged_in_msg",
|
||||
"TranslatedValue": "ابزار جدیدی با مشخصات ذیل در سامانه با حساب کاربری شما وارد شده است"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "new_device_logged_in_msg",
|
||||
"TranslatedValue": "new device with following details loggedin with your account in Dashboard"
|
||||
}
|
||||
]
|
||||
},
|
||||
"IdentityResourceConfiguration": {
|
||||
"Authority": "https://172.18.0.151",
|
||||
"ApiName": "xSaherElmAPI",
|
||||
"ApiSecret": "s@H@1694056",
|
||||
"ClientId": "xSaherElmAPIClient",
|
||||
"ClientSecret": "s@H@1694056",
|
||||
"XPoweredValue": "SaherElmITCenter",
|
||||
"XRevisionSecretKey": "SaherElmITCenter@1694056"
|
||||
},
|
||||
"StorageConfiguration": {
|
||||
"Authority": "https://ids.saherelm.ir",
|
||||
"IdentityAuthority": "https://ids.saherelm.ir",
|
||||
"Storage": "Storage",
|
||||
"Temp": "Temp",
|
||||
"Thumb": "Thumb",
|
||||
"Uploads": "Uploads",
|
||||
"Widgets": "Widgets",
|
||||
"Image": "Image",
|
||||
"Audio": "Audio",
|
||||
"Video": "Video",
|
||||
"Document": "Document",
|
||||
"FilePrefix": "xSaherElm_",
|
||||
"ThumbPrefix": "Thumb_",
|
||||
"ThumbSize": 512,
|
||||
"ThumbQuality": 72,
|
||||
"MaxFileSize": 41943040
|
||||
},
|
||||
"MessageConfiguration": {
|
||||
"MailConfigurations": {
|
||||
"gmail": {
|
||||
"Title": "SaherElm Dashboard",
|
||||
"Host": "smtp.gmail.com",
|
||||
"Port": 587,
|
||||
"EnableSsl": true,
|
||||
"Username": "saherelm@gmail.com",
|
||||
"Password": "vzuz gtrk tndb ctbc"
|
||||
}
|
||||
},
|
||||
"SmsConfigurations": {
|
||||
"yoursms": {
|
||||
"ServiceUrl": "http://sms.yourprovider.ir",
|
||||
"Username": "user",
|
||||
"Password": "psw",
|
||||
"LineNumber": "linenumber",
|
||||
"UserApiKey": "",
|
||||
"SecretKey": ""
|
||||
}
|
||||
}
|
||||
},
|
||||
"DbSeeder": {
|
||||
"UpdateExists": false,
|
||||
"Clients": [
|
||||
{
|
||||
"ClientId": "xSaherElmAPIClient",
|
||||
"ClientName": "Web Client of xMabsut API",
|
||||
"ClientSecrets": [
|
||||
{
|
||||
"Description": null,
|
||||
"Value": "NKaAKXeE9Ws+VVGGHsmM9DUO84cla4+hvx8swP1uuEg=",
|
||||
"Expiration": null,
|
||||
"Type": "SharedSecret"
|
||||
}
|
||||
],
|
||||
"Enabled": true,
|
||||
"RedirectUris": ["https://localhost:5001/signin-oidc"],
|
||||
"AllowedGrantTypes": [
|
||||
"hybrid",
|
||||
"password",
|
||||
"client_credentials"
|
||||
],
|
||||
"AllowedScopes": [
|
||||
"IdentityServerApi",
|
||||
"openid",
|
||||
"profile",
|
||||
"XAPI.read",
|
||||
"XAPI.write",
|
||||
"XAPI.admin",
|
||||
"manage",
|
||||
"offline_access"
|
||||
],
|
||||
"AllowedCorsOrigins": [
|
||||
"http://saherelm.ir",
|
||||
"admin",
|
||||
"responsible_manager",
|
||||
"journalist",
|
||||
"chief_clerk",
|
||||
"chief_clerk_assistant",
|
||||
"actuary",
|
||||
"actuary_assistant",
|
||||
"reporter",
|
||||
"reporter_assistant",
|
||||
"agent",
|
||||
"user"
|
||||
]
|
||||
},
|
||||
"Profile": {
|
||||
"ContainsEmail": false,
|
||||
"ContainsPhoneNumber": false,
|
||||
"ContainsRoles": true,
|
||||
"ContainsLastLogin": false,
|
||||
"ContainsDateOfBirth": false,
|
||||
"ContainsCreationDate": true
|
||||
}
|
||||
},
|
||||
"IdentityMessages": [
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "user_invite_msg",
|
||||
"TranslatedValue": "شما دعوت شده اید تا در سامانه ثبت نام کنید"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "user_invite_msg",
|
||||
"TranslatedValue": "You are Invited to Register at Dashboard"
|
||||
},
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "registration_approve_msg",
|
||||
"TranslatedValue": "شما باید حساب کاربری خود را با ورود به پیوند زیر فعال کنید"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "registration_approve_msg",
|
||||
"TranslatedValue": "you must activate your account by going to this link"
|
||||
},
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "registered_msg",
|
||||
"TranslatedValue": "ثبت نام شما در سامانه با موفقیت پایان یافت"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "registered_msg",
|
||||
"TranslatedValue": "you successfully registered at Dashboard"
|
||||
},
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "verification_code_msg",
|
||||
"TranslatedValue": "کد اعتبار سنجی شما در سامانه"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "verification_code_msg",
|
||||
"TranslatedValue": "Your Verification Code at Dashboard"
|
||||
},
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "change_password_msg",
|
||||
"TranslatedValue": "برای تغییر کلمه عبور پیوند زیر را دنبال کنید"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "change_password_msg",
|
||||
"TranslatedValue": "for change password please follow this link"
|
||||
},
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "password_changed_msg",
|
||||
"TranslatedValue": "کلمه عبور شما در سامانه تغییر یافت"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "password_changed_msg",
|
||||
"TranslatedValue": "your password at Dashboard changed"
|
||||
},
|
||||
{
|
||||
"Language": "fa-IR",
|
||||
"ResourceTitle": "new_device_logged_in_msg",
|
||||
"TranslatedValue": "ابزار جدیدی با مشخصات ذیل در سامانه با حساب کاربری شما وارد شده است"
|
||||
},
|
||||
{
|
||||
"Language": "en-US",
|
||||
"ResourceTitle": "new_device_logged_in_msg",
|
||||
"TranslatedValue": "new device with following details loggedin with your account in Dashboard"
|
||||
}
|
||||
]
|
||||
},
|
||||
"IdentityResourceConfiguration": {
|
||||
"Authority": "https://172.18.0.151",
|
||||
"ApiName": "xSaherElmAPI",
|
||||
"ApiSecret": "s@H@1694056",
|
||||
"ClientId": "xSaherElmAPIClient",
|
||||
"ClientSecret": "s@H@1694056",
|
||||
"XPoweredValue": "SaherElmITCenter",
|
||||
"XRevisionSecretKey": "SaherElmITCenter@1694056"
|
||||
},
|
||||
"StorageConfiguration": {
|
||||
"Authority": "https://ids.saherelm.ir",
|
||||
"IdentityAuthority": "https://ids.saherelm.ir",
|
||||
"Storage": "Storage",
|
||||
"Temp": "Temp",
|
||||
"Thumb": "Thumb",
|
||||
"Uploads": "Uploads",
|
||||
"Widgets": "Widgets",
|
||||
"Image": "Image",
|
||||
"Audio": "Audio",
|
||||
"Video": "Video",
|
||||
"Document": "Document",
|
||||
"FilePrefix": "xSaherElm_",
|
||||
"ThumbPrefix": "Thumb_",
|
||||
"ThumbSize": 512,
|
||||
"ThumbQuality": 72,
|
||||
"MaxFileSize": 41943040
|
||||
},
|
||||
"MessageConfiguration": {
|
||||
"MailConfigurations": {
|
||||
"gmail": {
|
||||
"Title": "SaherElm Dashboard",
|
||||
"Host": "smtp.gmail.com",
|
||||
"Port": 587,
|
||||
"EnableSsl": true,
|
||||
"Username": "saherelm@gmail.com",
|
||||
"Password": "vzuz gtrk tndb ctbc"
|
||||
}
|
||||
},
|
||||
"SmsConfigurations": {
|
||||
"yoursms": {
|
||||
"ServiceUrl": "http://sms.yourprovider.ir",
|
||||
"Username": "user",
|
||||
"Password": "psw",
|
||||
"LineNumber": "linenumber",
|
||||
"UserApiKey": "",
|
||||
"SecretKey": ""
|
||||
}
|
||||
}
|
||||
},
|
||||
"DbSeeder": {
|
||||
"UpdateExists": false,
|
||||
"Clients": [
|
||||
{
|
||||
"ClientId": "xSaherElmAPIClient",
|
||||
"ClientName": "Web Client of xMabsut API",
|
||||
"ClientSecrets": [
|
||||
{
|
||||
"Description": null,
|
||||
"Value": "NKaAKXeE9Ws+VVGGHsmM9DUO84cla4+hvx8swP1uuEg=",
|
||||
"Expiration": null,
|
||||
"Type": "SharedSecret"
|
||||
}
|
||||
],
|
||||
"Enabled": true,
|
||||
"RedirectUris": [
|
||||
"https://localhost:5001/signin-oidc"
|
||||
],
|
||||
"AllowedGrantTypes": [
|
||||
"hybrid",
|
||||
"password",
|
||||
"client_credentials"
|
||||
],
|
||||
"AllowedScopes": [
|
||||
"IdentityServerApi",
|
||||
"openid",
|
||||
"profile",
|
||||
"XAPI.read",
|
||||
"XAPI.write",
|
||||
"XAPI.admin",
|
||||
"manage",
|
||||
"offline_access"
|
||||
],
|
||||
"AllowedCorsOrigins": [
|
||||
"http://saherelm.ir",
|
||||
"https://saherelm.ir",
|
||||
"http://saherelmhub.ir",
|
||||
"https://saherelmhub.ir"
|
||||
],
|
||||
"AllowOfflineAccess": true,
|
||||
"RefreshTokenUsage": 1,
|
||||
"AccessTokenType": 1,
|
||||
"RefreshTokenExpiration": 0,
|
||||
"AbsoluteRefreshTokenLifetime": 2592000,
|
||||
"SlidingRefreshTokenLifetime": 1296000,
|
||||
"UpdateAccessTokenClaimsOnRefresh": true,
|
||||
"IdentityTokenLifetime": 300,
|
||||
"AccessTokenLifetime": 3600,
|
||||
"AuthorizationCodeLifetime": 300,
|
||||
"DeviceCodeLifetime": 300
|
||||
}
|
||||
],
|
||||
"IdentityResources": ["openid", "profile", "email", "role"],
|
||||
"ApiResources": [
|
||||
{
|
||||
"Name": "IdentityServerApi"
|
||||
},
|
||||
{
|
||||
"Name": "xSaherElmAPI",
|
||||
"DisplayName": "xSaherElm API",
|
||||
"Description": "Protected by IdentityServer API Access",
|
||||
"ApiSecrets": [
|
||||
{
|
||||
"Description": null,
|
||||
"Value": "NKaAKXeE9Ws+VVGGHsmM9DUO84cla4+hvx8swP1uuEg=",
|
||||
"Expiration": null,
|
||||
"Type": "SharedSecret"
|
||||
}
|
||||
],
|
||||
"Enabled": true,
|
||||
"Scopes": [
|
||||
"openid",
|
||||
"profile",
|
||||
"XAPI.read",
|
||||
"XAPI.write",
|
||||
"XAPI.admin",
|
||||
"manage"
|
||||
],
|
||||
"UserClaims": [
|
||||
"name",
|
||||
"role",
|
||||
"unique_name",
|
||||
"gender",
|
||||
"birthdate",
|
||||
"picture",
|
||||
"email",
|
||||
"phone_number",
|
||||
"email_verified",
|
||||
"phone_number_verified",
|
||||
"is_enabled",
|
||||
"is_banned",
|
||||
"creation_date",
|
||||
"last_login",
|
||||
"given_name",
|
||||
"family_name"
|
||||
]
|
||||
}
|
||||
],
|
||||
"ApiScopes": [
|
||||
{
|
||||
"Name": "IdentityServerApi"
|
||||
},
|
||||
{
|
||||
"Name": "xSaherElmAPI"
|
||||
},
|
||||
{
|
||||
"Name": "XAPI.read",
|
||||
"DisplayName": "Read Access for XAPI"
|
||||
},
|
||||
{
|
||||
"Name": "XAPI.write",
|
||||
"DisplayName": "Write Access for XAPI"
|
||||
},
|
||||
{
|
||||
"Name": "XAPI.admin",
|
||||
"DisplayName": "Admin Access for XAPI"
|
||||
},
|
||||
{
|
||||
"Name": "manage",
|
||||
"DisplayName": "Admin Access for All APIs"
|
||||
}
|
||||
],
|
||||
"Users": [
|
||||
{
|
||||
"Id": "b5713f9f-34f4-49b2-9680-b71e2b2de969",
|
||||
"FirstName": "Hadi",
|
||||
"LastName": "Khazaee Asl",
|
||||
"UserName": "admin",
|
||||
"Email": "hadi_khazaee_asl@yahoo.com",
|
||||
"EmailConfirmed": true,
|
||||
"PhoneNumber": "+989121694056",
|
||||
"PhoneNumberConfirmed": true,
|
||||
"Password": "s@H@1694056",
|
||||
"Role": "admin",
|
||||
"DateOfBirth": "1982-09-17 20:30:00.0000000",
|
||||
"IsEnable": true
|
||||
},
|
||||
{
|
||||
"Id": "83b09f5e-edd2-4e9a-8c5f-c4c129ee9d52",
|
||||
"FirstName": "Hadi",
|
||||
"LastName": "Khazaee Asl",
|
||||
"UserName": "agent",
|
||||
"Email": "hadi.khazaee.asl@gmail.com",
|
||||
"EmailConfirmed": true,
|
||||
"PhoneNumber": "+989101879789",
|
||||
"PhoneNumberConfirmed": true,
|
||||
"Password": "a@A@1694056",
|
||||
"Role": "agent",
|
||||
"DateOfBirth": "1982-09-17 20:30:00.0000000",
|
||||
"IsEnable": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
"AllowOfflineAccess": true,
|
||||
"RefreshTokenUsage": 1,
|
||||
"AccessTokenType": 1,
|
||||
"RefreshTokenExpiration": 0,
|
||||
"AbsoluteRefreshTokenLifetime": 2592000,
|
||||
"SlidingRefreshTokenLifetime": 1296000,
|
||||
"UpdateAccessTokenClaimsOnRefresh": true,
|
||||
"IdentityTokenLifetime": 300,
|
||||
"AccessTokenLifetime": 3600,
|
||||
"AuthorizationCodeLifetime": 300,
|
||||
"DeviceCodeLifetime": 300
|
||||
}
|
||||
],
|
||||
"IdentityResources": [
|
||||
"openid",
|
||||
"profile",
|
||||
"email",
|
||||
"role"
|
||||
],
|
||||
"ApiResources": [
|
||||
{
|
||||
"Name": "IdentityServerApi"
|
||||
},
|
||||
{
|
||||
"Name": "xSaherElmAPI",
|
||||
"DisplayName": "xSaherElm API",
|
||||
"Description": "Protected by IdentityServer API Access",
|
||||
"ApiSecrets": [
|
||||
{
|
||||
"Description": null,
|
||||
"Value": "NKaAKXeE9Ws+VVGGHsmM9DUO84cla4+hvx8swP1uuEg=",
|
||||
"Expiration": null,
|
||||
"Type": "SharedSecret"
|
||||
}
|
||||
],
|
||||
"Enabled": true,
|
||||
"Scopes": [
|
||||
"openid",
|
||||
"profile",
|
||||
"XAPI.read",
|
||||
"XAPI.write",
|
||||
"XAPI.admin",
|
||||
"manage"
|
||||
],
|
||||
"UserClaims": [
|
||||
"name",
|
||||
"role",
|
||||
"unique_name",
|
||||
"gender",
|
||||
"birthdate",
|
||||
"picture",
|
||||
"email",
|
||||
"phone_number",
|
||||
"email_verified",
|
||||
"phone_number_verified",
|
||||
"is_enabled",
|
||||
"is_banned",
|
||||
"creation_date",
|
||||
"last_login",
|
||||
"given_name",
|
||||
"family_name"
|
||||
]
|
||||
}
|
||||
],
|
||||
"ApiScopes": [
|
||||
{
|
||||
"Name": "IdentityServerApi"
|
||||
},
|
||||
{
|
||||
"Name": "xSaherElmAPI"
|
||||
},
|
||||
{
|
||||
"Name": "XAPI.read",
|
||||
"DisplayName": "Read Access for XAPI"
|
||||
},
|
||||
{
|
||||
"Name": "XAPI.write",
|
||||
"DisplayName": "Write Access for XAPI"
|
||||
},
|
||||
{
|
||||
"Name": "XAPI.admin",
|
||||
"DisplayName": "Admin Access for XAPI"
|
||||
},
|
||||
{
|
||||
"Name": "manage",
|
||||
"DisplayName": "Admin Access for All APIs"
|
||||
}
|
||||
],
|
||||
"Users": [
|
||||
{
|
||||
"Id": "b5713f9f-34f4-49b2-9680-b71e2b2de969",
|
||||
"FirstName": "Hadi",
|
||||
"LastName": "Khazaee Asl",
|
||||
"UserName": "admin",
|
||||
"Email": "hadi_khazaee_asl@yahoo.com",
|
||||
"EmailConfirmed": true,
|
||||
"PhoneNumber": "+989121694056",
|
||||
"PhoneNumberConfirmed": true,
|
||||
"Password": "s@H@1694056",
|
||||
"Role": "admin",
|
||||
"DateOfBirth": "1982-09-17 20:30:00.0000000",
|
||||
"IsEnable": true
|
||||
},
|
||||
{
|
||||
"Id": "83b09f5e-edd2-4e9a-8c5f-c4c129ee9d52",
|
||||
"FirstName": "Hadi",
|
||||
"LastName": "Khazaee Asl",
|
||||
"UserName": "agent",
|
||||
"Email": "hadi.khazaee.asl@gmail.com",
|
||||
"EmailConfirmed": true,
|
||||
"PhoneNumber": "+989101879789",
|
||||
"PhoneNumberConfirmed": true,
|
||||
"Password": "a@A@1694056",
|
||||
"Role": "agent",
|
||||
"DateOfBirth": "1982-09-17 20:30:00.0000000",
|
||||
"IsEnable": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"LoggingServiceConfiguration": {
|
||||
"Enabled": true,
|
||||
"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
@@ -1,4 +1,5 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<!-- Runtime Definitions -->
|
||||
<PropertyGroup>
|
||||
<Version>1.0.0</Version>
|
||||
@@ -23,18 +24,16 @@
|
||||
|
||||
<!-- Icon Handling -->
|
||||
<ItemGroup>
|
||||
<None Include="../../Resources/Images/favicon.png" Link="icon.png" Pack="true"
|
||||
PackagePath="\icon.png" />
|
||||
<None Include="../../Resources/Images/favicon.png" Link="icon.png" Pack="true" PackagePath="\icon.png" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Local Dependencies -->
|
||||
<ItemGroup>
|
||||
<!-- <PackageReference Include="xDashboard.xMessageService" Version="1.0.0" />
|
||||
<PackageReference Include="xDashboard.xStorageService" Version="1.0.0" /> -->
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Project Dependencies -->
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Modules\xLoggingService\xLoggingService.csproj" />
|
||||
<ProjectReference Include="..\Modules\xIdentityHelper\xIdentityHelper.csproj" />
|
||||
<ProjectReference Include="..\Modules\xMessageService\xMessageService.csproj" />
|
||||
<ProjectReference Include="..\Modules\xStorageService\xStorageService.csproj" />
|
||||
@@ -53,8 +52,7 @@
|
||||
<PackageReference Include="IdentityModel.AspNetCore.OAuth2Introspection" Version="5.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.12" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.2" />
|
||||
<PackageReference Include="IdentityModel.AspNetCore.AccessTokenValidation"
|
||||
Version="1.0.0-preview.3" />
|
||||
<PackageReference Include="IdentityModel.AspNetCore.AccessTokenValidation" Version="1.0.0-preview.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Ef Core -->
|
||||
@@ -84,4 +82,5 @@
|
||||
<Target Name="CreateRequiredFolder" AfterTargets="AfterPublish">
|
||||
<MakeDir Directories="$(PublishDir)wwwroot" Condition="!Exists('$(PublishDir)wwwroot')" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
Reference in New Issue
Block a user