Skip to content

Commit

Permalink
Merge pull request #83 from Ali-YousefiTelori/develop
Browse files Browse the repository at this point in the history
break for auth
  • Loading branch information
Ali-YousefiTelori authored Nov 26, 2023
2 parents f942f88 + 4048122 commit f6b28b5
Show file tree
Hide file tree
Showing 31 changed files with 425 additions and 304 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

namespace EasyMicroservices.Cores.AspCore.Tests
{
public class AuthorizationRolePermissionsTests : BasicTests
public abstract class AuthorizationRolePermissionsTests : BasicTests
{
public override int AppPort => 4566;
public AuthorizationRolePermissionsTests() : base()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace EasyMicroservices.Cores.AspCore.Tests
{
public class AuthorizationTests : BasicTests
public abstract class AuthorizationTests : BasicTests
{
public override int AppPort => 4565;
public AuthorizationTests() : base()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
using EasyMicroservices.Cores.Database.Managers;
using EasyMicroservices.Cores.Tests.Contracts.Common;
using EasyMicroservices.Cores.Tests.Laboratories;
using EasyMicroservices.Cores.Tests.Fixtures;
using EasyMicroservices.ServiceContracts;
using Newtonsoft.Json;

namespace EasyMicroservices.Cores.AspCore.Tests
{
public class BasicTests : WhiteLabelLaboratoryTest
public abstract class BasicTests : WhiteLabelLaboratoryFixture
{
public BasicTests()
{
Expand All @@ -21,7 +21,6 @@ protected virtual void InitializeTestHost(bool isUseAuthorization, Action<IServi
{
try
{
await OnInitialize();
await Startup.Run(AppPort, serviceCollection, null);
}
catch (Exception ex)
Expand Down
8 changes: 3 additions & 5 deletions src/CSharp/EasyMicroservices.Cores.AspCore.Tests/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using EasyMicroservices.Cores.AspEntityFrameworkCoreApi;
using EasyMicroservices.Cores.AspCoreApi.Managers;
using EasyMicroservices.Cores.AspEntityFrameworkCoreApi;
using EasyMicroservices.Cores.Database.Interfaces;
using EasyMicroservices.Cores.Database.Managers;
using EasyMicroservices.Cores.Relational.EntityFrameworkCore.Intrerfaces;
Expand All @@ -21,10 +22,7 @@ public static async Task Main(string[] args)
app.Services.AddScoped<IEntityFrameworkCoreDatabaseBuilder>(serviceProvider => new DatabaseBuilder());
app.Services.AddSingleton<IUniqueIdentityManager, DefaultUniqueIdentityManager>((provider) =>
{
if (UnitOfWork.DefaultUniqueIdentity.HasValue())
return new DefaultUniqueIdentityManager(UnitOfWork.DefaultUniqueIdentity, UnitOfWork.MicroserviceId, microserviceName);
else
return new DefaultUniqueIdentityManager(UnitOfWork.MicroserviceId, microserviceName);
return new DefaultUniqueIdentityManager(WhiteLabelManager.CurrentWhiteLabel);
});
StartUpExtensions.AddWhiteLabel(microserviceName, "RootAddresses:WhiteLabel");
var build = await app.Build<MyTestContext>();
Expand Down
6 changes: 2 additions & 4 deletions src/CSharp/EasyMicroservices.Cores.AspCore.Tests/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using EasyMicroservices.Cores.AspCore.Tests.Controllers;
using EasyMicroservices.Cores.AspCoreApi.Interfaces;
using EasyMicroservices.Cores.AspCoreApi.Managers;
using EasyMicroservices.Cores.AspEntityFrameworkCoreApi;
using EasyMicroservices.Cores.AspEntityFrameworkCoreApi.Interfaces;
using EasyMicroservices.Cores.Database.Interfaces;
Expand All @@ -23,10 +24,7 @@ static WebApplicationBuilder CreateBuilder(long port)
app.Services.AddTransient<IEntityFrameworkCoreDatabaseBuilder, DatabaseBuilder>();
app.Services.AddSingleton<IUniqueIdentityManager, DefaultUniqueIdentityManager>((provider) =>
{
if (UnitOfWork.DefaultUniqueIdentity.HasValue())
return new DefaultUniqueIdentityManager(UnitOfWork.DefaultUniqueIdentity, UnitOfWork.MicroserviceId, microserviceName);
else
return new DefaultUniqueIdentityManager(UnitOfWork.MicroserviceId, microserviceName);
return new DefaultUniqueIdentityManager(WhiteLabelManager.CurrentWhiteLabel);
});
StartUpExtensions.AddWhiteLabelRoute(microserviceName, $"http://localhost:6041");
app.Services.AddControllers().AddApplicationPart(typeof(UserController).Assembly);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using EasyMicroservices.Cores.Interfaces;
using EasyMicroservices.ServiceContracts;
using EasyMicroservices.Utilities.Collections.Generic;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
Expand All @@ -26,9 +27,14 @@ public class AspCoreAuthorization : IAuthorization
/// </summary>
public AspCoreAuthorization(IBaseUnitOfWork baseUnitOfWork)
{
BaseUnitOfWork = baseUnitOfWork;
UniqueIdentityManager = baseUnitOfWork.GetUniqueIdentityManager();
}

/// <summary>
///
/// </summary>
public IBaseUnitOfWork BaseUnitOfWork { get; }
/// <summary>
///
/// </summary>
Expand All @@ -37,7 +43,6 @@ public AspCoreAuthorization(IBaseUnitOfWork baseUnitOfWork)
///
/// </summary>
public static string AuthenticationRouteAddress { get; set; }

/// <summary>
///
/// </summary>
Expand All @@ -46,6 +51,15 @@ public AspCoreAuthorization(IBaseUnitOfWork baseUnitOfWork)
/// <exception cref="NotImplementedException"></exception>
public async Task<MessageContract> CheckIsAuthorized(HttpContext httpContext)
{
try
{
var result = await httpContext.AuthenticateAsync("Bearer");
await httpContext.SignInAsync("Bearer", result.Principal);
}
catch (Exception exxx)
{
var qq = exxx;
}
var hasPermission = await HasPermission(httpContext);
if (!hasPermission.IsSuccess)
return hasPermission.ToContract();
Expand All @@ -54,14 +68,19 @@ public async Task<MessageContract> CheckIsAuthorized(HttpContext httpContext)
return true;
}

async Task<string> GetMicroserviceName()
{
return (await BaseUnitOfWork.InitializeWhiteLabel()).MicroserviceName;
}

static ConcurrentDictionary<string, ICollection<ServicePermissionContract>> CachedPermissions { get; set; } = new();
static readonly ConcurrentTreeDictionary TreeDictionary = new ConcurrentTreeDictionary();
async Task<MessageContract> FetchData(string roleName)
{
var servicePermissionClient = new Authentications.GeneratedServices.ServicePermissionClient(AuthenticationRouteAddress, new System.Net.Http.HttpClient());
var permissionsResult = await servicePermissionClient.GetAllPermissionsByAsync(new Authentications.GeneratedServices.ServicePermissionRequestContract()
{
MicroserviceName = UniqueIdentityManager.MicroserviceName,
MicroserviceName = await GetMicroserviceName(),
RoleName = roleName
});
if (permissionsResult.IsSuccess)
Expand Down Expand Up @@ -105,7 +124,8 @@ async Task<MessageContract<bool>> HasPermission(HttpContext httpContext)
return fetchDataResult.ToContract<bool>();
}
}
return roleClaims.Any(role => TreeDictionary.TryGetValue(new object[] { role.Value, UniqueIdentityManager.MicroserviceName, controllerName, actionName }, out IList<object> permissions)
string microserviceName = await GetMicroserviceName();
return roleClaims.Any(role => TreeDictionary.TryGetValue([role.Value, microserviceName, controllerName, actionName], out IList<object> permissions)
&& permissions.LastOrDefault() is bool value && value);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<Platforms>AnyCPU;x64;x86</Platforms>
<Authors>EasyMicroservices</Authors>
<Version>0.0.0.53</Version>
<Version>0.0.0.54</Version>
<Description>asp core servces.</Description>
<Copyright>[email protected]</Copyright>
<PackageTags>core,cores,base,database,services,asp,aspnet</PackageTags>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<Platforms>AnyCPU;x64;x86</Platforms>
<Authors>EasyMicroservices</Authors>
<Version>0.0.0.53</Version>
<Version>0.0.0.54</Version>
<Description>asp core servces.</Description>
<Copyright>[email protected]</Copyright>
<PackageTags>core,cores,base,database,services,asp,aspnet,aspcore,efcore</PackageTags>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,60 @@
using EasyMicroservices.Cores.AspEntityFrameworkCoreApi;
using EasyMicroservices.Cores.Database.Managers;
using EasyMicroservices.Cores.Models;
using EasyMicroservices.ServiceContracts;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using WhiteLables.GeneratedServices;

namespace EasyMicroservices.Cores.AspCoreApi.Managers
{
internal class WhiteLabelManager
/// <summary>
///
/// </summary>
public class WhiteLabelManager
{
internal WhiteLabelManager(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}

private readonly IServiceProvider _serviceProvider;
/// <summary>
///
/// </summary>
public HttpClient HttpClient { get; set; } = new HttpClient();
/// <summary>
///
/// </summary>
public static bool IsInitialized
{
get
{
return _CurrentWhiteLabel is not null;
}
}

static WhiteLabelInfo _CurrentWhiteLabel;
/// <summary>
///
/// </summary>
public static WhiteLabelInfo CurrentWhiteLabel
{
get
{
if (_CurrentWhiteLabel is null)
throw new Exception("Whitelabel is not intialized!");
return _CurrentWhiteLabel;
}
private set
{
_CurrentWhiteLabel = value;
}
}

string GetDefaultUniqueIdentity(ICollection<WhiteLabelContract> whiteLables, long? parentId)
{
Expand All @@ -31,14 +66,25 @@ string GetDefaultUniqueIdentity(ICollection<WhiteLabelContract> whiteLables, lon
return $"{DefaultUniqueIdentityManager.GenerateUniqueIdentity(found.Id)}-{GetDefaultUniqueIdentity(whiteLables, found.Id)}".Trim('-');
}

public async Task Initialize(string microserviceName, string whiteLableRoute, params Type[] dbContextTypes)
/// <summary>
///
/// </summary>
/// <param name="microserviceName"></param>
/// <param name="whiteLableRoute"></param>
/// <param name="dbContextTypes"></param>
/// <returns></returns>
public async Task<WhiteLabelInfo> Initialize(string microserviceName, string whiteLableRoute, params Type[] dbContextTypes)
{
if (IsInitialized)
return CurrentWhiteLabel;
microserviceName.ThrowIfNullOrEmpty(nameof(microserviceName));
microserviceName.ThrowIfNullOrEmpty(nameof(whiteLableRoute));
Console.WriteLine($"WhiteLabelManager Initialize! {microserviceName} {whiteLableRoute}");
if (dbContextTypes.IsEmpty())
return;
return CurrentWhiteLabel;
var whiteLabelClient = new WhiteLables.GeneratedServices.WhiteLabelClient(whiteLableRoute, HttpClient);
var whiteLabels = await whiteLabelClient.GetAllAsync().ConfigureAwait(false);
UnitOfWork.DefaultUniqueIdentity = GetDefaultUniqueIdentity(whiteLabels.Result, null);
var whiteLabels = await whiteLabelClient.GetAllAsync().AsCheckedResult(x => x.Result).ConfigureAwait(false);
var defaultUniqueIdentity = GetDefaultUniqueIdentity(whiteLabels, null);

var microserviceClient = new WhiteLables.GeneratedServices.MicroserviceClient(whiteLableRoute, HttpClient);
var microservices = await microserviceClient.GetAllAsync().ConfigureAwait(false);
Expand All @@ -54,8 +100,13 @@ public async Task Initialize(string microserviceName, string whiteLableRoute, pa
var addMicroservice = await microserviceClient.AddAsync(foundMicroservice).ConfigureAwait(false);
foundMicroservice.Id = addMicroservice.Result;
}
UnitOfWork.MicroserviceId = foundMicroservice.Id;
UnitOfWork.MicroserviceName = microserviceName;

CurrentWhiteLabel = new WhiteLabelInfo()
{
MicroserviceId = foundMicroservice.Id,
MicroserviceName = microserviceName,
StartUniqueIdentity = defaultUniqueIdentity
};
var uniqueIdentityManager = new UnitOfWork(_serviceProvider).GetUniqueIdentityManager() as DefaultUniqueIdentityManager;

var microserviceContextTableClient = new WhiteLables.GeneratedServices.MicroserviceContextTableClient(whiteLableRoute, HttpClient);
Expand Down Expand Up @@ -105,6 +156,7 @@ public async Task Initialize(string microserviceName, string whiteLableRoute, pa
}
}
}
return CurrentWhiteLabel;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using EasyMicroservices.Cores.AspCoreApi.Authorizations;
using EasyMicroservices.Cores.AspCoreApi.Managers;
using EasyMicroservices.Cores.AspEntityFrameworkCoreApi.Interfaces;
using EasyMicroservices.Cores.AspEntityFrameworkCoreApi.Middlewares;
using EasyMicroservices.Cores.Database.Interfaces;
Expand All @@ -7,6 +8,7 @@
using EasyMicroservices.Cores.Relational.EntityFrameworkCore;
using EasyMicroservices.Cores.Relational.EntityFrameworkCore.Builders;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Any;
Expand Down Expand Up @@ -65,10 +67,7 @@ public static IServiceCollection Builder<TContext>(this IServiceCollection servi
services.AddScoped<IBaseUnitOfWork, UnitOfWork>();
services.AddSingleton<IUniqueIdentityManager, DefaultUniqueIdentityManager>((provider) =>
{
if (UnitOfWork.DefaultUniqueIdentity.HasValue())
return new DefaultUniqueIdentityManager(UnitOfWork.DefaultUniqueIdentity, UnitOfWork.MicroserviceId, MicroserviceName);
else
return new DefaultUniqueIdentityManager(UnitOfWork.MicroserviceId, MicroserviceName);
return new DefaultUniqueIdentityManager(WhiteLabelManager.CurrentWhiteLabel);
});
services.AddScoped(service => new UnitOfWork(service).GetMapper());
services.AddTransient<RelationalCoreContext>(serviceProvider => serviceProvider.GetService<TContext>());
Expand All @@ -79,6 +78,15 @@ public static IServiceCollection Builder<TContext>(this IServiceCollection servi
return services;
}

//static string GetUniqueIdentityFromHttpContext(HttpContext httpContext)
//{
// httpContext.ThrowIfNull(nameof(httpContext));
// var uniqueIdentity = httpContext.User.FindFirst(nameof(IUniqueIdentitySchema.UniqueIdentity));
// if (uniqueIdentity == null || uniqueIdentity.Value.IsNullOrEmpty())
// return UnitOfWork.DefaultUniqueIdentity;
// return uniqueIdentity.Value;
//}

/// <summary>
///
/// </summary>
Expand Down Expand Up @@ -147,7 +155,7 @@ public static async Task Build<TContext>(this IApplicationBuilder app)
if (WhiteLabelRoute.HasValue() || WhiteLabelConfigName.HasValue())
{
using var uow = scope.ServiceProvider.GetRequiredService<IUnitOfWork>() as UnitOfWork;
await uow.Initialize(MicroserviceName, config.GetValue<string>(WhiteLabelConfigName), typeof(TContext)).ConfigureAwait(false);
await uow.InitializeWhiteLabel(MicroserviceName, config.GetValue<string>(WhiteLabelConfigName), typeof(TContext)).ConfigureAwait(false);
}
if (AuthenticationConfigName.HasValue())
AspCoreAuthorization.AuthenticationRouteAddress = config.GetValue<string>(AuthenticationConfigName);
Expand Down Expand Up @@ -270,7 +278,7 @@ public static async Task<WebApplication> Use<TContext>(this WebApplication webAp
if (WhiteLabelRoute.HasValue() || WhiteLabelConfigName.HasValue())
{
var value = WhiteLabelRoute ?? config.GetValue<string>(WhiteLabelConfigName);
await uow.Initialize(MicroserviceName, WhiteLabelRoute ?? config.GetValue<string>(WhiteLabelConfigName), typeof(TContext)).ConfigureAwait(false);
await uow.InitializeWhiteLabel(MicroserviceName, WhiteLabelRoute ?? config.GetValue<string>(WhiteLabelConfigName), typeof(TContext)).ConfigureAwait(false);
}
if (AuthenticationConfigName.HasValue())
AspCoreAuthorization.AuthenticationRouteAddress = config.GetValue<string>(AuthenticationConfigName);
Expand Down
Loading

0 comments on commit f6b28b5

Please sign in to comment.