diff --git a/.github/workflows/identity-module.yml b/.github/workflows/identity-module.yml index c863eee9..a3960937 100644 --- a/.github/workflows/identity-module.yml +++ b/.github/workflows/identity-module.yml @@ -16,13 +16,13 @@ jobs: - name: Set up .NET Core uses: actions/setup-dotnet@v2 with: - dotnet-version: 8.0.x + dotnet-version: 9.0.x - name: Install dependencies - run: dotnet restore 'AspNetCore v8.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.csproj' + run: dotnet restore 'AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.csproj' - name: Build the NuGet package - run: dotnet pack 'AspNetCore v8.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.csproj' --configuration Release --output ${{env.DOTNET_ROOT}}\Package + run: dotnet pack 'AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.csproj' --configuration Release --output ${{env.DOTNET_ROOT}}\Package - name: Publish NuGet Package Calabonga.Microservice.Module run: dotnet nuget push ${{env.DOTNET_ROOT}}\Package\*.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate diff --git a/.github/workflows/module.yml b/.github/workflows/module.yml index 5db1451d..e41df35c 100644 --- a/.github/workflows/module.yml +++ b/.github/workflows/module.yml @@ -16,13 +16,13 @@ jobs: - name: Set up .NET Core uses: actions/setup-dotnet@v2 with: - dotnet-version: 8.0.x + dotnet-version: 9.0.x - name: Install dependencies - run: dotnet restore 'AspNetCore v8.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.csproj' + run: dotnet restore 'AspNetCore v9.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.csproj' - name: Build the NuGet package - run: dotnet pack 'AspNetCore v8.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.csproj' --configuration Release --output ${{env.DOTNET_ROOT}}\Package + run: dotnet pack 'AspNetCore v9.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.csproj' --configuration Release --output ${{env.DOTNET_ROOT}}\Package - name: Publish NuGet Package run: dotnet nuget push ${{env.DOTNET_ROOT}}\Package\*.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Core/AppData.Common.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Core/AppData.Common.cs deleted file mode 100644 index d9aa740f..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Core/AppData.Common.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Calabonga.Microservice.IdentityModule.Core -{ - /// - /// Static data container - /// - public static partial class AppData - { - /// - /// Current service name - /// - public const string ServiceName = "IdentityModule"; - - /// - /// "SystemAdministrator" - /// - public const string SystemAdministratorRoleName = "Administrator"; - - /// - /// "BusinessOwner" - /// - public const string ManagerRoleName = "Manager"; - - /// - /// Roles - /// - public static IEnumerable Roles - { - get - { - yield return SystemAdministratorRoleName; - yield return ManagerRoleName; - } - } - - /// - /// IdentityServer4 path - /// - public const string AuthUrl = "/auth"; - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Core/AppData.Exceptions.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Core/AppData.Exceptions.cs deleted file mode 100644 index b1f593f3..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Core/AppData.Exceptions.cs +++ /dev/null @@ -1,61 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Core -{ - public static partial class AppData - { - /// - /// Exception messages - /// - public static class Exceptions - { - /// - /// "An exception was thrown" - /// - public static string ThrownException => "An exception was thrown"; - - /// - /// "Invalid cast exception" - /// - public static string TypeConverterException => "Invalid cast exception"; - - /// - /// "User not registered in the system" - /// - public static string UserNotFoundException => "User not registered in the system"; - - /// - /// "Object not found" - /// - public static string NotFoundException => "Object not found"; - - /// - /// "Unauthorized access denied" - /// - public static string UnauthorizedException => "Unauthorized access denied"; - - /// - /// "Argument null exception" - /// - public static string ArgumentNullException => "Argument null exception"; - - /// - /// "File already exists" - /// - public static string FileAlreadyExists => "File already exists"; - - /// - /// "Some errors occurred while checking the entity" - /// - public static string EntityValidationException => "Some errors occurred while checking the entity"; - - /// - /// "Invalid operation exception was thrown" - /// - public static string InvalidOperationException => "Invalid operation exception was thrown"; - - /// - /// "Argument out of range" - /// - public static string ArgumentOutOfRangeException => "Argument out of range"; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Core/AppData.Messages.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Core/AppData.Messages.cs deleted file mode 100644 index a06fde08..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Core/AppData.Messages.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Core -{ - public static partial class AppData - { - /// - /// Common messages - /// - public static class Messages - { - /// - /// "User successfully registered" - /// - public static string UserSuccessfullyRegistered => "User successfully registered"; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Core/Calabonga.Microservice.IdentityModule.Core.csproj b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Core/Calabonga.Microservice.IdentityModule.Core.csproj deleted file mode 100644 index cb631906..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Core/Calabonga.Microservice.IdentityModule.Core.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - - - netcoreapp3.1 - - - diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationDbContext.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationDbContext.cs deleted file mode 100644 index 83b19f26..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationDbContext.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Data.Base; -using Calabonga.Microservice.IdentityModule.Entities; -using Microsoft.EntityFrameworkCore; - -namespace Calabonga.Microservice.IdentityModule.Data -{ - /// - /// Database context for current application - /// - public class ApplicationDbContext : DbContextBase, IApplicationDbContext - { - public ApplicationDbContext(DbContextOptions options) - : base(options) { } - - #region System - - public DbSet Logs { get; set; } - - public DbSet Profiles { get; set; } - - /// - public DbSet Permissions { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationRole.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationRole.cs deleted file mode 100644 index 0f155d16..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationRole.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using Microsoft.AspNetCore.Identity; - -namespace Calabonga.Microservice.IdentityModule.Data -{ - /// - /// Application role - /// - public class ApplicationRole : IdentityRole - { - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationUser.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationUser.cs deleted file mode 100644 index dac4180d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationUser.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using Microsoft.AspNetCore.Identity; - -namespace Calabonga.Microservice.IdentityModule.Data -{ - /// - /// Default user for application. - /// Add profile data for application users by adding properties to the ApplicationUser class - /// - public class ApplicationUser : IdentityUser - { - /// - /// FirstName - /// - public string FirstName { get; set; } - - /// - /// LastName - /// - public string LastName { get; set; } - - /// - /// Profile identity - /// - public Guid? ApplicationUserProfileId { get; set; } - - /// - /// User Profile - /// - public virtual ApplicationUserProfile ApplicationUserProfile { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationUserProfile.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationUserProfile.cs deleted file mode 100644 index 3b6d451d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationUserProfile.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Collections.Generic; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace Calabonga.Microservice.IdentityModule.Data -{ - /// - /// Represent person with login information (ApplicationUser) - /// - public class ApplicationUserProfile: Auditable - { - /// - /// Account - /// - public virtual ApplicationUser ApplicationUser { get; set; } - - /// - /// Microservice permission for policy-based authorization - /// - public ICollection Permissions { get; set; } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationUserStore.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationUserStore.cs deleted file mode 100644 index 74986cf8..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ApplicationUserStore.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; - -namespace Calabonga.Microservice.IdentityModule.Data -{ - /// - /// Application store for user - /// - public class ApplicationUserStore : UserStore - { - public ApplicationUserStore(ApplicationDbContext context, IdentityErrorDescriber describer = null) - : base(context, describer) - { - - } - - /// - public override Task FindByIdAsync(string userId, CancellationToken cancellationToken = new CancellationToken()) - { - return Users - .Include(x => x.ApplicationUserProfile) - .ThenInclude(x => x.Permissions) - .FirstOrDefaultAsync(u => u.Id.ToString() == userId, cancellationToken: cancellationToken); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/Base/DbContextBase.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/Base/DbContextBase.cs deleted file mode 100644 index 9fc8b1d6..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/Base/DbContextBase.cs +++ /dev/null @@ -1,264 +0,0 @@ -using System; -using System.Linq; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -using Calabonga.EntityFrameworkCore.Entities.Base; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; - -namespace Calabonga.Microservice.IdentityModule.Data.Base -{ - /// - /// Base DbContext with predefined configuration - /// - public abstract class DbContextBase : IdentityDbContext - { - private const string DefaultUserName = "Anonymous"; - - protected DbContextBase(DbContextOptions options) : base(options) - { - LastSaveChangesResult = new SaveChangesResult(); - } - - public SaveChangesResult LastSaveChangesResult { get; } - - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - /// - /// Saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// The number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override int SaveChanges(bool acceptAllChangesOnSuccess) - { - try - { - DbSaveChanges(); - return base.SaveChanges(acceptAllChangesOnSuccess); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - public override int SaveChanges() - { - try - { - DbSaveChanges(); - return base.SaveChanges(); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - private void DbSaveChanges() - { - var createdEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added); - foreach (var entry in createdEntries) - { - if (!(entry.Entity is IAuditable)) - { - continue; - } - - var creationDate = DateTime.Now.ToUniversalTime(); - var userName = entry.Property("CreatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("CreatedBy").CurrentValue; - var updatedAt = entry.Property("UpdatedAt").CurrentValue; - var createdAt = entry.Property("CreatedAt").CurrentValue; - if (createdAt != null) - { - if (DateTime.Parse(createdAt.ToString()).Year > 1970) - { - entry.Property("CreatedAt").CurrentValue = ((DateTime)createdAt).ToUniversalTime(); - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - - if (updatedAt != null) - { - if (DateTime.Parse(updatedAt.ToString()).Year > 1970) - { - entry.Property("UpdatedAt").CurrentValue = ((DateTime)updatedAt).ToUniversalTime(); - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - - entry.Property("CreatedBy").CurrentValue = userName; - entry.Property("UpdatedBy").CurrentValue = userName; - - LastSaveChangesResult.AddMessage($"ChangeTracker has new entities: {entry.Entity.GetType()}"); - } - - var updatedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified); - foreach (var entry in updatedEntries) - { - if (entry.Entity is IAuditable) - { - var userName = entry.Property("UpdatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("UpdatedBy").CurrentValue; - entry.Property("UpdatedAt").CurrentValue = DateTime.Now.ToUniversalTime(); - entry.Property("UpdatedBy").CurrentValue = userName; - } - - LastSaveChangesResult.AddMessage($"ChangeTracker has modified entities: {entry.Entity.GetType()}"); - } - } - - /// - /// Configures the schema needed for the identity framework. - /// - /// - /// The builder being used to construct the model for this context. - /// - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - var applyGenericMethod = typeof(ModelBuilder).GetMethods(BindingFlags.Instance | BindingFlags.Public).First(x => x.Name == "ApplyConfiguration"); - foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters)) - { - foreach (var item in type.GetInterfaces()) - { - if (!item.IsConstructedGenericType || item.GetGenericTypeDefinition() != typeof(IEntityTypeConfiguration<>)) - { - continue; - } - - var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(item.GenericTypeArguments[0]); - applyConcreteMethod.Invoke(builder, new[] { Activator.CreateInstance(type) }); - break; - } - } - - builder.EnableAutoHistory(2048); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/Calabonga.Microservice.IdentityModule.Data.csproj b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/Calabonga.Microservice.IdentityModule.Data.csproj deleted file mode 100644 index 59d98c48..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/Calabonga.Microservice.IdentityModule.Data.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - - netcoreapp3.1 - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/DatabaseInitialization/DatabaseInitializer.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/DatabaseInitialization/DatabaseInitializer.cs deleted file mode 100644 index 0a16619b..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/DatabaseInitialization/DatabaseInitializer.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Calabonga.Microservice.IdentityModule.Core; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.IdentityModule.Data.DatabaseInitialization -{ - /// - /// Database Initializer - /// - public static class DatabaseInitializer - { - public static async void Seed(IServiceProvider serviceProvider) - { - using var scope = serviceProvider.CreateScope(); - await using var context = scope.ServiceProvider.GetService(); - - // Should be uncomment when using UseSqlServer() settings or any other provider. - // This is should not be used when UseInMemoryDatabase() - // context.Database.Migrate(); - - var roles = AppData.Roles.ToArray(); - - foreach (var role in roles) - { - var roleManager = scope.ServiceProvider.GetRequiredService>(); - if (!context.Roles.Any(r => r.Name == role)) - { - await roleManager.CreateAsync(new ApplicationRole { Name = role, NormalizedName = role.ToUpper() }); - } - } - - #region developer - - var developer1 = new ApplicationUser - { - Email = "microservice@yopmail.com", - NormalizedEmail = "MICROSERVICE@YOPMAIL.COM", - UserName = "microservice@yopmail.com", - FirstName = "Microservice", - LastName = "Administrator", - NormalizedUserName = "MICROSERVICE@YOPMAIL.COM", - PhoneNumber = "+79000000000", - EmailConfirmed = true, - PhoneNumberConfirmed = true, - SecurityStamp = Guid.NewGuid().ToString("D"), - ApplicationUserProfile = new ApplicationUserProfile - { - CreatedAt = DateTime.Now, - CreatedBy = "SEED", - Permissions = new List - { - new MicroservicePermission - { - CreatedAt = DateTime.Now, - CreatedBy = "SEED", - PolicyName = "Logs:UserRoles:View", - Description = "Access policy for Logs controller user view" - } - } - } - }; - - if (!context.Users.Any(u => u.UserName == developer1.UserName)) - { - var password = new PasswordHasher(); - var hashed = password.HashPassword(developer1, "123qwe!@#"); - developer1.PasswordHash = hashed; - var userStore = scope.ServiceProvider.GetService(); - var result = await userStore.CreateAsync(developer1); - if (!result.Succeeded) - { - throw new InvalidOperationException("Cannot create account"); - } - - var userManager = scope.ServiceProvider.GetService>(); - foreach (var role in roles) - { - var roleAdded = await userManager.AddToRoleAsync(developer1, role); - if (roleAdded.Succeeded) - { - await context.SaveChangesAsync(); - } - } - } - #endregion - - await context.SaveChangesAsync(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/IApplicaitonDbContext.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/IApplicaitonDbContext.cs deleted file mode 100644 index 4fc2f735..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/IApplicaitonDbContext.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.ChangeTracking; -using Microsoft.EntityFrameworkCore.Infrastructure; - -namespace Calabonga.Microservice.IdentityModule.Data -{ - /// - /// Abstraction for Database (EntityFramework) - /// - public interface IApplicationDbContext - { - #region System - - DbSet Logs { get; set; } - - DbSet Users { get; set; } - - DbSet Profiles { get; set; } - - DbSet Permissions { get; set; } - - DatabaseFacade Database { get; } - - ChangeTracker ChangeTracker { get; } - - DbSet Set() where TEntity : class; - - int SaveChanges(); - - #endregion - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/MicroservicePermission.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/MicroservicePermission.cs deleted file mode 100644 index ec2e42dc..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/MicroservicePermission.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace Calabonga.Microservice.IdentityModule.Data -{ - /// - /// User permission for microservice - /// - public class MicroservicePermission: Auditable - { - /// - /// Application User profile identifier - /// - public Guid ApplicationUserProfileId { get; set; } - - /// - /// Application User Profile - /// - public virtual ApplicationUserProfile ApplicationUserProfile { get; set; } - - /// - /// Authorize attribute policy name - /// - public string PolicyName { get; set; } - - /// - /// Description for current permission - /// - public string Description { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/ApplicationUserModelConfiguration.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/ApplicationUserModelConfiguration.cs deleted file mode 100644 index 753c6dcb..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/ApplicationUserModelConfiguration.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Calabonga.Microservice.IdentityModule.Data.ModelConfigurations -{ - /// - /// Entity Type Configuration for entity - /// - - public class ApplicationUserModelConfiguration : IEntityTypeConfiguration - { - - /// - /// Configures the entity of type . - /// - /// The builder to be used to configure the entity type. - public void Configure(EntityTypeBuilder builder) - { - builder.Property(x => x.LastName).HasMaxLength(128).IsRequired(); - builder.Property(x => x.FirstName).HasMaxLength(128).IsRequired(); - builder.Property(x => x.ApplicationUserProfileId).IsRequired(false); - - builder.HasOne(x => x.ApplicationUserProfile); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/ApplicationUserProfileModelConfiguration.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/ApplicationUserProfileModelConfiguration.cs deleted file mode 100644 index 8332a9a5..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/ApplicationUserProfileModelConfiguration.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Data.ModelConfigurations.Base; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Calabonga.Microservice.IdentityModule.Data.ModelConfigurations -{ - /// - /// Entity Type Configuration for entity - /// - - public class ApplicationUserProfileModelConfiguration : AuditableModelConfigurationBase - { - protected override void AddBuilder(EntityTypeBuilder builder) - { - builder.HasMany(x => x.Permissions); - - builder.HasOne(x => x.ApplicationUser) - .WithOne(x => x.ApplicationUserProfile) - .HasForeignKey(x => x.ApplicationUserProfileId); - } - - protected override string TableName() - { - return "ApplicationUserProfiles"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/Base/AuditableModelConfigurationBase.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/Base/AuditableModelConfigurationBase.cs deleted file mode 100644 index 3c78e4a9..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/Base/AuditableModelConfigurationBase.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Calabonga.Microservice.IdentityModule.Data.ModelConfigurations.Base -{ - /// - /// Audit-able Model Configuration base - /// - /// - public abstract class AuditableModelConfigurationBase : IEntityTypeConfiguration where T : Auditable - { - public void Configure(EntityTypeBuilder builder) - { - builder.ToTable(TableName()); - builder.HasKey(x => x.Id); - builder.Property(x => x.Id).IsRequired(); - - // audit - builder.Property(x => x.CreatedAt).IsRequired().HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)).IsRequired(); - builder.Property(x => x.CreatedBy).HasMaxLength(256).IsRequired(); - builder.Property(x => x.UpdatedAt).HasConversion(v => v.Value, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); - builder.Property(x => x.UpdatedBy).HasMaxLength(256); - - AddBuilder(builder); - } - - /// - /// Add custom properties for your entity - /// - /// - protected abstract void AddBuilder(EntityTypeBuilder builder); - - /// - /// Table name - /// - /// - protected abstract string TableName(); - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/Base/IdentityModelConfigurationBase.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/Base/IdentityModelConfigurationBase.cs deleted file mode 100644 index 203b24cb..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/Base/IdentityModelConfigurationBase.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Calabonga.EntityFrameworkCore.Entities.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Calabonga.Microservice.IdentityModule.Data.ModelConfigurations.Base -{ - /// - /// Audit-able Model Configuration base - /// - /// - public abstract class IdentityModelConfigurationBase : IEntityTypeConfiguration where T : Identity - { - public void Configure(EntityTypeBuilder builder) - { - builder.ToTable(TableName()); - builder.HasKey(x => x.Id); - builder.Property(x => x.Id).IsRequired(); - - AddBuilder(builder); - } - - /// - /// Add custom properties for your entity - /// - /// - protected abstract void AddBuilder(EntityTypeBuilder builder); - - /// - /// Table name - /// - /// - protected abstract string TableName(); - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/LogModelConfiguration.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/LogModelConfiguration.cs deleted file mode 100644 index eefdfe52..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/LogModelConfiguration.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using Calabonga.Microservice.IdentityModule.Data.ModelConfigurations.Base; -using Calabonga.Microservice.IdentityModule.Entities; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Calabonga.Microservice.IdentityModule.Data.ModelConfigurations -{ - /// - /// Entity Type Configuration for entity - /// - public class LogModelConfiguration: IdentityModelConfigurationBase - { - protected override void AddBuilder(EntityTypeBuilder builder) - { - builder.Property(x => x.Logger).HasMaxLength(255).IsRequired(); - builder.Property(x => x.Level).HasMaxLength(50).IsRequired(); - builder.Property(x => x.Message).HasMaxLength(4000).IsRequired(); - builder.Property(x => x.CreatedAt).HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)).IsRequired(); - builder.Property(x => x.ThreadId).HasMaxLength(255); - builder.Property(x => x.ExceptionMessage).HasMaxLength(2000); - } - - protected override string TableName() - { - return "Logs"; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/MicroservicePermissionModelConfiguration.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/MicroservicePermissionModelConfiguration.cs deleted file mode 100644 index a3d3e032..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/MicroservicePermissionModelConfiguration.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Data.ModelConfigurations.Base; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Calabonga.Microservice.IdentityModule.Data.ModelConfigurations -{ - /// - /// Entity Type Configuration for entity - /// - - public class MicroservicePermissionModelConfiguration : AuditableModelConfigurationBase - { - protected override void AddBuilder(EntityTypeBuilder builder) - { - builder.Property(x => x.PolicyName).HasMaxLength(64).IsRequired(); - builder.Property(x => x.Description).HasMaxLength(1024); - builder.Property(x => x.ApplicationUserProfileId).IsRequired(); - - builder.HasOne(x => x.ApplicationUserProfile).WithMany(x => x.Permissions); - } - - protected override string TableName() - { - return "MicroservicePermissions"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Models/Calabonga.Microservice.IdentityModule.Entities.csproj b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Models/Calabonga.Microservice.IdentityModule.Entities.csproj deleted file mode 100644 index f0c983a0..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Models/Calabonga.Microservice.IdentityModule.Entities.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - netcoreapp3.1 - - - - - - - - - - - diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Models/Log.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Models/Log.cs deleted file mode 100644 index c97abef1..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Models/Log.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace Calabonga.Microservice.IdentityModule.Entities -{ - /// - /// Log entity for demo purposes only - /// - public class Log: Identity - { - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } - - public string Level { get; set; } - - public string Message { get; set; } - - public string ThreadId { get; set; } - - public string ExceptionMessage { get; set; } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesAuthentication.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesAuthentication.cs deleted file mode 100644 index 4b2d245f..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesAuthentication.cs +++ /dev/null @@ -1,61 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Core; -using Calabonga.Microservice.IdentityModule.Data; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Services; -using IdentityServer4.AccessTokenValidation; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.IdentityModule.Web.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// Authentication path - /// - public static class ConfigureServicesAuthentication - { - /// - /// Configure Authentication & Authorization - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - var url = configuration.GetSection("IdentityServer").GetValue("Url"); - services.AddAuthentication(options => - { - options.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; - options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; - options.DefaultSignInScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; - options.DefaultSignOutScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; - }) - .AddIdentityServerAuthentication(options => - { - options.SupportedTokens = SupportedTokens.Jwt; - options.Authority = $"{url}{AppData.AuthUrl}"; - options.EnableCaching = true; - options.RequireHttpsMetadata = false; - }); - - services.AddIdentityServer(options => - { - options.Authentication.CookieSlidingExpiration = true; - options.IssuerUri = $"{url}{AppData.AuthUrl}"; - options.Events.RaiseErrorEvents = true; - options.Events.RaiseInformationEvents = true; - options.Events.RaiseFailureEvents = true; - options.Events.RaiseSuccessEvents = true; - }) - .AddInMemoryPersistedGrants() - .AddDeveloperSigningCredential() - .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources()) - .AddInMemoryApiResources(IdentityServerConfig.GetApiResources()) - .AddInMemoryClients(IdentityServerConfig.GetClients()) - .AddInMemoryApiScopes(IdentityServerConfig.GetAPiScopes()) - .AddAspNetIdentity() - .AddJwtBearerClientAuthentication() - .AddProfileService(); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesBase.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesBase.cs deleted file mode 100644 index f6ca437c..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesBase.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Data; -using Calabonga.Microservice.IdentityModule.Web.Extensions; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Settings; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.IdentityModule.Web.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesBase - { - /// - /// ConfigureServices Services - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - services - .AddIdentity() - .AddUserStore() - .AddEntityFrameworkStores() - .AddDefaultTokenProviders(); - - services.AddDbContextPool(config => - { - // UseInMemoryDatabase - This for demo purposes only! - // Should uninstall package "Microsoft.EntityFrameworkCore.InMemory" and install what you need. - // For example: "Microsoft.EntityFrameworkCore.SqlServer" - // uncomment line below to use UseSqlServer(). Don't forget setup connection string in appSettings.json - config.UseInMemoryDatabase("DEMO_PURPOSES_ONLY"); - // config.UseSqlServer(configuration.GetConnectionString(nameof(ApplicationDbContext))); - }); - - services.AddAutoMapper(typeof(Startup)); - - services.AddUnitOfWork(); - - services.AddMemoryCache(); - - services.AddRouting(options => options.LowercaseUrls = true); - - services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); - - services.Configure(options => - { - // Password settings. - options.Password.RequireDigit = false; - options.Password.RequireLowercase = false; - options.Password.RequireNonAlphanumeric = false; - options.Password.RequireUppercase = false; - options.Password.RequiredLength = 6; - options.Password.RequiredUniqueChars = 0; - - // Lockout settings. - options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); - options.Lockout.MaxFailedAccessAttempts = 10; - options.Lockout.AllowedForNewUsers = true; - - // User settings. - options.User.AllowedUserNameCharacters = null; - options.User.RequireUniqueEmail = true; - }); - - services.AddOptions(); - services.Configure(configuration.GetSection(nameof(CurrentAppSettings))); - services.Configure(options => options.UseRouteSlugify()); - services.AddLocalization(); - services.AddHttpContextAccessor(); - services.AddResponseCaching(); - services.AddAuthorization(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesControllers.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesControllers.cs deleted file mode 100644 index 8202217c..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesControllers.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.IdentityModule.Web.AppStart.ConfigureServices -{ - /// - /// Configure controllers - /// - public static class ConfigureServicesControllers - { - /// - /// Configure services - /// - /// - public static void ConfigureServices(IServiceCollection services) - { - services.AddControllers(); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesCors.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesCors.cs deleted file mode 100644 index 30f79846..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesCors.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.Linq; -using Calabonga.Microservices.Web.Core; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.IdentityModule.Web.AppStart.ConfigureServices -{ - /// - /// Cors configurations - /// - public class ConfigureServicesCors - { - /// - /// ConfigureServices - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - var origins = configuration.GetSection("Cors")?.GetSection("Origins")?.Value?.Split(','); - services.AddCors(options => - { - options.AddPolicy("CorsPolicy", builder => - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - if (origins != null && origins.Length > 0) - { - if (origins.Contains("*")) - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - builder.SetIsOriginAllowed(host => true); - builder.AllowCredentials(); - } - else - { - foreach (var origin in origins) - { - builder.WithOrigins(origin); - } - } - } - }); - }); - - services.UseMicroserviceAuthorizationPolicy(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesMediator.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesMediator.cs deleted file mode 100644 index e3e43995..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesMediator.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Extensions; -using Calabonga.Microservice.IdentityModule.Data; -using Calabonga.Microservice.IdentityModule.Web.Extensions; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Settings; -using Calabonga.Microservice.IdentityModule.Web.Mediator.Behaviors; -using Calabonga.UnitOfWork; -using MediatR; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.IdentityModule.Web.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesMediator - { - /// - /// ConfigureServices Services - /// - /// - public static void ConfigureServices(IServiceCollection services) - { - services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>)); - services.AddCommandAndQueries(typeof(Startup).Assembly); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesSwagger.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesSwagger.cs deleted file mode 100644 index 12c2b464..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesSwagger.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Calabonga.Microservice.IdentityModule.Web.AppStart.SwaggerFilters; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerUI; - -namespace Calabonga.Microservice.IdentityModule.Web.AppStart.ConfigureServices -{ - /// - /// Swagger configuration - /// - public static class ConfigureServicesSwagger - { - private const string AppTitle = "Microservice API (with IdentityServer4)"; - private static readonly string AppVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - private const string SwaggerConfig = "/swagger/v1/swagger.json"; - private const string SwaggerUrl = "api/manual"; - - /// - /// ConfigureServices Swagger services - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - services.AddSwaggerGen(options => - { - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = AppTitle, - Version = AppVersion, - Description = "Microservice API (with IdentityServer4) module API documentation. This template based on ASP.NET Core 3.1." - }); - options.ResolveConflictingActions(x => x.First()); - - var url = configuration.GetSection("IdentityServer").GetValue("Url"); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - Password = new OpenApiOAuthFlow - { - TokenUrl = new Uri($"{url}/auth/connect/token", UriKind.Absolute), - Scopes = new Dictionary - { - { "api1", "Default scope" } - } - } - } - }); - - options.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "oauth2" - }, - Scheme = "oauth2", - Name = "Bearer", - In = ParameterLocation.Header, - - }, - new List() - } - }); - - options.OperationFilter(); - }); - } - - /// - /// Set up some properties for swagger UI - /// - /// - public static void SwaggerSettings(SwaggerUIOptions settings) - { - settings.SwaggerEndpoint(SwaggerConfig, $"{AppTitle} v.{AppVersion}"); - settings.RoutePrefix = SwaggerUrl; - settings.DocumentTitle = "Microservice API"; - settings.DefaultModelExpandDepth(0); - settings.DefaultModelRendering(ModelRendering.Model); - settings.DefaultModelsExpandDepth(0); - settings.DocExpansion(DocExpansion.None); - settings.OAuthClientId("microservice1"); - settings.OAuthScopeSeparator(" "); - settings.OAuthClientSecret("secret"); - settings.DisplayRequestDuration(); - settings.OAuthAppName("Microservice API (with IdentityServer4) module API documentation"); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesValidators.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesValidators.cs deleted file mode 100644 index 2a873e78..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesValidators.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels; -using FluentValidation; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.IdentityModule.Web.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesValidators - { - /// - /// ConfigureServices Services - /// - /// - public static void ConfigureServices(IServiceCollection services) - { - services.AddValidatorsFromAssembly(typeof(Startup).Assembly); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/Configures/ConfigureCommon.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/Configures/ConfigureCommon.cs deleted file mode 100644 index 836317fc..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/Configures/ConfigureCommon.cs +++ /dev/null @@ -1,61 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Core; -using Calabonga.Microservice.IdentityModule.Web.AppStart.ConfigureServices; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Auth; -using Calabonga.Microservice.IdentityModule.Web.Middlewares; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.IdentityModule.Web.AppStart.Configures -{ - /// - /// Pipeline configuration - /// - public static class ConfigureCommon - { - /// - /// Configure pipeline - /// - /// - /// - /// - public static void Configure(IApplicationBuilder app, IWebHostEnvironment env, AutoMapper.IConfigurationProvider mapper) - { - if (env.IsDevelopment()) - { - mapper.AssertConfigurationIsValid(); - app.UseDeveloperExceptionPage(); - } - else - { - mapper.CompileMappings(); - } - - app.UseDefaultFiles(); - app.UseStaticFiles(new StaticFileOptions - { - OnPrepareResponse = ctx => - { - ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=600"); - } - }); - - app.UseResponseCaching(); - - app.UseETagger(); - - app.Map($"{AppData.AuthUrl}", authServer => { authServer.UseIdentityServer(); }); - - app.UseMiddleware(typeof(ErrorHandlingMiddleware)); - - app.UseSwaggerUI(ConfigureServicesSwagger.SwaggerSettings); - - app.UseSwagger(); - - // Singleton setup for User Identity - UserIdentity.Instance.Configure(app.ApplicationServices.GetService()); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/Configures/ConfigureEndpoints.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/Configures/ConfigureEndpoints.cs deleted file mode 100644 index 103bc489..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/Configures/ConfigureEndpoints.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.AspNetCore.Builder; - -namespace Calabonga.Microservice.IdentityModule.Web.AppStart.Configures -{ - /// - /// Configure pipeline - /// - public static class ConfigureEndpoints - { - /// - /// Configure Routing - /// - /// - public static void Configure(IApplicationBuilder app) - { - app.UseRouting(); - app.UseCors("CorsPolicy"); - app.UseAuthentication(); - app.UseAuthorization(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/IdentityServerConfig.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/IdentityServerConfig.cs deleted file mode 100644 index 5ab69ba6..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/IdentityServerConfig.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System.Collections.Generic; -using IdentityServer4; -using IdentityServer4.Models; - -namespace Calabonga.Microservice.IdentityModule.Web.AppStart -{ - /// - /// IdentityServer configuration - /// - public class IdentityServerConfig - { - /// - /// clients want to access resources (aka scopes) - /// - /// - public static IEnumerable GetClients() - { - // client credentials client - return new List - { - // resource owner password grant client - // you can create your own client - new Client - { - ClientId = "microservice1", - AllowAccessTokensViaBrowser = true, - IdentityTokenLifetime = 21600, - AuthorizationCodeLifetime = 21600, - AccessTokenLifetime = 21600, - AllowOfflineAccess = true, - RefreshTokenUsage = TokenUsage.ReUse, - RefreshTokenExpiration = TokenExpiration.Sliding, - SlidingRefreshTokenLifetime = 1296000, //in seconds = 15 days - AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, - RequireClientSecret = false, - AllowedScopes = { - IdentityServerConstants.StandardScopes.OpenId, - IdentityServerConstants.StandardScopes.Profile, - IdentityServerConstants.StandardScopes.Email, - IdentityServerConstants.StandardScopes.Address, - "api1" - } - } - }; - } - - /// - /// scopes define the resources in your system - /// - /// - public static IEnumerable GetIdentityResources() - { - return new List - { - new IdentityResources.OpenId(), - new IdentityResources.Email(), - new IdentityResources.Profile() - }; - } - - /// - /// IdentityServer4 API resources - /// - /// - public static IEnumerable GetApiResources() - { - return new List - { - new ApiResource("api1", "API Default") - }; - } - - public static IEnumerable GetAPiScopes() - { - yield return new ApiScope("api1"); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/MapperRegistration.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/MapperRegistration.cs deleted file mode 100644 index 08a17417..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/MapperRegistration.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Mappers.Base; - -namespace Calabonga.Microservice.IdentityModule.Web.AppStart -{ - /// - /// AutoMapper profiles registration - /// - public static class MapperRegistration - { - private static List GetProfiles() - { - return (from t in typeof(Startup).GetTypeInfo().Assembly.GetTypes() - where typeof(IAutoMapper).IsAssignableFrom(t) && !t.GetTypeInfo().IsAbstract - select t).ToList(); - } - - /// - /// Create and build mapper profiles - /// - /// - public static MapperConfiguration GetMapperConfiguration() - { - var profiles = GetProfiles(); - return new MapperConfiguration(cfg => - { - foreach (var item in profiles.Select(profile => (Profile)Activator.CreateInstance(profile))) - { - cfg.AddProfile(item); - } - }); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/SwaggerFilters/ApplySummariesOperationFilter.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/SwaggerFilters/ApplySummariesOperationFilter.cs deleted file mode 100644 index b4940b1b..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/AppStart/SwaggerFilters/ApplySummariesOperationFilter.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Calabonga.Microservice.IdentityModule.Web.AppStart.SwaggerFilters -{ - /// - /// Swagger Method Info Generator from summary for - /// - public class ApplySummariesOperationFilter : IOperationFilter - { - /// - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var controllerActionDescriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor; - if (controllerActionDescriptor == null) - { - return; - } - - var actionName = controllerActionDescriptor.ActionName; - if (actionName != "GetPaged") return; - var resourceName = controllerActionDescriptor.ControllerName; - operation.Summary = $"Returns paged list of the {resourceName} as IPagedList wrapped with OperationResult"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj deleted file mode 100644 index 2f9541e6..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj +++ /dev/null @@ -1,46 +0,0 @@ - - - - netcoreapp3.1 - - - - - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/Account2Controller.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/Account2Controller.cs deleted file mode 100644 index 242cf985..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/Account2Controller.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Threading.Tasks; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Services; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork.Controllers.Controllers; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.IdentityModule.Web.Controllers -{ - /// - /// Account Controller - /// - [Route("api/[controller]")] - [Authorize] - public class Account2Controller : OperationResultController - { - private readonly IAccountService _accountService; - - /// - /// Register controller - /// - /// - public Account2Controller(IAccountService accountService) - { - _accountService = accountService; - } - - /// - /// Register new user. Success registration returns UserProfile for new user. - /// - /// - /// - [HttpPost("[action]")] - [AllowAnonymous] - [ProducesResponseType(200, Type = typeof(OperationResult))] - public async Task>> Register([FromBody]RegisterViewModel model) - { - if (!ModelState.IsValid) - { - return ValidationProblem(ModelState); - } - - return OperationResultResponse(await _accountService.RegisterAsync(model)); - } - - /// - /// Returns profile information for authenticated user - /// - /// - [HttpGet("[action]")] - [ProducesResponseType(200, Type = typeof(OperationResult))] - public async Task>> Profile() - { - if (!User.Identity.IsAuthenticated) - { - return OperationResultError(null, new MicroserviceUnauthorizedException()); - } - - var userId = _accountService.GetCurrentUserId(); - if (Guid.Empty == userId) - { - return BadRequest(); - } - - var claimsOperationResult = await _accountService.GetProfileAsync(userId.ToString()); - return Ok(claimsOperationResult); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/AccountController.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/AccountController.cs deleted file mode 100644 index 6f597614..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/AccountController.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System.Threading.Tasks; -using Calabonga.Microservice.IdentityModule.Web.Mediator.Account; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels; -using Calabonga.OperationResults; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.IdentityModule.Web.Controllers -{ - /// - /// Account Controller - /// - [Route("api/[controller]")] - [Authorize] - public class AccountController : ControllerBase - { - private readonly IMediator _mediator; - - /// - /// Register controller - /// - public AccountController(IMediator mediator) - { - _mediator = mediator; - } - - /// - /// Register new user. Success registration returns UserProfile for new user. - /// - /// - /// - [HttpPost("[action]")] - [AllowAnonymous] - [ProducesResponseType(200, Type = typeof(OperationResult))] - public async Task>> Register([FromBody]RegisterViewModel model) - { - return Ok(await _mediator.Send(new RegisterRequest(model), HttpContext.RequestAborted)); - } - - /// - /// Returns profile information for authenticated user - /// - /// - [HttpGet("[action]")] - [ProducesResponseType(200, Type = typeof(OperationResult))] - public async Task>> Profile() - { - return await _mediator.Send(new ProfileRequest(), HttpContext.RequestAborted); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsReadOnlyController.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsReadOnlyController.cs deleted file mode 100644 index 0c3b2c5e..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsReadOnlyController.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Security.Claims; -using System.Threading; -using System.Threading.Tasks; -using Calabonga.Microservice.IdentityModule.Core; -using Calabonga.Microservice.IdentityModule.Web.Mediator.LogsReadonly; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.IdentityModule.Web.Controllers -{ - /// - /// ReadOnlyController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsReadonlyController : ControllerBase - { - private readonly IMediator _mediator; - - public LogsReadonlyController(IMediator mediator) - { - _mediator = mediator; - } - - [HttpGet("[action]")] - [Authorize(Policy = "Logs:UserRoles:View", Roles = AppData.SystemAdministratorRoleName)] - public async Task GetRoles() - { - //Get Roles for current user - return Ok(await _mediator.Send(new GetRolesRequest(), HttpContext.RequestAborted)); - } - - [HttpGet("[action]/{id:guid}")] - [ProducesResponseType(200)] - public async Task GetById(Guid id) - { - return Ok(await _mediator.Send(new LogGetByIdRequest(id), HttpContext.RequestAborted)); - } - - - [HttpGet("[action]")] - [ProducesResponseType(200)] - public async Task GetPaged([FromQuery] PagedListQueryParams queryParams) - { - return Ok(await _mediator.Send(new LogGetPagedRequest(queryParams), HttpContext.RequestAborted)); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsReadonly2Controller.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsReadonly2Controller.cs deleted file mode 100644 index 6c08164c..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsReadonly2Controller.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System.Security.Claims; - -using AutoMapper; - -using Calabonga.Microservice.IdentityModule.Core; -using Calabonga.Microservice.IdentityModule.Data; -using Calabonga.Microservice.IdentityModule.Entities; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Settings; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.Microservices.Core.Validators; -using Calabonga.UnitOfWork; -using Calabonga.UnitOfWork.Controllers.Controllers; - -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Options; - -namespace Calabonga.Microservice.IdentityModule.Web.Controllers -{ - /// - /// ReadOnlyController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsReadonly2Controller : ReadOnlyController - { - private readonly CurrentAppSettings _appSettings; - - /// - public LogsReadonly2Controller( - IOptions appSettings, - IUnitOfWork unitOfWork, - IMapper mapper) - : base(unitOfWork, mapper) - { - _appSettings = appSettings.Value; - } - - [HttpGet("[action]")] - [Authorize(Policy = "Logs:UserRoles:View", Roles = AppData.SystemAdministratorRoleName)] - public IActionResult GetRoles() - { - //Get Roles for current user - var roles = ClaimsHelper.GetValues((ClaimsIdentity)User.Identity, "role"); - return Ok($"Current user ({User.Identity.Name}) have following roles: {string.Join("|", roles)}"); - } - - /// - protected override PermissionValidationResult ValidateQueryParams(PagedListQueryParams queryParams) - { - if (queryParams.PageSize <= 0) - { - queryParams.PageSize = _appSettings.PageSize; - } - return new PermissionValidationResult(); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsWritable2Controller.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsWritable2Controller.cs deleted file mode 100644 index 1d90515d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsWritable2Controller.cs +++ /dev/null @@ -1,47 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Data; -using Calabonga.Microservice.IdentityModule.Entities; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Settings; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.Microservices.Core.Validators; -using Calabonga.UnitOfWork; -using Calabonga.UnitOfWork.Controllers.Controllers; -using Calabonga.UnitOfWork.Controllers.Factories; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Options; - -namespace Calabonga.Microservice.IdentityModule.Web.Controllers -{ - /// - /// WritableController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsWritable2Controller : WritableController - { - private readonly CurrentAppSettings _appSettings; - - /// - public LogsWritable2Controller( - IOptions appSettings, - IEntityManagerFactory entityManagerFactory, - IUnitOfWork unitOfWork, - IMapper mapper) - : base(entityManagerFactory, unitOfWork, mapper) - { - _appSettings = appSettings.Value; - } - - /// - protected override PermissionValidationResult ValidateQueryParams(PagedListQueryParams queryParams) - { - if (queryParams.PageSize <= 0) - { - queryParams.PageSize = _appSettings.PageSize; - } - return new PermissionValidationResult(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsWritableController.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsWritableController.cs deleted file mode 100644 index fe410619..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsWritableController.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.Threading.Tasks; -using Calabonga.Microservice.IdentityModule.Web.Mediator.LogsReadonly; -using Calabonga.Microservice.IdentityModule.Web.Mediator.LogsWritable; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.QueryParams; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.IdentityModule.Web.Controllers -{ - /// - /// WritableController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsWritableController : ControllerBase - { - private readonly IMediator _mediator; - - public LogsWritableController(IMediator mediator) - { - _mediator = mediator; - } - - - [HttpGet("[action]/{id:guid}")] - [ProducesResponseType(200)] - public async Task GetById(Guid id) - { - return Ok(await _mediator.Send(new LogGetByIdRequest(id), HttpContext.RequestAborted)); - } - - - [HttpGet("[action]")] - [ProducesResponseType(200)] - public async Task GetPaged([FromQuery] PagedListQueryParams queryParams) - { - return Ok(await _mediator.Send(new LogGetPagedRequest(queryParams), HttpContext.RequestAborted)); - } - - [HttpGet("[action]")] - public async Task GetViewmodelForCreation() - { - return Ok(await _mediator.Send(new LogCreateViewModelRequest(), HttpContext.RequestAborted)); - } - - [HttpGet("[action]/{id:guid}")] - public async Task GetViewmodelForEditing(Guid id) - { - return Ok(await _mediator.Send(new LogUpdateViewModelRequest(id), HttpContext.RequestAborted)); - } - - [HttpPost("[action]")] - public async Task PostItem([FromBody]LogCreateViewModel model) - { - return Ok(await _mediator.Send(new LogPostItemRequest(model), HttpContext.RequestAborted)); - } - - [HttpPut("[action]")] - public async Task PutItem([FromBody]LogUpdateViewModel model) - { - return Ok(await _mediator.Send(new LogPutItemRequest(model), HttpContext.RequestAborted)); - } - - [HttpDelete("[action]/{id:guid}")] - public async Task DeleteItem(Guid id) - { - return Ok(await _mediator.Send(new LogDeleteItemRequest(id), HttpContext.RequestAborted)); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/ApplicationBuilderExtensions.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/ApplicationBuilderExtensions.cs deleted file mode 100644 index 1d1bb366..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/ApplicationBuilderExtensions.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Text.RegularExpressions; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.ApplicationModels; -using Microsoft.AspNetCore.Routing; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.IdentityModule.Web.Extensions -{ - /// - /// Extensions for application class - /// - public static class ApplicationBuilderExtensions - { - /// - /// Use special route slugify for Pegasus routing - /// - /// - public static void UseRouteSlugify(this MvcOptions options) - { - options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer())); - } - } - - /// - /// Special route naming convention - /// - public class SlugifyParameterTransformer : IOutboundParameterTransformer - { - /// - public string TransformOutbound(object value) - { - return value == null - ? null - : Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower(); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/AssemblyExtensions.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/AssemblyExtensions.cs deleted file mode 100644 index 717120b0..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/AssemblyExtensions.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace Calabonga.Microservice.IdentityModule.Web.Extensions -{ - /// - /// Assembly helpers - /// - public static class AssemblyExtensions - { - /// - /// Returns types - /// - /// - /// - /// - public static List GetTypesAssignableFrom(this Assembly assembly) - { - return assembly.GetTypesAssignableFrom(typeof(T)); - } - - private static List GetTypesAssignableFrom(this Assembly assembly, Type compareType) - { - var ret = new List(); - foreach (var type in assembly.DefinedTypes) - { - if (compareType.IsAssignableFrom(type) && compareType != type && !type.IsAbstract) - { - ret.Add(type); - } - } - return ret; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/DateTimeExtensions.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/DateTimeExtensions.cs deleted file mode 100644 index 2bde1b47..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/DateTimeExtensions.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Calabonga.Microservice.IdentityModule.Web.Extensions -{ - /// - /// DateTime extensions - /// - public static class DateTimeExtensions - { - /// - /// Each day enumeration - /// - /// - /// - /// - private static IEnumerable EachDay(DateTime from, DateTime thru) - { - for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1)) - { - yield return day; - } - } - - /// - /// Each month enumeration - /// - /// - /// - /// - private static IEnumerable EachMonth(DateTime from, DateTime thru) - { - for (var month = from.Date; month.Date <= thru.Date || month.Month == thru.Month; month = month.AddMonths(1)) - { - yield return month; - } - } - - /// - /// Enumerates all days in period - /// - /// - /// - /// - public static IEnumerable EachDayTo(this DateTime dateFrom, DateTime dateTo) - { - return EachDay(dateFrom, dateTo); - } - - /// - /// Enumerates all months in period - /// - /// - /// - /// - public static IEnumerable EachMonthTo(this DateTime dateFrom, DateTime dateTo) - { - return EachMonth(dateFrom, dateTo); - } - - - /// - /// Total Month count between two dates - /// - /// - /// - /// - public static int TotalMonths(this DateTime start, DateTime end) - { - return (start.Year * 12 + start.Month) - (end.Year * 12 + end.Month); - } - - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/EntityValidatorExtensions.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/EntityValidatorExtensions.cs deleted file mode 100644 index c79081ae..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/EntityValidatorExtensions.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections.Generic; -using Calabonga.Microservices.Core.Validators; - -namespace Calabonga.Microservice.IdentityModule.Web.Extensions -{ - /// - /// Entity Validator Extensions - /// - public static class EntityValidatorExtensions - { - /// - /// Returns validator from validation results - /// - /// - /// - public static ValidationContext GetResult(this List source) - { - return new ValidationContext(source); - } - - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/IdentityExtensions.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/IdentityExtensions.cs deleted file mode 100644 index 46843f98..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Extensions/IdentityExtensions.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Security.Principal; -using Calabonga.Microservices.Core.Extensions; -using IdentityServer4.Extensions; - -namespace Calabonga.Microservice.IdentityModule.Web.Extensions -{ - /// - /// Extensions - /// - public static class IdentityExtensions - { - /// - /// Returns true/false user is owner - /// - /// - /// - /// - public static bool IsOwner(this IIdentity source, Guid userId) - { - return source.GetSubjectId().ToGuid() == userId; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/SwaggerFormAttribute.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/SwaggerFormAttribute.cs deleted file mode 100644 index ae907aa9..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/SwaggerFormAttribute.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Attributes -{ - /// - /// Custom attribute for Swagger Upload Form - /// - [AttributeUsage(AttributeTargets.Method)] - public sealed class SwaggerFormAttribute : Attribute - { - /// - public SwaggerFormAttribute(string parameterName, string description, bool hasFileUpload = true) - { - ParameterName = parameterName; - Description = description; - HasFileUpload = hasFileUpload; - } - - /// - /// UploadFile enabled - /// - public bool HasFileUpload { get; } - - /// - /// Name for the parameter - /// - public string ParameterName { get; } - - /// - /// Small description - /// - public string Description { get;} - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/SwaggerGroupAttribute.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/SwaggerGroupAttribute.cs deleted file mode 100644 index 1e336e6d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/SwaggerGroupAttribute.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Attributes -{ - /// - /// Swagger controller group attribute - /// - /// - [AttributeUsage(AttributeTargets.Class)] - public class SwaggerGroupAttribute : Attribute - { - /// - public SwaggerGroupAttribute(string groupName) - { - GroupName = groupName; - } - - /// - /// Group name - /// - public string GroupName { get; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/ValidateModelStateAttribute.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/ValidateModelStateAttribute.cs deleted file mode 100644 index dedc5bd8..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/ValidateModelStateAttribute.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Linq; -using Calabonga.OperationResults; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Attributes -{ - /// - /// Custom validation handler for availability to whit OperationResult - /// - public class ValidateModelStateAttribute : ActionFilterAttribute - { - /// - public override void OnActionExecuting(ActionExecutingContext context) - { - if (context.ModelState.IsValid) return; - var operation = OperationResult.CreateResult(); - var messages = context.ModelState.Values.SelectMany(x => x.Errors.Select(xx => xx.ErrorMessage)); - var message = string.Join(" ", messages); - operation.AddError(message); - context.Result = new OkObjectResult(operation); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/ApplicationClaimsPrincipalFactory.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/ApplicationClaimsPrincipalFactory.cs deleted file mode 100644 index 92ea8b2e..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/ApplicationClaimsPrincipalFactory.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System.Linq; -using System.Security.Claims; -using System.Threading.Tasks; -using Calabonga.Microservice.IdentityModule.Data; -using IdentityModel; -using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.Options; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Auth -{ - /// - /// Application Claims custom factory - /// - public class ApplicationClaimsPrincipalFactory : UserClaimsPrincipalFactory - { - /// - public ApplicationClaimsPrincipalFactory( - UserManager userManager, - RoleManager roleManager, - IOptions optionsAccessor) - : base(userManager, roleManager, optionsAccessor) - { - - } - - /// - /// Creates a from an user asynchronously. - /// - /// The user to create a from. - /// The that represents the asynchronous creation operation, containing the created . - public override async Task CreateAsync(ApplicationUser user) - { - var principal = await base.CreateAsync(user); - - if (user.ApplicationUserProfile?.Permissions != null) - { - var permissions = user.ApplicationUserProfile.Permissions.ToList(); - if (permissions.Any()) - { - permissions.ForEach(x => ((ClaimsIdentity)principal.Identity).AddClaim(new Claim(x.PolicyName, JwtClaimTypes.Role))); - } - } - if (!string.IsNullOrWhiteSpace(user.FirstName)) - { - ((ClaimsIdentity)principal.Identity).AddClaim(new Claim(JwtClaimTypes.GivenName, user.FirstName)); - } - - if (!string.IsNullOrWhiteSpace(user.LastName)) - { - ((ClaimsIdentity)principal.Identity).AddClaim(new Claim(ClaimTypes.Surname, user.LastName)); - } - - return principal; - } - - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/AuthorizationPolicyExtensions.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/AuthorizationPolicyExtensions.cs deleted file mode 100644 index abac4069..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/AuthorizationPolicyExtensions.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Auth -{ - /// - /// Authorization Policy registration - /// - public static class AuthorizationPolicyExtensions - { - /// - /// Registers custom for able to use authorization by policy - /// - /// - public static void UseMicroserviceAuthorizationPolicy(this IServiceCollection services) - { - services.AddSingleton(); - services.AddSingleton(); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/AuthorizationPolicyProvider.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/AuthorizationPolicyProvider.cs deleted file mode 100644 index ff65d68e..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/AuthorizationPolicyProvider.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.Options; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Auth -{ - /// - /// - /// - public class AuthorizationPolicyProvider : DefaultAuthorizationPolicyProvider - { - private readonly AuthorizationOptions _options; - - /// - public AuthorizationPolicyProvider(IOptions options) : base(options) - { - _options = options.Value; - } - - /// - public override async Task GetPolicyAsync(string policyName) - { - var policyExists = await base.GetPolicyAsync(policyName); - if (policyExists != null) return policyExists; - policyExists = new AuthorizationPolicyBuilder().AddRequirements(new PermissionRequirement(policyName)).Build(); - _options.AddPolicy(policyName, policyExists); - return policyExists; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/IdentityServerCorsPolicy.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/IdentityServerCorsPolicy.cs deleted file mode 100644 index d0623c20..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/IdentityServerCorsPolicy.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Threading.Tasks; -using IdentityServer4.Services; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Auth -{ - /// - /// Customized CORS policy for IdentityServer4 - /// - public class IdentityServerCorsPolicy : ICorsPolicyService - { - /// - public Task IsOriginAllowedAsync(string origin) - { - return Task.FromResult(true); - } - - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/MicroservicePermissionHandler.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/MicroservicePermissionHandler.cs deleted file mode 100644 index 039f5e5f..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/MicroservicePermissionHandler.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Security.Claims; -using System.Threading.Tasks; -using Calabonga.Microservices.Core; -using Microsoft.AspNetCore.Authorization; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Auth -{ - /// - /// Permission handler for custom authorization implementations - /// - public class MicroservicePermissionHandler : AuthorizationHandler - { - /// - protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) - { - var identity = (ClaimsIdentity) context.User.Identity; - var claim = ClaimsHelper.GetValue(identity, requirement.PermissionName); - if (claim == null) - { - return Task.CompletedTask; - } - - context.Succeed(requirement); - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/PermissionRequirement.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/PermissionRequirement.cs deleted file mode 100644 index de2ad5fa..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/PermissionRequirement.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Microsoft.AspNetCore.Authorization; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Auth -{ - /// - /// Permission requirement for user or service authorization - /// - public class PermissionRequirement : IAuthorizationRequirement - { - public PermissionRequirement(string permissionName) - { - PermissionName = permissionName; - } - - /// - /// Permission name - /// - public string PermissionName { get; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/UserIdentity.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/UserIdentity.cs deleted file mode 100644 index fc559a5d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/UserIdentity.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Security.Claims; -using System.Security.Principal; -using Calabonga.Microservices.Core.Exceptions; -using Microsoft.AspNetCore.Http; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Auth -{ - /// - /// Identity helper for Requests operations - /// - public sealed class UserIdentity - { - private UserIdentity() { } - - public static UserIdentity Instance => Lazy.Value; - - public void Configure(IHttpContextAccessor httpContextAccessor) - { - ContextAccessor = httpContextAccessor ?? throw new MicroserviceArgumentNullException(nameof(IHttpContextAccessor)); - IsInitialized = true; - } - - public IIdentity User - { - get - { - if (IsInitialized) - { - return ContextAccessor.HttpContext.User.Identity.IsAuthenticated - ? ContextAccessor.HttpContext.User.Identity - : null; - } - throw new MicroserviceArgumentNullException($"{nameof(UserIdentity)} has not been initialized. Please use {nameof(UserIdentity)}.Instance.Configure(...) in Configure Application method in Startup.cs"); - } - } - - public IEnumerable Claims - { - get - { - if (User != null) - { - return ContextAccessor.HttpContext.User.Claims; - } - return null; - } - } - - private static readonly Lazy Lazy = new Lazy(() => new UserIdentity()); - - private bool IsInitialized { get; set; } - - private static IHttpContextAccessor ContextAccessor { get; set; } - - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/DependencyInjection/CommonRegistrations.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/DependencyInjection/CommonRegistrations.cs deleted file mode 100644 index 9e78dba9..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/DependencyInjection/CommonRegistrations.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Data; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Auth; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Services; -using IdentityServer4.Services; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.DependencyInjection -{ - /// - /// Registrations for both points: API and Scheduler - /// - public partial class DependencyContainer - { - /// - /// Register - /// - /// - public static void Common(IServiceCollection services) - { - services.AddTransient(); - services.AddTransient(); - services.AddScoped(); - - // services - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/EntityManagers/LogManager.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/EntityManagers/LogManager.cs deleted file mode 100644 index ad3b58ac..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/EntityManagers/LogManager.cs +++ /dev/null @@ -1,21 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Entities; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.Validators; -using Calabonga.UnitOfWork.Controllers.Factories; -using Calabonga.UnitOfWork.Controllers.Managers; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Engine.EntityManagers -{ - /// - /// Entity manager for - /// - public class LogManager: EntityManager - { - /// - public LogManager(IMapper mapper, IViewModelFactory viewModelFactory, IEntityValidator validator) - : base(mapper, viewModelFactory, validator) - { - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/EntityValidators/LogValidator.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/EntityValidators/LogValidator.cs deleted file mode 100644 index a562c583..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/EntityValidators/LogValidator.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Entities; -using Calabonga.Microservices.Core.Validators; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Engine.EntityValidators -{ - /// - /// Entity Validator for - /// - public class LogValidator: EntityValidator - { - - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/ViewModelFactories/LogViewModelFactory.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/ViewModelFactories/LogViewModelFactory.cs deleted file mode 100644 index 18a69167..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/ViewModelFactories/LogViewModelFactory.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Threading.Tasks; -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Data; -using Calabonga.Microservice.IdentityModule.Entities; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using Calabonga.UnitOfWork.Controllers.Factories; -using Microsoft.Extensions.Logging; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Engine.ViewModelFactories -{ - /// - /// ViewModel factory for - /// - public class LogViewModelFactory: ViewModelFactory - { - private readonly IUnitOfWork _context; - private readonly IMapper _mapper; - - public LogViewModelFactory( - IUnitOfWork context, - IMapper mapper) - { - _context = context; - _mapper = mapper; - } - - /// - public override Task> GenerateForCreateAsync() - { - var operation = OperationResult.CreateResult(); - operation.Result = new LogCreateViewModel() - { - CreatedAt = DateTime.Now, - Level = LogLevel.Information.ToString(), - Logger = "Demo purposes only", - Message = $"This is demo message {DateTime.Now}" - }; - return Task.FromResult(operation); - } - - /// - public override async Task> GenerateForUpdateAsync(Guid id) - { - var operation = OperationResult.CreateResult(); - var entity = await _context.GetRepository().GetFirstOrDefaultAsync(predicate: x => x.Id == id); - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("ViewModel generated for Log entity. Please see Additional information in DataObject").AddData(new { Identifier = id }); - - return operation; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Helpers/ValidationContextHelper.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Helpers/ValidationContextHelper.cs deleted file mode 100644 index 736ac683..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Helpers/ValidationContextHelper.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.ObjectModel; -using System.ComponentModel.DataAnnotations; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Helpers -{ - /// - /// ValidationContext Helper for validation operations - /// - public static class ValidationContextHelper - { - /// - /// Returns validation results of IValidatableObject - /// - /// - /// - /// - /// - public static bool TryValidate(object obj, out Collection results, ValidationContext validationContext = null) - { - var context = validationContext ?? new ValidationContext(obj, serviceProvider: null, items: null); - results = new Collection(); - return Validator.TryValidateObject(obj, context, results, validateAllProperties: true); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/ApplicationUserProfileMapperConfiguration.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/ApplicationUserProfileMapperConfiguration.cs deleted file mode 100644 index 419351c2..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/ApplicationUserProfileMapperConfiguration.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Data; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Mappers.Base; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Mappers -{ - /// - /// Mapper Configuration for entity Person - /// - public class ApplicationUserProfileMapperConfiguration : MapperConfigurationBase - { - /// - public ApplicationUserProfileMapperConfiguration() - { - CreateMap() - .ForAllOtherMembers(x => x.Ignore()); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/IAutoMapper.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/IAutoMapper.cs deleted file mode 100644 index 283cff26..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/IAutoMapper.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Mappers.Base -{ - /// - /// The stub for reflection helper profiles registrations - /// - public interface IAutoMapper { } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/MapperConfigurationBase.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/MapperConfigurationBase.cs deleted file mode 100644 index 52420fee..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/MapperConfigurationBase.cs +++ /dev/null @@ -1,10 +0,0 @@ -using AutoMapper; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Mappers.Base { - - /// - /// Base class for mapper configuration. - /// All ViewModel that will be mapped should implement IAutoMapper - /// - public abstract class MapperConfigurationBase : Profile, IAutoMapper { } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/PagedListConverter.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/PagedListConverter.cs deleted file mode 100644 index b3aa074f..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/PagedListConverter.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using AutoMapper; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Mappers.Base { - - /// - /// Generic converter for IPagedList collections - /// - /// - /// - public class PagedListConverter : ITypeConverter, IPagedList> { - - /// Performs conversion from source to destination type - /// Source object - /// Destination object - /// Resolution context - /// Destination object - public IPagedList Convert(IPagedList source, IPagedList destination, ResolutionContext context) { - if (source == null) return null; - var vm = source.Items.Select(m => context.Mapper.Map(m)).ToList(); - - - var pagedList = PagedList.From(source, (con)=> context.Mapper.Map>(con)); - // var pagedList = vm.ToPagedList(source.PageIndex, source.PageSize); - return pagedList; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/LogMapperConfiguration.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/LogMapperConfiguration.cs deleted file mode 100644 index 335fe5c1..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/LogMapperConfiguration.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Entities; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Mappers.Base; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Mappers -{ - /// - /// Mapper Configuration for entity Log - /// - public class LogMapperConfiguration : MapperConfigurationBase - { - /// - public LogMapperConfiguration() - { - CreateMap() - .ForMember(x => x.Id, o => o.Ignore()); - - CreateMap(); - - CreateMap(); - - CreateMap() - .ForMember(x => x.CreatedAt, o => o.Ignore()) - .ForMember(x => x.ThreadId, o => o.Ignore()) - .ForMember(x => x.ExceptionMessage, o => o.Ignore()); - - CreateMap, IPagedList>() - .ConvertUsing>(); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/UserMapperConfiguration.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/UserMapperConfiguration.cs deleted file mode 100644 index 945e48e3..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/UserMapperConfiguration.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Security.Claims; -using Calabonga.Microservice.IdentityModule.Data; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Mappers.Base; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels; -using Calabonga.Microservices.Core; -using IdentityModel; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Mappers -{ - /// - /// Mapper Configuration for entity ApplicationUser - /// - public class UserMapperConfiguration : MapperConfigurationBase - { - /// - public UserMapperConfiguration() - { - CreateMap() - .ForMember(x => x.UserName, o => o.MapFrom(p => p.Email)) - .ForMember(x => x.Email, o => o.MapFrom(p => p.Email)) - .ForMember(x => x.EmailConfirmed, o => o.MapFrom(src => true)) - .ForMember(x => x.FirstName, o => o.MapFrom(p => p.FirstName)) - .ForMember(x => x.LastName, o => o.MapFrom(p => p.LastName)) - .ForMember(x => x.PhoneNumberConfirmed, o => o.MapFrom(src => true)) - .ForAllOtherMembers(x => x.Ignore()); - - CreateMap() - .ForMember(x => x.Id, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, JwtClaimTypes.Subject))) - .ForMember(x => x.PositionName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Actor))) - .ForMember(x => x.FirstName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, JwtClaimTypes.GivenName))) - .ForMember(x => x.LastName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Surname))) - .ForMember(x => x.Roles, o => o.MapFrom(claims => ClaimsHelper.GetValues(claims, JwtClaimTypes.Role))) - .ForMember(x => x.Email, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, JwtClaimTypes.Name))) - .ForMember(x => x.PhoneNumber, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, JwtClaimTypes.PhoneNumber))) - .ForAllOtherMembers(x => x.Ignore()); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/AccountService.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/AccountService.cs deleted file mode 100644 index e59a781f..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/AccountService.cs +++ /dev/null @@ -1,248 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Claims; -using System.Threading.Tasks; -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Core; -using Calabonga.Microservice.IdentityModule.Data; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Auth; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.Microservices.Core.Extensions; -using Calabonga.Microservices.Core.Validators; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using IdentityModel; -using IdentityServer4.Extensions; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Services -{ - /// - /// Account service - /// - public class AccountService : IAccountService - { - private readonly IUnitOfWork _unitOfWork; - private readonly ILogger _logger; - private readonly ApplicationClaimsPrincipalFactory _claimsFactory; - private readonly IHttpContextAccessor _httpContext; - private readonly IMapper _mapper; - private readonly UserManager _userManager; - private readonly RoleManager _roleManager; - - public AccountService( - IUserStore userStore, - IOptions optionsAccessor, - IPasswordHasher passwordHasher, - IEnumerable> userValidators, - IEnumerable> passwordValidators, - ILookupNormalizer keyNormalizer, - IdentityErrorDescriber errors, - IServiceProvider services, - ILogger> loggerRole, - IEnumerable> roleValidators, - IUnitOfWork unitOfWork, - ILogger logger, - ILogger> loggerUser, - ApplicationClaimsPrincipalFactory claimsFactory, - IHttpContextAccessor httpContext, - IMapper mapper) - { - _unitOfWork = unitOfWork; - _logger = logger; - _claimsFactory = claimsFactory; - _httpContext = httpContext; - _mapper = mapper; - - // We need to created a custom instance for current service - // It'll help to use Transaction in the Unit Of Work - _userManager = new UserManager(userStore, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, loggerUser); - var roleStore = new RoleStore(_unitOfWork.DbContext); - _roleManager = new RoleManager(roleStore, roleValidators, keyNormalizer, errors, loggerRole); - } - - /// - public Guid GetCurrentUserId() - { - var identity = _httpContext.HttpContext?.User.Identity; - var identitySub = identity.GetSubjectId(); - return identitySub.ToGuid(); - } - - /// - /// Returns instance after successful registration - /// - /// - /// - public async Task> RegisterAsync(RegisterViewModel model) - { - var operation = OperationResult.CreateResult(); - var user = _mapper.Map(model); - await using var transaction = await _unitOfWork.BeginTransactionAsync(); - var result = await _userManager.CreateAsync(user, model.Password); - const string role = AppData.ManagerRoleName; - - if (result.Succeeded) - { - if (await _roleManager.FindByNameAsync(role) == null) - { - operation.Exception = new MicroserviceUserNotFoundException(); - operation.AddError(AppData.Exceptions.UserNotFoundException); - return await Task.FromResult(operation); - } - await _userManager.AddToRoleAsync(user, role); - await AddClaimsToUser(_userManager, user, role); - var profile = _mapper.Map(model); - var profileRepository = _unitOfWork.GetRepository(); - - await profileRepository.InsertAsync(profile); - await _unitOfWork.SaveChangesAsync(); - if (_unitOfWork.LastSaveChangesResult.IsOk) - { - var principal = await _claimsFactory.CreateAsync(user); - operation.Result = _mapper.Map(principal.Identity); - operation.AddSuccess(AppData.Messages.UserSuccessfullyRegistered); - _logger.LogInformation(operation.GetMetadataMessages()); - transaction.Commit(); - return await Task.FromResult(operation); - } - } - var errors = result.Errors.Select(x => $"{x.Code}: {x.Description}"); - operation.AddError(string.Join(", ", errors)); - operation.Exception = _unitOfWork.LastSaveChangesResult.Exception; - transaction.Rollback(); - return await Task.FromResult(operation); - } - - /// - /// Returns user profile - /// - /// - /// - public async Task> GetProfileAsync(string identifier) - { - var operation = OperationResult.CreateResult(); - var claimsPrincipal = await GetUserClaimsAsync(identifier); - operation.Result = _mapper.Map(claimsPrincipal.Identity); - return await Task.FromResult(operation); - } - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - /// - public async Task GetUserClaimsAsync(string identifier) - { - if (string.IsNullOrEmpty(identifier)) - { - throw new MicroserviceException(); - } - var userManager = _userManager; - var user = await userManager.FindByIdAsync(identifier); - if (user == null) - { - throw new MicroserviceUserNotFoundException(); - } - - var defaultClaims = await _claimsFactory.CreateAsync(user); - return defaultClaims; - } - - /// - /// Returns user by his identifier - /// - /// - /// - public Task GetByIdAsync(Guid id) - { - var userManager = _userManager; - return userManager.FindByIdAsync(id.ToString()); - } - - /// - /// Returns current user account information or null when user does not logged in - /// - /// - public async Task GetCurrentUserAsync() - { - var userManager = _userManager; - var userId = GetCurrentUserId().ToString(); - var user = await userManager.FindByIdAsync(userId); - return user; - } - - /// - public async Task> GetUsersByEmailsAsync(IEnumerable emails) - { - var userManager = _userManager; - var result = new List(); - foreach (var email in emails) - { - var user = await userManager.FindByEmailAsync(email); - if (user != null && !result.Contains(user)) - { - result.Add(user); - } - } - return await Task.FromResult(result); - } - - /// - /// Check roles for current user - /// - /// - /// - public async Task IsInRolesAsync(string[] roleNames) - { - var userManager = _userManager; - var userId = GetCurrentUserId().ToString(); - var user = await userManager.FindByIdAsync(userId); - if (user == null) - { - var resultUserNotFound = new PermissionValidationResult(); - resultUserNotFound.AddError(AppData.Exceptions.UnauthorizedException); - return await Task.FromResult(resultUserNotFound); - } - foreach (var roleName in roleNames) - { - var ok = await userManager.IsInRoleAsync(user, roleName); - if (ok) - { - return new PermissionValidationResult(); - } - } - - var result = new PermissionValidationResult(); - result.AddError(AppData.Exceptions.UnauthorizedException); - return result; - } - - /// - public async Task> GetUsersInRoleAsync(string roleName) - { - var userManager = _userManager; - return await userManager.GetUsersInRoleAsync(roleName); - } - - #region privates - - private async Task AddClaimsToUser(UserManager userManager, ApplicationUser user, string role) - { - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.Name, user.UserName)); - await userManager.AddClaimAsync(user, new Claim(JwtClaimTypes.GivenName, user.FirstName)); - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.Surname, user.LastName)); - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.Email, user.Email)); - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, role)); - } - - #endregion - } -} - diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/CacheService.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/CacheService.cs deleted file mode 100644 index 055d36a2..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/CacheService.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using Calabonga.Microservices.Core.Exceptions; -using Microsoft.Extensions.Caching.Memory; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Services -{ - /// - /// Cache service - /// - public class CacheService : ICacheService - { - private readonly IMemoryCache _cache; - private readonly TimeSpan _defaultSlidingExpiration = TimeSpan.FromSeconds(60); - - /// - public CacheService(IMemoryCache cache) - { - _cache = cache; - } - - /// - public TEntry Get(object key) - { - if (key == null) - { - throw new MicroserviceArgumentNullException(nameof(key)); - } - - return _cache.Get(key); - } - - /// - public void SetForMinute(object key, TEntry cacheEntry) - { - SetWithSlidingExpiration(key, cacheEntry, _defaultSlidingExpiration); - } - - /// - public void SetForThirtyMinutes(object key, TEntry cacheEntry) - { - SetWithSlidingExpiration(key, cacheEntry, TimeSpan.FromMinutes(30)); - } - - /// - /// Default set mechanism - /// - /// - /// - /// - /// - public void SetWithSlidingExpiration(object key, TEntry cacheEntry, TimeSpan slidingExpiration) - { - if (cacheEntry == null) - { - throw new MicroserviceArgumentNullException(nameof(cacheEntry)); - } - - if (key == null) - { - throw new MicroserviceArgumentNullException(nameof(key)); - } - - if (slidingExpiration.Ticks == 0) - { - slidingExpiration = _defaultSlidingExpiration; - } - - var options = new MemoryCacheEntryOptions().SetSlidingExpiration(slidingExpiration); - - _cache.Set(key, cacheEntry, options); - } - - /// - public TEntry GetOrCreate(TKey key, Func findIfNotFoundFunc) - { - return _cache.GetOrCreate(key, findIfNotFoundFunc); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/IAccountService.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/IAccountService.cs deleted file mode 100644 index 1fa0390b..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/IAccountService.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Security.Claims; -using System.Threading.Tasks; -using Calabonga.Microservice.IdentityModule.Data; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels; -using Calabonga.Microservices.Core.Validators; -using Calabonga.OperationResults; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Services -{ - /// - /// Represent interface for account management - /// - public interface IAccountService - { - /// - /// Returns a collection of the by emails - /// - /// - /// - Task> GetUsersByEmailsAsync(IEnumerable emails); - - /// - /// Get User Id from HttpContext - /// - /// - Guid GetCurrentUserId(); - - /// - /// Returns instance after successful registration - /// - /// - /// - Task> RegisterAsync(RegisterViewModel model); - - /// - /// Returns user profile - /// - /// - /// - Task> GetProfileAsync(string identifier); - - /// - /// Returns User by user identifier - /// - /// - /// - Task GetByIdAsync(Guid id); - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - /// - Task GetUserClaimsAsync(string identifier); - - /// - /// Returns current user account information or null when user does not logged in - /// - /// - Task GetCurrentUserAsync(); - - /// - /// Check roles for current user - /// - /// - /// - Task IsInRolesAsync(string[] roleNames); - - /// - /// Returns all system administrators registered in the system - /// - /// - /// - Task> GetUsersInRoleAsync(string roleName); - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/ICacheService.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/ICacheService.cs deleted file mode 100644 index cc93b97f..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/ICacheService.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using Microsoft.Extensions.Caching.Memory; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Services -{ - /// - /// Cache service interface - /// - public interface ICacheService - { - /// - /// Get the entry from the cache - /// - /// - /// - TEntry Get(object key); - - /// - /// Sets entry cache for one minute sliding expiration - /// - /// - /// - /// - void SetForMinute(object key, TEntry cacheEntry); - - /// - /// Sets entry cache for 30 minutes sliding expiration - /// - /// - /// - /// - void SetForThirtyMinutes(object key, TEntry cacheEntry); - - /// - /// Sets entry cache for custom sliding expiration interval - /// - /// - /// - /// - /// - void SetWithSlidingExpiration(object key, TEntry cacheEntry, TimeSpan slidingExpiration); - - /// - /// Returns already exist entry or first put it to the cache and then return entry - /// - /// - /// - /// - /// - /// - TEntry GetOrCreate(TKey key, Func findIfNotFoundFunc); - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/ILogService.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/ILogService.cs deleted file mode 100644 index 91572d2f..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/ILogService.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Services -{ - /// - /// Interface for Business logic logger can save messages to database - /// - public interface ILogService - { - /// - /// Log information message - /// - /// - void LogInformation(string message); - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/IdentityProfileService.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/IdentityProfileService.cs deleted file mode 100644 index 23a6fbd3..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/IdentityProfileService.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Linq; -using System.Threading.Tasks; -using Calabonga.Microservices.Core.Extensions; -using IdentityServer4.Extensions; -using IdentityServer4.Models; -using IdentityServer4.Services; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Services -{ - /// - /// Custom implementation of the IProfileService - /// - public class IdentityProfileService : IProfileService - { - private readonly IAccountService _accountService; - /// - /// Identity Profile Service - /// - /// - public IdentityProfileService(IAccountService accountService) - { - _accountService = accountService; - } - - /// - /// This method is called whenever claims about the user are requested (e.g. during token creation or via the user info endpoint) - /// - /// The context. - /// - public async Task GetProfileDataAsync(ProfileDataRequestContext context) - { - var identifier = context.Subject.GetSubjectId(); - var profile = await _accountService.GetUserClaimsAsync(identifier); - context.IssuedClaims = profile.Claims.ToList(); - } - - /// - /// Returns IsActive (IdentityServer4) - /// - /// - /// - public async Task IsActiveAsync(IsActiveContext context) - { - var identifier = context.Subject.GetSubjectId(); - var user = await _accountService.GetByIdAsync(identifier.ToGuid()); - context.IsActive = user != null; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/LogService.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/LogService.cs deleted file mode 100644 index a8e26cfc..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/LogService.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using Calabonga.Microservice.IdentityModule.Data; -using Calabonga.Microservice.IdentityModule.Entities; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.UnitOfWork; -using Microsoft.Extensions.Logging; - -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Services -{ - /// - /// Business logic logger can save messages to database - /// - public class LogService : ILogService - { - private readonly IUnitOfWork _unitOfWork; - - /// - public LogService(IUnitOfWork unitOfWork) - { - _unitOfWork = unitOfWork; - } - /// - public void LogInformation(string message) - { - Log(LogLevel.Information, message); - } - - /// - /// Allows to save data logs to the database Logs table - /// - private void Log(LogLevel level, string message, Exception exception = null) - { - var logs = _unitOfWork.GetRepository(); - var log = new Log - { - CreatedAt = DateTime.UtcNow, - Level = level.ToString(), - Logger = GetType().Name, - Message = message, - ThreadId = "0", - ExceptionMessage = exception?.Message - }; - logs.Insert(log); - _unitOfWork.SaveChanges(); - if (!_unitOfWork.LastSaveChangesResult.IsOk) - { - throw new MicroserviceArgumentNullException(); - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Settings/CurrentAppSettings.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Settings/CurrentAppSettings.cs deleted file mode 100644 index cf15a022..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Settings/CurrentAppSettings.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Web.Infrastructure.Settings -{ - /// - /// Represents configuration file with current application settings - /// - public class CurrentAppSettings - { - /// - /// Default page size - /// - public int PageSize { get; set; } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/Account/Profile.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/Account/Profile.cs deleted file mode 100644 index 30e3d6cd..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/Account/Profile.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; - -using Calabonga.AspNetCore.Controllers.Base; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Services; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels; -using Calabonga.OperationResults; - -using IdentityServer4.Extensions; - -using Microsoft.AspNetCore.Http; - -namespace Calabonga.Microservice.IdentityModule.Web.Mediator.Account -{ - /// - /// Request: Profile - /// - public class ProfileRequest : RequestBase> - { - } - - /// - /// Response: Profile - /// - public class ProfileRequestHandler : OperationResultRequestHandlerBase - { - private readonly IAccountService _accountService; - private readonly IHttpContextAccessor _httpContextAccessor; - - public ProfileRequestHandler( - IAccountService accountService, - IHttpContextAccessor httpContextAccessor) - { - _accountService = accountService; - _httpContextAccessor = httpContextAccessor; - } - - public override async Task> Handle(ProfileRequest request, CancellationToken cancellationToken) - { - var user = _httpContextAccessor.HttpContext.User; - if (user != null) - { - return await _accountService.GetProfileAsync(user.Identity.GetSubjectId()); - } - - var operation = OperationResult.CreateResult(); - operation.AddWarning("User not found"); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/Account/Register.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/Account/Register.cs deleted file mode 100644 index 358f94b8..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/Account/Register.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; - -using Calabonga.AspNetCore.Controllers.Base; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.Services; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels; -using Calabonga.OperationResults; - -namespace Calabonga.Microservice.IdentityModule.Web.Mediator.Account -{ - /// - /// Request: Register new account - /// - public class RegisterRequest : RequestBase> - { - public RegisterViewModel Model { get; } - - public RegisterRequest(RegisterViewModel model) - { - Model = model; - } - } - - /// - /// Response: Register new account - /// - public class RegisterRequestHandler : OperationResultRequestHandlerBase - { - private readonly IAccountService _accountService; - - public RegisterRequestHandler(IAccountService accountService) - { - _accountService = accountService; - } - - public override Task> Handle(RegisterRequest request, CancellationToken cancellationToken) - { - return _accountService.RegisterAsync(request.Model); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/Behaviors/ValidatorBehavior.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/Behaviors/ValidatorBehavior.cs deleted file mode 100644 index 35cc3059..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/Behaviors/ValidatorBehavior.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Calabonga.AspNetCore.Controllers.Base; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using FluentValidation; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Mediator.Behaviors -{ - /// - /// Base validator for requests - /// - /// - /// - public class ValidatorBehavior : IPipelineBehavior - where TRequest : IRequest - { - private readonly IEnumerable> _validators; - - public ValidatorBehavior(IEnumerable> validators) - { - _validators = validators; - } - - /// - /// Pipeline handler. Perform any additional behavior and await the delegate as necessary - /// - /// Incoming request - /// Cancellation token - /// Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler. - /// Awaitable task returning the - public Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) - { - var failures = _validators - .Select(x => x.Validate(new ValidationContext(request))) - .SelectMany(x => x.Errors) - .Where(x => x != null) - .ToList(); - - if (!failures.Any()) return next(); - - var type = typeof(TResponse); - if (!type.IsSubclassOf(typeof(OperationResult))) - { - var exception = new ValidationException(failures); - throw exception; - } - - var result = Activator.CreateInstance(type); - (result as OperationResult).AddError(new MicroserviceEntityValidationException()); - foreach (var failure in failures) - { - (result as OperationResult)?.AppendLog($"{failure.PropertyName}: {failure.ErrorMessage}"); - } - return Task.FromResult((TResponse) result); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/GetRoles.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/GetRoles.cs deleted file mode 100644 index 1bd234a3..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/GetRoles.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Security.Claims; -using Calabonga.AspNetCore.Controllers.Base; -using Calabonga.Microservices.Core; -using MediatR; -using Microsoft.AspNetCore.Http; - -namespace Calabonga.Microservice.IdentityModule.Web.Mediator.LogsReadonly -{ - /// - /// Request: Returns user roles - /// - public class GetRolesRequest: RequestBase - { - - } - - public class GetRolesRequestHandler : RequestHandler - { - private readonly IHttpContextAccessor _httpContextAccessor; - - public GetRolesRequestHandler(IHttpContextAccessor httpContextAccessor) - { - _httpContextAccessor = httpContextAccessor; - } - - protected override string Handle(GetRolesRequest request) - { - var user = _httpContextAccessor.HttpContext.User; - var roles = ClaimsHelper.GetValues((ClaimsIdentity)user.Identity, "role"); - return $"Current user ({user.Identity.Name}) have following roles: {string.Join("|", roles)}"; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/LogGetById.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/LogGetById.cs deleted file mode 100644 index ab097db8..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/LogGetById.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.IdentityModule.Entities; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.IdentityModule.Web.Mediator.LogsReadonly -{ - /// - /// Request for Log by Identifier - /// - public class LogGetByIdRequest : GetByIdQuery - { - public LogGetByIdRequest(Guid id) : base(id) - { - } - } - - /// - /// Response for Request for Log by Identifier - /// - public class LogGetByIdRequestHandler : GetByIdHandlerBase - { - public LogGetByIdRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/LogGetPaged.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/LogGetPaged.cs deleted file mode 100644 index 4a4cc525..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/LogGetPaged.cs +++ /dev/null @@ -1,30 +0,0 @@ -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.IdentityModule.Entities; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.IdentityModule.Web.Mediator.LogsReadonly -{ - /// - /// Request for paged list of Logs - /// - public class LogGetPagedRequest : GetPagedQuery - { - public LogGetPagedRequest(PagedListQueryParams queryParams) : base(queryParams) - { - } - } - - /// - /// Request for paged list of Logs - /// - public class LogGetPagedRequestHandler : GetPagedHandlerBase - { - public LogGetPagedRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogCreateViewModel.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogCreateViewModel.cs deleted file mode 100644 index 38538b8a..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogCreateViewModel.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Threading.Tasks; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Microsoft.Extensions.Logging; - -namespace Calabonga.Microservice.IdentityModule.Web.Mediator.LogsWritable -{ - /// - /// Request: Returns ViewModel for entity Log creation - /// - public class LogCreateViewModelRequest: CreateViewModelQuery - { - - } - - /// - /// Response: Returns ViewModel for entity Log creation - /// - public class LogCreateViewModelRequestHandler : CreateViewModelHandlerBase - { - protected override ValueTask GenerateCreateViewModel() - { - return new ValueTask(new LogCreateViewModel - { - CreatedAt = DateTime.UtcNow, - Level = LogLevel.Information.ToString(), - Message = "Generated automatically", - Logger = "LogCreateViewModelRequestHandler", - ThreadId = "0" - }); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogDeleteItem.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogDeleteItem.cs deleted file mode 100644 index 7c0a967b..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogDeleteItem.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.IdentityModule.Entities; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.IdentityModule.Web.Mediator.LogsWritable -{ - /// - /// Request: Log delete - /// - public class LogDeleteItemRequest: DeleteByIdQuery - { - public LogDeleteItemRequest(Guid id) : base(id) - { - } - } - - /// - /// Request: Log delete - /// - public class LogDeleteItemRequestHandler : DeleteByIdHandlerBase - { - public LogDeleteItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogPostItem.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogPostItem.cs deleted file mode 100644 index 6221ca7d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogPostItem.cs +++ /dev/null @@ -1,29 +0,0 @@ -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.IdentityModule.Entities; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.IdentityModule.Web.Mediator.LogsWritable -{ - /// - /// Request: Log creation - /// - public class LogPostItemRequest: PostItemQuery - { - public LogPostItemRequest(LogCreateViewModel model) : base(model) - { - } - } - - /// - /// Request: Log creation - /// - public class LogPostItemRequestHandler : PostItemHandlerBase - { - public LogPostItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogPutItem.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogPutItem.cs deleted file mode 100644 index 2ff33e15..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogPutItem.cs +++ /dev/null @@ -1,37 +0,0 @@ -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.IdentityModule.Entities; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.IdentityModule.Web.Mediator.LogsWritable -{ - /// - /// Request: Log edit - /// - public class LogPutItemRequest: PutItemQuery - { - public LogPutItemRequest(LogUpdateViewModel model) : base(model) - { - } - } - - /// - /// Request: Log creation - /// - public class LogPutItemRequestHandler : PutItemHandlerBase - { - public LogPutItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - - protected override OperationResult ProcessOperationResult(OperationResult operationResult, LogViewModel response) - { - operationResult.AppendLog("Successfully updated"); - operationResult.Result = response; - return operationResult; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogUpdateViewModel.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogUpdateViewModel.cs deleted file mode 100644 index 2fc13e49..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogUpdateViewModel.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.IdentityModule.Entities; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.IdentityModule.Web.Mediator.LogsWritable -{ - /// - /// Request: Returns ViewModel for entity Log creation - /// - public class LogUpdateViewModelRequest: UpdateViewModelQuery - { - public LogUpdateViewModelRequest(Guid id) : base(id) - { - } - } - - /// - /// Response: Returns ViewModel for entity Log creation - /// - public class LogUpdateViewModelRequestHandler : UpdateViewModelHandlerBase - { - public LogUpdateViewModelRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Middlewares/ETagMiddleware.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Middlewares/ETagMiddleware.cs deleted file mode 100644 index 6d9bd2c9..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Middlewares/ETagMiddleware.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System.IO; -using System.Security.Cryptography; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Net.Http.Headers; - -namespace Calabonga.Microservice.IdentityModule.Web.Middlewares -{ - /// - /// ETagger extension - /// - public static class ApplicationBuilderExtensions - { - /// - /// Use Custom middleware - /// - /// - public static void UseETagger(this IApplicationBuilder app) - { - app.UseMiddleware(); - } - } - - /// - /// ETag middleware from Mads Kristensen. - /// See https://madskristensen.net/blog/send-etag-headers-in-aspnet-core/ - /// - public class ETagMiddleware - { - private readonly RequestDelegate _next; - - /// - public ETagMiddleware(RequestDelegate next) - { - _next = next; - } - - /// - /// Invoke middleware entry point - /// - /// - /// - public async Task InvokeAsync(HttpContext context) - { - var response = context.Response; - var originalStream = response.Body; - - using (var ms = new MemoryStream()) - { - response.Body = ms; - - await _next(context); - - if (IsEtagSupported(response)) - { - var checksum = CalculateChecksum(ms); - - response.Headers[HeaderNames.ETag] = checksum; - - if (context.Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var etag) && checksum == etag) - { - response.StatusCode = StatusCodes.Status304NotModified; - return; - } - } - - ms.Position = 0; - await ms.CopyToAsync(originalStream); - } - } - - private static bool IsEtagSupported(HttpResponse response) - { - if (response.StatusCode != StatusCodes.Status200OK) - return false; - - // The 100kb length limit is not based in science. Feel free to change - if (response.Body.Length > 100 * 1024) - return false; - - if (response.Headers.ContainsKey(HeaderNames.ETag)) - return false; - - return true; - } - - private static string CalculateChecksum(MemoryStream ms) - { - string checksum = ""; - - using (var algo = SHA1.Create()) - { - ms.Position = 0; - byte[] bytes = algo.ComputeHash(ms); - checksum = $"\"{WebEncoders.Base64UrlEncode(bytes)}\""; - } - - return checksum; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Middlewares/ErrorHandle.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Middlewares/ErrorHandle.cs deleted file mode 100644 index 2ed4d176..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Middlewares/ErrorHandle.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Threading.Tasks; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; - -namespace Calabonga.Microservice.IdentityModule.Web.Middlewares -{ - /// - /// Custom error handler. It allows to view error messages on UI - /// - public class ErrorHandlingMiddleware - { - private readonly RequestDelegate _next; - - /// - public ErrorHandlingMiddleware(RequestDelegate next) - { - _next = next; - } - - /// - /// Invoke middle ware. Entry point - /// - /// - /// - public async Task Invoke(HttpContext context) - { - try - { - await _next(context); - } - catch (Exception ex) - { - await HandleExceptionAsync(context, ex); - } - } - - private static Task HandleExceptionAsync(HttpContext context, Exception exception) - { - try - { - var result = JsonConvert.SerializeObject(ExceptionHelper.GetMessages(exception), Formatting.Indented); - if (result?.Length > 4000) - { - return context.Response.WriteAsync("Error message to long. Please use DEBUG in method HandleExceptionAsync to handle a whole of text of the exception"); - } - return context.Response.WriteAsync(result); - } - catch - { - return context.Response.WriteAsync($"{exception.Message} For more information please use DEBUG in method HandleExceptionAsync to handle a whole of text of the exception"); - } - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Program.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Program.cs deleted file mode 100644 index 8766cc42..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Program.cs +++ /dev/null @@ -1,39 +0,0 @@ -// --------------------------------------- -// Name: Microservice Template -// Author: Calabonga (calabonga.net) -// Version: 2.2.0 -// Based on: ASP.NET Core 3.1 -// Created Date: 2019-10-06 -// Updated Date 2020-09-27 -// --------------------------------------- - -using System; -using Calabonga.Microservice.IdentityModule.Core; -using Calabonga.Microservice.IdentityModule.Data.DatabaseInitialization; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -namespace Calabonga.Microservice.IdentityModule.Web -{ - public class Program - { - public static void Main(string[] args) - { - var webHost = CreateHostBuilder(args).Build(); - using (var scope = webHost.Services.CreateScope()) - { - DatabaseInitializer.Seed(scope.ServiceProvider); - } - - Console.Title = $"{AppData.ServiceName} v.{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - webHost.Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Properties/launchSettings.json b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Properties/launchSettings.json deleted file mode 100644 index fe92d81b..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Properties/launchSettings.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/launchsettings.json", - "profiles": { - "Kestrel_dev": { - "commandName": "Project", - "launchBrowser": true, - "launchUrl": "api/manual", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "http://localhost:10001" - }, - "Kestrel_prod": { - "commandName": "Project", - "launchBrowser": true, - "launchUrl": "api/manual", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Production" - }, - "applicationUrl": "http://localhost:10001" - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Startup.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Startup.cs deleted file mode 100644 index 8fa80045..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Startup.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Web.AppStart.Configures; -using Calabonga.Microservice.IdentityModule.Web.AppStart.ConfigureServices; -using Calabonga.Microservice.IdentityModule.Web.Infrastructure.DependencyInjection; -using Calabonga.UnitOfWork.Controllers.DependencyContainer; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.IdentityModule.Web -{ - /// - /// Entry point - /// - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - /// - /// Configuration - /// - public IConfiguration Configuration { get; } - - /// - /// This method gets called by the runtime. Use this method to add services to the container. - /// - /// - public void ConfigureServices(IServiceCollection services) - { - ConfigureServicesBase.ConfigureServices(services, Configuration); - ConfigureServicesAuthentication.ConfigureServices(services, Configuration); - ConfigureServicesSwagger.ConfigureServices(services, Configuration); - ConfigureServicesCors.ConfigureServices(services, Configuration); - ConfigureServicesControllers.ConfigureServices(services); - ConfigureServicesMediator.ConfigureServices(services); - ConfigureServicesValidators.ConfigureServices(services); - - DependencyContainer.Common(services); - NimbleDependencyContainer.ConfigureServices(services); - } - /// - /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - /// - /// - /// - /// - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, AutoMapper.IConfigurationProvider mapper) - { - ConfigureCommon.Configure(app, env, mapper); - ConfigureEndpoints.Configure(app); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/RegisterViewModel.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/RegisterViewModel.cs deleted file mode 100644 index 5b39cbac..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/RegisterViewModel.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels -{ - /// - /// Data transfer object for user registration - /// - public class RegisterViewModel - { - /// - /// FirstName - /// - [Required] - [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)] - [Display(Name = "First Name")] - public string FirstName { get; set; } - - /// - /// LastName - /// - [Required] - [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)] - [Display(Name = "Last Name")] - public string LastName { get; set; } - - /// - /// Email - /// - [Required] - [EmailAddress] - [Display(Name = "Email")] - public string Email { get; set; } - - /// - /// Password - /// - [Required] - [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] - [DataType(DataType.Password)] - [Display(Name = "Password")] - public string Password { get; set; } - - /// - /// Password confirmation - /// - [DataType(DataType.Password)] - [Display(Name = "Confirm password")] - [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] - public string ConfirmPassword { get; set; } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/RegisterViewModelValidator.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/RegisterViewModelValidator.cs deleted file mode 100644 index caf26455..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/RegisterViewModelValidator.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Web.Mediator.Account; -using FluentValidation; - -namespace Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels -{ - /// - /// RegisterViewModel Validator - /// - public class RegisterRequestValidator : AbstractValidator - { - public RegisterRequestValidator() - { - RuleSet("default", () => - { - RuleFor(x => x.Model.Email).NotNull().EmailAddress(); - RuleFor(x => x.Model.FirstName).NotEmpty().NotNull().MaximumLength(50); - RuleFor(x => x.Model.LastName).NotEmpty().NotNull().MaximumLength(50); - RuleFor(x => x.Model.Password).NotNull().NotEmpty().MaximumLength(50); - RuleFor(x => x.Model.ConfirmPassword).NotNull().MaximumLength(50).Equal(x => x.Model.Password).When(x => !string.IsNullOrEmpty(x.Model.Password)); - }); - - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/UserProfileViewModel.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/UserProfileViewModel.cs deleted file mode 100644 index 14a1011c..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/UserProfileViewModel.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels -{ - /// - /// Application User Profile - /// - public class UserProfileViewModel - { - /// - /// Identifier - /// - public Guid Id { get; set; } - - /// - /// FirstName - /// - public string FirstName { get; set; } - - /// - /// LastName - /// - public string LastName { get; set; } - - /// - /// Email - /// - public string Email { get; set; } - - /// - /// User Roles - /// - public List Roles { get; set; } - - /// - /// User PhoneNumber - /// - public string PhoneNumber { get; set; } - - /// - /// Position Name - /// - public string PositionName { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogCreateViewModel.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogCreateViewModel.cs deleted file mode 100644 index a70bf7e0..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogCreateViewModel.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; -using Calabonga.EntityFrameworkCore.Entities.Base; -using Microsoft.Extensions.Logging; - -namespace Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels -{ - /// - /// Data Transfer Object for Log entity - /// - public class LogCreateViewModel : IViewModel - { - /// - /// Log Created At - /// - [Required] - public DateTime CreatedAt { get; set; } - - /// - /// Service name or provider - /// - [Required] - [StringLength(255)] - public string Logger { get; set; } - - /// - /// Log level for logging. See - /// - [Required] - [StringLength(50)] - public string Level { get; set; } - - /// - /// Log Message - /// - [Required] - [StringLength(4000)] - public string Message { get; set; } - - /// - /// Thread identifier - /// - public string ThreadId { get; set; } - - /// - /// Exception message - /// - public string ExceptionMessage { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogUpdateViewModel.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogUpdateViewModel.cs deleted file mode 100644 index 88a56678..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogUpdateViewModel.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels -{ - /// - /// Log View model for Update operations - /// - public class LogUpdateViewModel : ViewModelBase - { - public string Logger { get; set; } - - public string Level { get; set; } - - public string Message { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogViewModel.cs b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogViewModel.cs deleted file mode 100644 index 2d5ae4bf..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogViewModel.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace Calabonga.Microservice.IdentityModule.Web.ViewModels.LogViewModels -{ - /// - /// Log ViewModel - /// - public class LogViewModel: ViewModelBase - { - /// - /// Created at - /// - public DateTime CreatedAt { get; set; } - - /// - /// Logger name - /// - public string Logger { get; set; } - - /// - /// Level - /// - public string Level { get; set; } - - /// - /// Message text - /// - public string Message { get; set; } - - /// - /// Thread ID - /// - public string ThreadId { get; set; } - - /// - /// - /// - public string ExceptionMessage { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json deleted file mode 100644 index 1a1bae9d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=;User ID=;Password=" - }, - "Logging": { - "IncludeScopes": false, - "Debug": { - "LogLevel": { - "Default": "Warning", - "System": "Information", - "Microsoft": "Information" - } - }, - "Console": { - "LogLevel": { - "Default": "Warning", - "System": "Information", - "Microsoft": "Information" - } - } - }, - "Cors": { - "Origins": "*" - }, - "IdentityServer": { - "Url": "http://localhost:10001" - }, - "CurrentAppSettings": { - "PageSize": 50 - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.Production.json b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.Production.json deleted file mode 100644 index 0e5d7f22..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.Production.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=MicroserviceWithIdentityDb;Trusted_Connection=True;" - }, - "Logging": { - "IncludeScopes": false, - "Debug": { - "LogLevel": { - "Default": "Warning", //"Debug" - "System": "Information", - "Microsoft": "Information" - } - }, - "Console": { - "LogLevel": { - "Default": "Warning", //"Debug" - "System": "Information", - "Microsoft": "Information" - } - } - }, - "Cors": { - "Origins": "*" - }, - "IdentityServer": { - "Url": "http://localhost:4455" - }, - "CurrentAppSettings": { - "PageSize": 50 - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.json b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.json deleted file mode 100644 index d9d9a9bf..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - }, - "AllowedHosts": "*" -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk deleted file mode 100644 index 15aac77f..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk +++ /dev/null @@ -1 +0,0 @@ -{"alg":"RS256","d":"MR0gmrThHp6iHjLVL8ofRvz30UDV-L3B0QBLey15bVRo-nTDpTduvPaNDdh3WmbDCCTyoZ4dfWY3YREMtD7PeoG3otgBxnIL6ZBEwvT2QrutJnuPNQ0wU2LVQCFbNRYaA1GebDeTQt7qpUxlqx_Dm8zDoOWYw52cAjkq0UuesCq7maI0_ffGGIOyv-yyHpmVpu9c5aakmdHeP4vj9P3HrLEc8OI2RwYgH1FflIexHOs0tjmskK2TB1HwGLBlgD5YX36tAWsxLRtNxAuZdKvmQxwVqEpkffuCfm3X8LE_7J6qXxcsoVOB_oyQm_1TUocuOLwrHnFab6UITjlusPP00Q","dp":"LiHZEkcE9c_w6Wt29WfVrqd7Kr4s_q-ApWZAMqdndJqbfoGUQYQ6F0x6U8P_UkUmyJTRCtGWRjwajDZI0f6St297xjg-jSO_2rbcpqvmAdYOZEAA6OM-CDWyN7MxhHNaA_piOK7DByV3oFp7jaQ_1U5BqAPLr9vp4_nOIyhHDMM","dq":"8KFJso4RZE6hJALNTGdSHRhxC4ulQhd-jP0pPft_IGLBQe5GceX3lEGi3He2MpzxIAVQpAZ7kOkLpunMBqQ9t75ROL5jNIA8z0cIf390sdWz53A1599InL2imX8oce5IAbqBUSuIB80-CtA4HGqvttAXGQN9Au6FZWBH-E3gbZE","e":"AQAB","kid":"ED43460F57D930E62A56FC8BEEF8A283","kty":"RSA","n":"1Sne51c04wn7MwM-oyZvXs8V37s5DwzcPZyGMjLwYeM3ysuMEhdCdwlTJbsNizD8hd2Y5cS3BfZzizsHWI6-t4bIrD4ySsvj_GitY4NgoW53zBDqGzNKibeVt4zoTmp0H2RTyDj0lK-7tuEx1elUFSoaaHSImV51lm7CQz7dI8T-z2vHGN6mVCYpzR8h7Zuz0UixV5LWHI3ulYOI0IApk7obbH-2X3xHC6zEJMgPnFJ1cjXP474Y-FslF1u7Dx8h0v0zeD-fJ12P6L8Nsgo0NP_4OBAtrHFfThnugQC5WEA2mFXNMS0N_8SgLZlavv-NLNS74QXbzJC59SkGS60vZQ","p":"2rhU-K-zyaRzg9mPTeQEo5bEUIyZEGY3nQJrLDMUbXQaUZ5Np9E_pNsVPy1gEUTukV-cbjRucvpwpMSgPS2qJGBv0UGX1TmFxwvSiysbuCTlUYzdcJ9AMr1H5sPZ_ZvHdwjWcVKcmisg6A5LrKgwCELy1mAvxlvalnyajCp9Bz8","q":"-X8WBAyWajXfWbv2mbqXVJOtEdbrOMkl1IAjfeWdKQ9Ee3IeIjNtIqyIE4xW4Ftixzopk2u7Rm0MNwn1gP1DeZWyRCuHzdt0_3b5tVDK5mm3FhTrlnVsTOFg4BeYhAdc5MLOki4tHZp6o0s25-_6buATm2fN_7kCxRXsuUrZZFs","qi":"slbCpR9QO_FXiU2ciHEhtZCN4Vj4wXfTtQj2G0-WooOUSan_SFZsAXEfA-ihE0Fl1xQtcMwcMUsD9EGDDNjC_7ESlUojU_AOWRX_b8AcTJU28wqnXj4DP6gwptiywL-agwWrjnBWu8dMCogU8-hJFp3f8ruIx06hVecZXGzR-v8"} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/tempkey.rsa b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/tempkey.rsa deleted file mode 100644 index 2dbfd2b8..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/tempkey.rsa +++ /dev/null @@ -1 +0,0 @@ -{"KeyId":"YV6cLgCDMZMat6HrRL-K6g","Parameters":{"D":"KPGMhbGs2Nnl881go6X6QtFvN7x9KHAxOKIrt00GWhJ/7tZKbY/wrAimXxHWLNj/t3t0f7yY/zgTEwbXhTRY2Qz0LS2vTCc5SW/PrtKPfoAlgiaxcl3AUwzL0CG/84f1RwiarJQ139PrQLZylr5m7Chr7t8SOcx04RhliJ50afsUU2DoQ2ydNHVkNFHmD4LtKsUTe1HW2YZLhKlaaof7I/B5CYDJhOMktvssZnYn6tldaCPLFhlb2qKqJ5IIoLRbxSW49OgknBxvRPFhvuNgJy5U0G5Zj6hnGqVYkFAWpy8SvKr+y3x3utHas+5ad0Tl4Jni2oY5Hy5CsbjVJyq1XQ==","DP":"vb5xD/KvgM3vrWWvbrPHn/dkxn3v093fG3fTqusD1J8H3VSDlLAXFl1yLme3aGHFdfqU6Kh0fm2ljp1hcxzaSqIG6nm/eXtQKlPmUCfhVgaQd6kKpBTNR+fKi2GmJnYPq/j9YOtbRrvgfEOJjcr9pPnwvm462NXY/whBU20/1/U=","DQ":"KKF2T1Yjrx5x3DxY6uu5eDKCULwtOj1WcRt3sknVytVuXzdnHALQYPx3GlZGd69Os2783YTl27bA568NGdRTTDgH1WsbUEJ/L6HnmMjF2c9tFOuJTNkt9liepi1DE+vweNP47J7vC56RnB53cJxH9NrUJgwLOrduk0KOg51S9O0=","Exponent":"AQAB","InverseQ":"F/c6r8Lz5GFEvZ4pVoANwiLBJ6ygoU0epbNSJOctlh1WXSqK6vubx9kLaKXiPwvL1lKI3wLli90hS27IMQ0TGRbx2whCsQmYkQbZ/N8bQFbqLq17QGjlOtHTVyb1xVdpWBsbUsm2CyNcrcLwehNq1BQKZGhuMzRS2vjWdALWV8E=","Modulus":"ozV6PBtB42xupEMGErHRRM2BHbBie/73jtJeCiHwYkvcdQCwckO0owQZ98At0e26h8u+dyJIZsi+YteiI8eacAtqvXa0LuBV9hU5k0HSpKPuCTCfFoy1cZtNIwMRmXL41lif5lJoaye87kKZ47UpUXDX3OtC2+7Z/BCbuV7bph+fmr0HenPWy+s7kgKR0z6Zvb7DrQcbYxdm1L5Ocym3u/MjUifwNd7jpXUvzKSoKhRbY8aXa47JDzWAxZRReFQQsfsnq5bxtcFG8lyeAVsn6hLGLwtwnAx/abTTITAkKCY/DAHHg8uTr52WO9vwLbsXOP9VMMg3GaQDByzbFj1wjQ==","P":"xJrNIiraGxuADMd6GKuB1RwE8gweioaxwJzoRNVX1fupwkEBY5se9ONOUTL7De+fmvnutM/2LzvtG48HQ1m4lcW9TOVRssUmIBaae4lV2o2CHiKbVCj3K97SK/CPqwVgInyeJiE429IVMWMIJAY7E3+0Elrgyl/Vmkj38b9Ni6s=","Q":"1IPhc5uKlqkbT0bBbOkAsWwMptls8kgtFG3acWHdsIxtHVWSUImMmhEVBPjyg8Zu9I1jbWxk3BhI3aJcSMNsvqXmiCFbuNsCNY0ph6DYdSLqEHBqaY5hKPSeruMi4SEQumvUXx+pQuyIsnyJxH/T5G8qOm++GvEHsjjVlryB/Kc="}} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.sln b/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.sln deleted file mode 100644 index a149cb7e..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.sln +++ /dev/null @@ -1,43 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29324.140 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.IdentityModule.Web", "Calabonga.Microservice.IdentityModule.Web\Calabonga.Microservice.IdentityModule.Web.csproj", "{3E88A8C5-EEEE-4ACE-BF86-BCD86EC3D9AD}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.IdentityModule.Core", "Calabonga.Microservice.IdentityModule.Core\Calabonga.Microservice.IdentityModule.Core.csproj", "{0F6F76E6-CAE0-44D1-A58F-015D9A77C4CD}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.IdentityModule.Entities", "Calabonga.Microservice.IdentityModule.Models\Calabonga.Microservice.IdentityModule.Entities.csproj", "{B0CD0126-151C-47F6-8C64-DFBA56098C69}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.IdentityModule.Data", "Calabonga.Microservice.IdentityModule.Data\Calabonga.Microservice.IdentityModule.Data.csproj", "{96370E1A-425A-4E25-A783-9D59B42ADB83}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {3E88A8C5-EEEE-4ACE-BF86-BCD86EC3D9AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3E88A8C5-EEEE-4ACE-BF86-BCD86EC3D9AD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3E88A8C5-EEEE-4ACE-BF86-BCD86EC3D9AD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3E88A8C5-EEEE-4ACE-BF86-BCD86EC3D9AD}.Release|Any CPU.Build.0 = Release|Any CPU - {0F6F76E6-CAE0-44D1-A58F-015D9A77C4CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0F6F76E6-CAE0-44D1-A58F-015D9A77C4CD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0F6F76E6-CAE0-44D1-A58F-015D9A77C4CD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0F6F76E6-CAE0-44D1-A58F-015D9A77C4CD}.Release|Any CPU.Build.0 = Release|Any CPU - {B0CD0126-151C-47F6-8C64-DFBA56098C69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B0CD0126-151C-47F6-8C64-DFBA56098C69}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B0CD0126-151C-47F6-8C64-DFBA56098C69}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B0CD0126-151C-47F6-8C64-DFBA56098C69}.Release|Any CPU.Build.0 = Release|Any CPU - {96370E1A-425A-4E25-A783-9D59B42ADB83}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {96370E1A-425A-4E25-A783-9D59B42ADB83}.Debug|Any CPU.Build.0 = Debug|Any CPU - {96370E1A-425A-4E25-A783-9D59B42ADB83}.Release|Any CPU.ActiveCfg = Release|Any CPU - {96370E1A-425A-4E25-A783-9D59B42ADB83}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {C1ED467B-6F53-4A1D-9226-354F0618F23F} - EndGlobalSection -EndGlobal diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/AppData.Common.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/AppData.Common.cs deleted file mode 100644 index fe414a58..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/AppData.Common.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Collections.Generic; - -namespace Calabonga.Microservice.Module.Core -{ - /// - /// Static data container - /// - public static partial class AppData - { - /// - /// Current service name - /// - public const string ServiceName = "Module"; - - /// - /// "SystemAdministrator" - /// - public const string SystemAdministratorRoleName = "Administrator"; - - /// - /// "BusinessOwner" - /// - public const string ManagerRoleName = "Manager"; - - /// - /// Roles - /// - public static IEnumerable Roles - { - get - { - yield return SystemAdministratorRoleName; - yield return ManagerRoleName; - } - } - - /// - /// IdentityServer4 path - /// - public const string AuthUrl = "/auth"; - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/AppData.Exceptions.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/AppData.Exceptions.cs deleted file mode 100644 index f56ce9fd..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/AppData.Exceptions.cs +++ /dev/null @@ -1,61 +0,0 @@ -namespace Calabonga.Microservice.Module.Core -{ - public static partial class AppData - { - /// - /// Exception messages - /// - public static class Exceptions - { - /// - /// "An exception was thrown" - /// - public static string ThrownException => "An exception was thrown"; - - /// - /// "Invalid cast exception" - /// - public static string TypeConverterException => "Invalid cast exception"; - - /// - /// "User not registered in the system" - /// - public static string UserNotFoundException => "User not registered in the system"; - - /// - /// "Object not found" - /// - public static string NotFoundException => "Object not found"; - - /// - /// "Unauthorized access denied" - /// - public static string UnauthorizedException => "Unauthorized access denied"; - - /// - /// "Argument null exception" - /// - public static string ArgumentNullException => "Argument null exception"; - - /// - /// "File already exists" - /// - public static string FileAlreadyExists => "File already exists"; - - /// - /// "Email Service Unavailable or SMTP provider error occupied" - /// - public static string EmailServiceUnavailable => "Email Service Unavailable or SMTP provider error occupied"; - - /// - /// "Some errors occurred while checking the entity" - /// - public static string EntityValidationException => "Some errors occurred while checking the entity"; - - /// - /// "Invalid operation exception was thrown" - /// - public static string InvalidOperationException => "Invalid operation exception was thrown"; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/AppData.Messages.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/AppData.Messages.cs deleted file mode 100644 index f8b549ea..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/AppData.Messages.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace Calabonga.Microservice.Module.Core -{ - public static partial class AppData - { - /// - /// Common messages - /// - public static class Messages - { - - /// - /// "Entity successfully deleted" - /// - public static string EntitySuccessfullyDeleted => "Entity successfully deleted"; - - /// - /// "Automatically generated by {0}" - /// - public static string ViewModelFactoryGenerationText => "Automatically generated by {0}"; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Calabonga.Microservice.Module.Core.csproj b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Calabonga.Microservice.Module.Core.csproj deleted file mode 100644 index cb631906..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Calabonga.Microservice.Module.Core.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - - - netcoreapp3.1 - - - diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/EmailMessage.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/EmailMessage.cs deleted file mode 100644 index e4f5a25c..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/EmailMessage.cs +++ /dev/null @@ -1,37 +0,0 @@ -namespace Calabonga.Microservice.Module.Core -{ - /// - /// Mail Message to send - /// - public class EmailMessage : IEmailMessage - { - - /// - public EmailMessage() - { - Result = new SendEmailResult(); - } - - /// - public string MailTo { get; set; } - - /// - public string Subject { get; set; } - - /// - public string Body { get; set; } - - /// - /// Sent result info - /// - public SendEmailResult Result { get; } - - /// - /// Use HTML in the Body - /// - public bool IsHtml { get; set; } - - /// - public string MailFrom { get; set; } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceArgumentNullException.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceArgumentNullException.cs deleted file mode 100644 index 28edf74e..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceArgumentNullException.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; - -namespace Calabonga.Microservice.Module.Core.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceArgumentNullException : Exception - { - public MicroserviceArgumentNullException() : base(AppData.Exceptions.ArgumentNullException) - { - - } - - public MicroserviceArgumentNullException(string message) : base(message) - { - - } - - public MicroserviceArgumentNullException(string message, Exception exception) : base(message, exception) - { - - } - - public MicroserviceArgumentNullException(Exception exception) : base(AppData.Exceptions.ArgumentNullException, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceEntityValidationException.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceEntityValidationException.cs deleted file mode 100644 index 883b0ba1..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceEntityValidationException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace Calabonga.Microservice.Module.Core.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceEntityValidationException : Exception - { - public MicroserviceEntityValidationException() : base(AppData.Exceptions.EntityValidationException) - { - - } - - public MicroserviceEntityValidationException(string message) : base(message) - { - - } - - public MicroserviceEntityValidationException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceException.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceException.cs deleted file mode 100644 index 7f843783..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace Calabonga.Microservice.Module.Core.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceException : Exception - { - public MicroserviceException() : base(AppData.Exceptions.ThrownException) - { - - } - - public MicroserviceException(string message) : base(message) - { - - } - - public MicroserviceException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceFileAlreadyExistsException.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceFileAlreadyExistsException.cs deleted file mode 100644 index c0245039..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceFileAlreadyExistsException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace Calabonga.Microservice.Module.Core.Exceptions -{ - /// - /// FileAlreadyExists - /// - public class MicroserviceFileAlreadyExistsException : Exception - { - public MicroserviceFileAlreadyExistsException() : base(AppData.Exceptions.FileAlreadyExists) - { - - } - - public MicroserviceFileAlreadyExistsException(string message) : base(message) - { - - } - - public MicroserviceFileAlreadyExistsException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceInvalidCastException.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceInvalidCastException.cs deleted file mode 100644 index 160a5120..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceInvalidCastException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace Calabonga.Microservice.Module.Core.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceInvalidCastException : Exception - { - public MicroserviceInvalidCastException() : base(AppData.Exceptions.TypeConverterException) - { - - } - - public MicroserviceInvalidCastException(string message) : base(message) - { - - } - - public MicroserviceInvalidCastException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceInvalidOperationException.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceInvalidOperationException.cs deleted file mode 100644 index afa1bc1b..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceInvalidOperationException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace Calabonga.Microservice.Module.Core.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceInvalidOperationException : Exception - { - public MicroserviceInvalidOperationException() : base(AppData.Exceptions.InvalidOperationException) - { - - } - - public MicroserviceInvalidOperationException(string message) : base(message) - { - - } - - public MicroserviceInvalidOperationException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceNotFoundException.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceNotFoundException.cs deleted file mode 100644 index 512a0f47..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceNotFoundException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace Calabonga.Microservice.Module.Core.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceNotFoundException : Exception - { - public MicroserviceNotFoundException() : base(AppData.Exceptions.NotFoundException) - { - - } - - public MicroserviceNotFoundException(string message) : base(message) - { - - } - - public MicroserviceNotFoundException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceUnauthorizedException.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceUnauthorizedException.cs deleted file mode 100644 index 62b356bb..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceUnauthorizedException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace Calabonga.Microservice.Module.Core.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceUnauthorizedException : Exception - { - public MicroserviceUnauthorizedException() : base(AppData.Exceptions.UnauthorizedException) - { - - } - - public MicroserviceUnauthorizedException(string message) : base(message) - { - - } - - public MicroserviceUnauthorizedException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceUserNotFoundException.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceUserNotFoundException.cs deleted file mode 100644 index a473b43b..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceUserNotFoundException.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; - -namespace Calabonga.Microservice.Module.Core.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceUserNotFoundException : Exception - { - public MicroserviceUserNotFoundException() : base(AppData.Exceptions.UserNotFoundException) - { - - } - - public MicroserviceUserNotFoundException(string message) : base(message) - { - } - - public MicroserviceUserNotFoundException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/IMailMessage.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/IMailMessage.cs deleted file mode 100644 index b6fbbeb6..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/IMailMessage.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace Calabonga.Microservice.Module.Core -{ - /// - /// Mail message interface - /// - public interface IEmailMessage - { - /// - /// Mail to - /// - string MailTo { get; set; } - - /// - /// Mail from - /// - string MailFrom { get; set; } - - /// - /// Subject or title of the message - /// - string Subject { get; set; } - - /// - /// Message content - /// - string Body { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/SendEmailResult.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/SendEmailResult.cs deleted file mode 100644 index 0c96d9e7..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/SendEmailResult.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace Calabonga.Microservice.Module.Core -{ - /// - /// MailKit send result - /// - public class SendEmailResult - { - /// - /// Indicate mail sent - /// - public bool IsSent { get; set; } - - /// - /// Indicate sending in process - /// - public bool IsInProcess { get; set; } - - /// - /// Exception while sending - /// - public Exception Exception { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/StringExtensions.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/StringExtensions.cs deleted file mode 100644 index 3b84b21c..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Core/StringExtensions.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Diagnostics; -using System.Globalization; -using System.Text.RegularExpressions; - -namespace Calabonga.Microservice.Module.Core -{ - public static class StringExtensions - { - private static readonly Regex WebUrlExpression = new Regex(@"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)", RegexOptions.Singleline | RegexOptions.Compiled); - private static readonly Regex EmailExpression = new Regex(@"^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$", RegexOptions.Singleline | RegexOptions.Compiled); - private static readonly Regex StripHtmlExpression = new Regex("<\\S[^><]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled); - - [DebuggerStepThrough] - public static Guid ToGuid(this string value) - { - Guid.TryParse(value, out var result); - return result; - } - - [DebuggerStepThrough] - public static bool IsWebUrl(this string target) - { - return !string.IsNullOrEmpty(target) && WebUrlExpression.IsMatch(target); - } - - [DebuggerStepThrough] - public static bool IsEmail(this string target) - { - return !string.IsNullOrEmpty(target) && EmailExpression.IsMatch(target); - } - - [DebuggerStepThrough] - public static string NullSafe(this string target) - { - return (target ?? string.Empty).Trim(); - } - - [DebuggerStepThrough] - public static string FormatWith(this string target, params object[] args) - { - if (target == null) { return string.Empty; } - return string.Format(CultureInfo.CurrentCulture, target, args); - } - - [DebuggerStepThrough] - public static string StripHtml(this string target) - { - return StripHtmlExpression.Replace(target, string.Empty); - } - - - [DebuggerStepThrough] - public static T ToEnum(this string target, T defaultValue) where T : IComparable, IFormattable - { - T convertedValue = defaultValue; - - if (!string.IsNullOrEmpty(target)) - { - try - { - convertedValue = (T)Enum.Parse(typeof(T), target.Trim(), true); - } - catch (ArgumentException) - { - } - } - - return convertedValue; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/ApplicationDbContext.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/ApplicationDbContext.cs deleted file mode 100644 index 6a1d50e2..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/ApplicationDbContext.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Calabonga.Microservice.Module.Data.Base; -using Calabonga.Microservice.Module.Entities; -using Microsoft.EntityFrameworkCore; - -namespace Calabonga.Microservice.Module.Data -{ - /// - /// Database for application - /// - public class ApplicationDbContext : DbContextBase, IApplicationDbContext - { - /// - public ApplicationDbContext(DbContextOptions options) : base(options) - { - } - - #region System - - public DbSet Logs { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/Base/DbContextBase.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/Base/DbContextBase.cs deleted file mode 100644 index d03da66d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/Base/DbContextBase.cs +++ /dev/null @@ -1,262 +0,0 @@ -using System; -using System.Linq; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -using Calabonga.EntityFrameworkCore.Entities.Base; -using Calabonga.UnitOfWork; -using Microsoft.EntityFrameworkCore; - -namespace Calabonga.Microservice.Module.Data.Base -{ - /// - /// Base DbContext with predefined configuration - /// - public abstract class DbContextBase : DbContext where TContext : DbContext - { - private const string DefaultUserName = "Anonymous"; - - protected DbContextBase( DbContextOptions options): base(options) - { - LastSaveChangesResult = new SaveChangesResult(); - } - - public SaveChangesResult LastSaveChangesResult { get; } - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - /// - /// Saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// The number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override int SaveChanges(bool acceptAllChangesOnSuccess) - { - try - { - DbSaveChanges(); - return base.SaveChanges(acceptAllChangesOnSuccess); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - public override int SaveChanges() - { - try - { - DbSaveChanges(); - return base.SaveChanges(); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - private void DbSaveChanges() - { - var createdEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added); - foreach (var entry in createdEntries) - { - if (!(entry.Entity is IAuditable)) - { - continue; - } - - var creationDate = DateTime.Now.ToUniversalTime(); - var userName = entry.Property("CreatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("CreatedBy").CurrentValue; - var updatedAt = entry.Property("UpdatedAt").CurrentValue; - var createdAt = entry.Property("CreatedAt").CurrentValue; - if (createdAt != null) - { - if (DateTime.Parse(createdAt.ToString()).Year > 1970) - { - entry.Property("CreatedAt").CurrentValue = ((DateTime)createdAt).ToUniversalTime(); - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - - if (updatedAt != null) - { - if (DateTime.Parse(updatedAt.ToString()).Year > 1970) - { - entry.Property("UpdatedAt").CurrentValue = ((DateTime)updatedAt).ToUniversalTime(); - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - - entry.Property("CreatedBy").CurrentValue = userName; - entry.Property("UpdatedBy").CurrentValue = userName; - - LastSaveChangesResult.AddMessage($"ChangeTracker has new entities: {entry.Entity.GetType()}"); - } - - var updatedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified); - foreach (var entry in updatedEntries) - { - if (entry.Entity is IAuditable) - { - var userName = entry.Property("UpdatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("UpdatedBy").CurrentValue; - entry.Property("UpdatedAt").CurrentValue = DateTime.Now.ToUniversalTime(); - entry.Property("UpdatedBy").CurrentValue = userName; - } - - LastSaveChangesResult.AddMessage($"ChangeTracker has modified entities: {entry.Entity.GetType()}"); - } - } - - /// - /// Configures the schema needed for the identity framework. - /// - /// - /// The builder being used to construct the model for this context. - /// - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - var applyGenericMethod = typeof(ModelBuilder).GetMethods(BindingFlags.Instance | BindingFlags.Public).First(x => x.Name == "ApplyConfiguration"); - foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters)) - { - foreach (var item in type.GetInterfaces()) - { - if (!item.IsConstructedGenericType || item.GetGenericTypeDefinition() != typeof(IEntityTypeConfiguration<>)) - { - continue; - } - - var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(item.GenericTypeArguments[0]); - applyConcreteMethod.Invoke(builder, new[] { Activator.CreateInstance(type) }); - break; - } - } - - builder.EnableAutoHistory(2048); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/Calabonga.Microservice.Module.Data.csproj b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/Calabonga.Microservice.Module.Data.csproj deleted file mode 100644 index c25ae681..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/Calabonga.Microservice.Module.Data.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - netcoreapp3.1 - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/DatabaseInitialization/DatabaseInitializer.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/DatabaseInitialization/DatabaseInitializer.cs deleted file mode 100644 index af699fee..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/DatabaseInitialization/DatabaseInitializer.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.Module.Data.DatabaseInitialization -{ - /// - /// Database Initializer - /// - public static class DatabaseInitializer - { - public static async void Seed(IServiceProvider serviceProvider) - { - using var scope = serviceProvider.CreateScope(); - await using var context = scope.ServiceProvider.GetService(); - - // Should be uncomment when using UseSqlServer() settings or any other provider. - // This is should not be used when UseInMemoryDatabase() - // context.Database.Migrate(); - - // TODO: Add your seed data here - - if (context.ChangeTracker.HasChanges()) - { - await context.SaveChangesAsync(); - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/IApplicaitonDbContext.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/IApplicaitonDbContext.cs deleted file mode 100644 index d1203fb1..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/IApplicaitonDbContext.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Calabonga.Microservice.Module.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.ChangeTracking; -using Microsoft.EntityFrameworkCore.Infrastructure; - -namespace Calabonga.Microservice.Module.Data -{ - /// - /// Abstraction for Database (EntityFramework) - /// - public interface IApplicationDbContext - { - #region System - - DbSet Logs { get; set; } - - DatabaseFacade Database { get; } - - ChangeTracker ChangeTracker { get; } - - DbSet Set() where TEntity : class; - - DbQuery Query() where TQuery : class; - - int SaveChanges(); - - #endregion - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/ModelConfigurations/Base/AuditableModelConfigurationBase.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/ModelConfigurations/Base/AuditableModelConfigurationBase.cs deleted file mode 100644 index 897bdfdb..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/ModelConfigurations/Base/AuditableModelConfigurationBase.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Calabonga.Microservice.Module.Data.ModelConfigurations.Base -{ - /// - /// Audit-able Model Configuration base - /// - /// - public abstract class AuditableModelConfigurationBase : IEntityTypeConfiguration where T : Auditable - { - public void Configure(EntityTypeBuilder builder) - { - builder.ToTable(TableName()); - builder.HasKey(x => x.Id); - builder.Property(x => x.Id).IsRequired(); - - // audit - builder.Property(x => x.CreatedAt).IsRequired().HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)).IsRequired(); - builder.Property(x => x.CreatedBy).HasMaxLength(256).IsRequired(); - builder.Property(x => x.UpdatedAt).HasConversion(v => v.Value, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); - builder.Property(x => x.UpdatedBy).HasMaxLength(256); - - AddBuilder(builder); - } - - /// - /// Add custom properties for your entity - /// - /// - protected abstract void AddBuilder(EntityTypeBuilder builder); - - /// - /// Table name - /// - /// - protected abstract string TableName(); - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/ModelConfigurations/Base/IdentityModelConfigurationBase.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/ModelConfigurations/Base/IdentityModelConfigurationBase.cs deleted file mode 100644 index 4523f16d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/ModelConfigurations/Base/IdentityModelConfigurationBase.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Calabonga.EntityFrameworkCore.Entities.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Calabonga.Microservice.Module.Data.ModelConfigurations.Base -{ - /// - /// Audit-able Model Configuration base - /// - /// - public abstract class IdentityModelConfigurationBase : IEntityTypeConfiguration where T : Identity - { - public void Configure(EntityTypeBuilder builder) - { - builder.ToTable(TableName()); - builder.HasKey(x => x.Id); - builder.Property(x => x.Id).IsRequired(); - - AddBuilder(builder); - } - - /// - /// Add custom properties for your entity - /// - /// - protected abstract void AddBuilder(EntityTypeBuilder builder); - - /// - /// Table name - /// - /// - protected abstract string TableName(); - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/ModelConfigurations/LogModelConfiguration.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/ModelConfigurations/LogModelConfiguration.cs deleted file mode 100644 index 531c8cdc..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Data/ModelConfigurations/LogModelConfiguration.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using Calabonga.Microservice.Module.Data.ModelConfigurations.Base; -using Calabonga.Microservice.Module.Entities; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace Calabonga.Microservice.Module.Data.ModelConfigurations -{ - /// - /// Entity Type Configuration for Log entity - /// - public class LogModelConfiguration : IdentityModelConfigurationBase - { - protected override void AddBuilder(EntityTypeBuilder builder) - { - builder.Property(x => x.Logger).HasMaxLength(255).IsRequired(); - builder.Property(x => x.Level).HasMaxLength(50).IsRequired(); - builder.Property(x => x.Message).HasMaxLength(4000).IsRequired(); - builder.Property(x => x.CreatedAt).HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)).IsRequired(); - builder.Property(x => x.ThreadId).HasMaxLength(255); - builder.Property(x => x.ExceptionMessage).HasMaxLength(2000); - } - - protected override string TableName() - { - return "Logs"; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Entities/Calabonga.Microservice.Module.Entities.csproj b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Entities/Calabonga.Microservice.Module.Entities.csproj deleted file mode 100644 index 6c99e22e..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Entities/Calabonga.Microservice.Module.Entities.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - netcoreapp3.1 - - - - - - - - - - - diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Entities/Log.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Entities/Log.cs deleted file mode 100644 index cb58aa86..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Entities/Log.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace Calabonga.Microservice.Module.Entities -{ - /// - /// Logs - /// - public class Log : Identity - { - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } - - public string Level { get; set; } - - public string Message { get; set; } - - public string ThreadId { get; set; } - - public string ExceptionMessage { get; set; } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesAuthentication.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesAuthentication.cs deleted file mode 100644 index f9c0bec8..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesAuthentication.cs +++ /dev/null @@ -1,42 +0,0 @@ -using Calabonga.Microservice.Module.Core; -using IdentityServer4.AccessTokenValidation; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.Module.Web.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesAuthentication - { - /// - /// ConfigureServices Services - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - var url = configuration.GetSection("IdentityServer").GetValue("Url"); - - services - .AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; - }) - .AddIdentityServerAuthentication(options => - { - options.SupportedTokens = SupportedTokens.Jwt; - options.Authority = $"{url}{AppData.AuthUrl}"; - options.EnableCaching = true; - options.RequireHttpsMetadata = false; - }); - - services.AddAuthorization(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesBase.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesBase.cs deleted file mode 100644 index f808d298..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesBase.cs +++ /dev/null @@ -1,49 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.Module.Data; -using Calabonga.Microservice.Module.Web.Extensions; -using Calabonga.Microservice.Module.Web.Infrastructure.Settings; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.Module.Web.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesBase - { - /// - /// ConfigureServices Services - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - services.AddDbContextPool(config => - { - // UseInMemoryDatabase - This for demo purposes only! - // Should uninstall package "Microsoft.EntityFrameworkCore.InMemory" and install what you need. - // For example: "Microsoft.EntityFrameworkCore.SqlServer" - // uncomment line below to use UseSqlServer(). Don't forget setup connection string in appSettings.json - config.UseInMemoryDatabase("DEMO_PURPOSES_ONLY"); - // config.UseSqlServer(configuration.GetConnectionString(nameof(ApplicationDbContext))); - }); - - services.AddAutoMapper(typeof(Startup)); - services.AddControllers(); - services.AddUnitOfWork(); - services.AddMemoryCache(); - services.AddRouting(); - services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); - services.AddOptions(); - services.Configure(configuration.GetSection(nameof(CurrentAppSettings))); - services.Configure(options => options.UseRouteSlugify()); - services.AddLocalization(); - services.AddHttpContextAccessor(); - services.AddResponseCaching(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesControllers.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesControllers.cs deleted file mode 100644 index 1d991a00..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesControllers.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Calabonga.AspNetCore.Controllers.Extensions; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.Module.Web.AppStart.ConfigureServices -{ - /// - /// Configure controllers - /// - public static class ConfigureServicesControllers - { - /// - /// Configure services - /// - /// - public static void ConfigureServices(IServiceCollection services) - { - services.AddControllers(); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesCors.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesCors.cs deleted file mode 100644 index ff717f31..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesCors.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.Linq; -using Calabonga.Microservices.Web.Core; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.Module.Web.AppStart.ConfigureServices -{ - /// - /// Cors configurations - /// - public class ConfigureServicesCors - { - /// - /// ConfigureServices - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - var origins = configuration.GetSection("Cors")?.GetSection("Origins")?.Value?.Split(','); - services.AddCors(options => - { - options.AddPolicy("CorsPolicy", builder => - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - if (origins != null && origins.Length > 0) - { - if (origins.Contains("*")) - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - builder.SetIsOriginAllowed(host => true); - builder.AllowCredentials(); - } - else - { - foreach (var origin in origins) - { - builder.WithOrigins(origin); - } - } - } - }); - }); - - services.UseMicroserviceAuthorizationPolicy(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesMediator.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesMediator.cs deleted file mode 100644 index 6db0d842..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesMediator.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Calabonga.AspNetCore.Controllers.Extensions; -using Calabonga.Microservice.Module.Web.Mediator.Behaviors; -using MediatR; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.Module.Web.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesMediator - { - /// - /// ConfigureServices Services - /// - /// - public static void ConfigureServices(IServiceCollection services) - { - services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>)); - services.AddCommandAndQueries(typeof(Startup).Assembly); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesSwagger.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesSwagger.cs deleted file mode 100644 index 5243b907..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesSwagger.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Calabonga.Microservice.Module.Web.AppStart.SwaggerFilters; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerUI; - -namespace Calabonga.Microservice.Module.Web.AppStart.ConfigureServices -{ - /// - /// Swagger configuration - /// - public static class ConfigureServicesSwagger - { - private const string AppTitle = "Microservice API"; - private static readonly string AppVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - private const string SwaggerConfig = "/swagger/v1/swagger.json"; - private const string SwaggerUrl = "api/manual"; - - /// - /// ConfigureServices Swagger services - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - services.AddSwaggerGen(options => - { - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = AppTitle, - Version = AppVersion, - Description = "Microservice API module API documentation. This template based on ASP.NET Core 3.1." - }); - options.ResolveConflictingActions(x => x.First()); - - var url = configuration.GetSection("IdentityServer").GetValue("Url"); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - Password = new OpenApiOAuthFlow - { - TokenUrl = new Uri($"{url}/auth/connect/token", UriKind.Absolute), - Scopes = new Dictionary - { - { "api1", "Default scope" } - } - } - } - }); - - options.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "oauth2" - }, - Scheme = "oauth2", - Name = "Bearer", - In = ParameterLocation.Header, - - }, - new List() - } - }); - - options.OperationFilter(); - }); - } - - /// - /// Set up some properties for swagger UI - /// - /// - public static void SwaggerSettings(SwaggerUIOptions settings) - { - settings.SwaggerEndpoint(SwaggerConfig, $"{AppTitle} v.{AppVersion}"); - settings.RoutePrefix = SwaggerUrl; - settings.DocumentTitle = "Microservice API"; - settings.DefaultModelExpandDepth(0); - settings.DefaultModelRendering(ModelRendering.Model); - settings.DefaultModelsExpandDepth(0); - settings.DocExpansion(DocExpansion.None); - settings.OAuthClientId("microservice1"); - settings.OAuthScopeSeparator(" "); - settings.OAuthClientSecret("secret"); - settings.DisplayRequestDuration(); - settings.OAuthAppName("Microservice API module API documentation"); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesValidators.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesValidators.cs deleted file mode 100644 index 96a2444f..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesValidators.cs +++ /dev/null @@ -1,20 +0,0 @@ -using FluentValidation; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.Module.Web.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesValidators - { - /// - /// ConfigureServices Services - /// - /// - public static void ConfigureServices(IServiceCollection services) - { - services.AddValidatorsFromAssembly(typeof(Startup).Assembly); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/Configures/ConfigureCommon.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/Configures/ConfigureCommon.cs deleted file mode 100644 index 5972b88a..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/Configures/ConfigureCommon.cs +++ /dev/null @@ -1,54 +0,0 @@ -using Calabonga.Microservice.Module.Web.AppStart.ConfigureServices; -using Calabonga.Microservice.Module.Web.Middlewares; -using Calabonga.Microservices.Web.Core; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; - -namespace Calabonga.Microservice.Module.Web.AppStart.Configures -{ - /// - /// Pipeline configuration - /// - public static class ConfigureCommon - { - /// - /// Configure pipeline - /// - /// - /// - /// - public static void Configure(IApplicationBuilder app, IWebHostEnvironment env, AutoMapper.IConfigurationProvider mapper) - { - if (env.IsDevelopment()) - { - mapper.AssertConfigurationIsValid(); - app.UseDeveloperExceptionPage(); - } - else - { - mapper.CompileMappings(); - } - - app.UseDefaultFiles(); - app.UseStaticFiles(new StaticFileOptions - { - OnPrepareResponse = ctx => - { - ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=600"); - } - }); - - app.UseResponseCaching(); - app.UseETagger(); - app.UseMiddleware(typeof(ErrorHandlingMiddleware)); - app.UseSwagger(); - app.UseSwaggerUI(ConfigureServicesSwagger.SwaggerSettings); - - // Singleton setup for User Identity - UserIdentity.Instance.Configure(app.ApplicationServices.GetService()); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/Configures/ConfigureEndpoints.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/Configures/ConfigureEndpoints.cs deleted file mode 100644 index cb66473d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/Configures/ConfigureEndpoints.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.AspNetCore.Builder; - -namespace Calabonga.Microservice.Module.Web.AppStart.Configures -{ - /// - /// Configure pipeline - /// - public static class ConfigureEndpoints - { - /// - /// Configure Routing - /// - /// - public static void Configure(IApplicationBuilder app) - { - app.UseRouting(); - app.UseCors("CorsPolicy"); - app.UseAuthentication(); - app.UseAuthorization(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/SwaggerFilters/ApplySummariesOperationFilter.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/SwaggerFilters/ApplySummariesOperationFilter.cs deleted file mode 100644 index 49292a78..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/AppStart/SwaggerFilters/ApplySummariesOperationFilter.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Calabonga.Microservice.Module.Web.AppStart.SwaggerFilters -{ - /// - /// Swagger Method Info Generator from summary for - /// - public class ApplySummariesOperationFilter : IOperationFilter - { - /// - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var controllerActionDescriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor; - if (controllerActionDescriptor == null) - { - return; - } - - var actionName = controllerActionDescriptor.ActionName; - if (actionName != "GetPaged") return; - var resourceName = controllerActionDescriptor.ControllerName; - operation.Summary = $"Returns paged list of the {resourceName} as IPagedList wrapped with OperationResult"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj deleted file mode 100644 index 4bb54dc2..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj +++ /dev/null @@ -1,50 +0,0 @@ - - - - netcoreapp3.1 - - - - - - - - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Controllers/LogsReadonly2Controller.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Controllers/LogsReadonly2Controller.cs deleted file mode 100644 index 116ed869..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Controllers/LogsReadonly2Controller.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Security.Claims; -using AutoMapper; -using Calabonga.Microservice.Module.Data; -using Calabonga.Microservice.Module.Entities; -using Calabonga.Microservice.Module.Web.Infrastructure.Settings; -using Calabonga.Microservice.Module.Web.ViewModels.LogViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.Microservices.Core.Validators; -using Calabonga.UnitOfWork; -using Calabonga.UnitOfWork.Controllers.Controllers; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Options; - -namespace Calabonga.Microservice.Module.Web.Controllers -{ - /// - /// ReadOnlyController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsReadonly2Controller : ReadOnlyController - { - private readonly CurrentAppSettings _appSettings; - - /// - public LogsReadonly2Controller( - IOptions appSettings, - IUnitOfWork unitOfWork, - IMapper mapper) - : base(unitOfWork, mapper) - { - _appSettings = appSettings.Value; - } - - [HttpGet("user-roles")] - [Authorize(Policy = "Logs:UserRoles:View")] - public IActionResult Get() - { - //Get Roles for current user - var roles = ClaimsHelper.GetValues((ClaimsIdentity)User.Identity, "role"); - return Ok($"Current user ({User.Identity.Name}) have following roles: {string.Join("|", roles)}"); - } - - /// - protected override PermissionValidationResult ValidateQueryParams(PagedListQueryParams queryParams) - { - if (queryParams.PageSize <= 0) - { - queryParams.PageSize = _appSettings.PageSize; - } - return new PermissionValidationResult(); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Controllers/LogsReadonlyController.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Controllers/LogsReadonlyController.cs deleted file mode 100644 index 765fc6cd..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Controllers/LogsReadonlyController.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Threading.Tasks; -using Calabonga.Microservice.Module.Core; -using Calabonga.Microservice.Module.Web.Mediator.LogsReadonly; -using Calabonga.Microservices.Core.QueryParams; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.Module.Web.Controllers -{ - /// - /// ReadOnlyController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsReadonlyController : ControllerBase - { - private readonly IMediator _mediator; - - public LogsReadonlyController(IMediator mediator) - { - _mediator = mediator; - } - - [HttpGet("[action]")] - [Authorize(Policy = "Logs:UserRoles:View", Roles = AppData.SystemAdministratorRoleName)] - public async Task GetRoles() - { - //Get Roles for current user - return Ok(await _mediator.Send(new GetRolesRequest(), HttpContext.RequestAborted)); - } - - [HttpGet("[action]/{id:guid}")] - [ProducesResponseType(200)] - public async Task GetById(Guid id) - { - return Ok(await _mediator.Send(new LogGetByIdRequest(id), HttpContext.RequestAborted)); - } - - - [HttpGet("[action]")] - [ProducesResponseType(200)] - public async Task GetPaged([FromQuery] PagedListQueryParams queryParams) - { - return Ok(await _mediator.Send(new LogGetPagedRequest(queryParams), HttpContext.RequestAborted)); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Controllers/LogsWritable2Controller.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Controllers/LogsWritable2Controller.cs deleted file mode 100644 index 9096f10c..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Controllers/LogsWritable2Controller.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Threading.Tasks; -using AutoMapper; -using Calabonga.Microservice.Module.Data; -using Calabonga.Microservice.Module.Entities; -using Calabonga.Microservice.Module.Web.Infrastructure.Settings; -using Calabonga.Microservice.Module.Web.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.Microservices.Core.Validators; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using Calabonga.UnitOfWork.Controllers.Controllers; -using Calabonga.UnitOfWork.Controllers.Factories; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Options; - -namespace Calabonga.Microservice.Module.Web.Controllers -{ - /// - /// WritableController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsWritable2Controller : WritableController - { - private readonly CurrentAppSettings _appSettings; - - /// - public LogsWritable2Controller( - IOptions appSettings, - IEntityManagerFactory entityManagerFactory, - IUnitOfWork unitOfWork, - IMapper mapper) - : base(entityManagerFactory, unitOfWork, mapper) - { - _appSettings = appSettings.Value; - } - - /// - [Authorize(Policy = "LogsWritable:GetCreateViewModelAsync:View")] - public override Task>> GetViewmodelForCreation() - { - return base.GetViewmodelForCreation(); - } - - /// - protected override PermissionValidationResult ValidateQueryParams(PagedListQueryParams queryParams) - { - if (queryParams.PageSize <= 0) - { - queryParams.PageSize = _appSettings.PageSize; - } - return new PermissionValidationResult(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Controllers/LogsWritableController.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Controllers/LogsWritableController.cs deleted file mode 100644 index 5fe30eaf..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Controllers/LogsWritableController.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.Threading.Tasks; -using Calabonga.Microservice.Module.Web.Mediator.LogsReadonly; -using Calabonga.Microservice.Module.Web.Mediator.LogsWritable; -using Calabonga.Microservice.Module.Web.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.QueryParams; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.Module.Web.Controllers -{ - /// - /// WritableController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsWritableController : ControllerBase - { - private readonly IMediator _mediator; - - public LogsWritableController(IMediator mediator) - { - _mediator = mediator; - } - - - [HttpGet("[action]/{id:guid}")] - [ProducesResponseType(200)] - public async Task GetById(Guid id) - { - return Ok(await _mediator.Send(new LogGetByIdRequest(id), HttpContext.RequestAborted)); - } - - - [HttpGet("[action]")] - [ProducesResponseType(200)] - public async Task GetPaged([FromQuery] PagedListQueryParams queryParams) - { - return Ok(await _mediator.Send(new LogGetPagedRequest(queryParams), HttpContext.RequestAborted)); - } - - [HttpGet("[action]")] - public async Task GetViewmodelForCreation() - { - return Ok(await _mediator.Send(new LogCreateViewModelRequest(), HttpContext.RequestAborted)); - } - - [HttpGet("[action]/{id:guid}")] - public async Task GetViewmodelForEditing(Guid id) - { - return Ok(await _mediator.Send(new LogUpdateViewModelRequest(id), HttpContext.RequestAborted)); - } - - [HttpPost("[action]")] - public async Task PostItem([FromBody]LogCreateViewModel model) - { - return Ok(await _mediator.Send(new LogPostItemRequest(model), HttpContext.RequestAborted)); - } - - [HttpPut("[action]")] - public async Task PutItem([FromBody]LogUpdateViewModel model) - { - return Ok(await _mediator.Send(new LogPutItemRequest(model), HttpContext.RequestAborted)); - } - - [HttpDelete("[action]/{id:guid}")] - public async Task DeleteItem(Guid id) - { - return Ok(await _mediator.Send(new LogDeleteItemRequest(id), HttpContext.RequestAborted)); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Extensions/ApplicationBuilderExtensions.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Extensions/ApplicationBuilderExtensions.cs deleted file mode 100644 index dfecc50d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Extensions/ApplicationBuilderExtensions.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Text.RegularExpressions; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.ApplicationModels; -using Microsoft.AspNetCore.Routing; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.Module.Web.Extensions -{ - /// - /// Extensions for application class - /// - public static class ApplicationBuilderExtensions - { - /// - /// Use special route slugify for Pegasus routing - /// - /// - public static void UseRouteSlugify(this MvcOptions options) - { - options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer())); - } - } - - /// - /// Special route naming convention - /// - public class SlugifyParameterTransformer : IOutboundParameterTransformer - { - /// - public string TransformOutbound(object value) - { - return value == null - ? null - : Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower(); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Extensions/AssemblyExtensions.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Extensions/AssemblyExtensions.cs deleted file mode 100644 index da499567..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Extensions/AssemblyExtensions.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace Calabonga.Microservice.Module.Web.Extensions -{ - /// - /// Assembly helpers - /// - public static class AssemblyExtensions - { - /// - /// Returns types - /// - /// - /// - /// - public static List GetTypesAssignableFrom(this Assembly assembly) - { - return assembly.GetTypesAssignableFrom(typeof(T)); - } - - private static List GetTypesAssignableFrom(this Assembly assembly, Type compareType) - { - var ret = new List(); - foreach (var type in assembly.DefinedTypes) - { - if (compareType.IsAssignableFrom(type) && compareType != type && !type.IsAbstract) - { - ret.Add(type); - } - } - return ret; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Extensions/DateTimeExtensions.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Extensions/DateTimeExtensions.cs deleted file mode 100644 index dea69a01..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Extensions/DateTimeExtensions.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Calabonga.Microservice.Module.Web.Extensions -{ - /// - /// DateTime extensions - /// - public static class DateTimeExtensions - { - /// - /// Each day enumeration - /// - /// - /// - /// - private static IEnumerable EachDay(DateTime from, DateTime thru) - { - for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1)) - { - yield return day; - } - } - - /// - /// Each month enumeration - /// - /// - /// - /// - private static IEnumerable EachMonth(DateTime from, DateTime thru) - { - for (var month = from.Date; month.Date <= thru.Date || month.Month == thru.Month; month = month.AddMonths(1)) - { - yield return month; - } - } - - /// - /// Enumerates all days in period - /// - /// - /// - /// - public static IEnumerable EachDayTo(this DateTime dateFrom, DateTime dateTo) - { - return EachDay(dateFrom, dateTo); - } - - /// - /// Enumerates all months in period - /// - /// - /// - /// - public static IEnumerable EachMonthTo(this DateTime dateFrom, DateTime dateTo) - { - return EachMonth(dateFrom, dateTo); - } - - - /// - /// Total Month count between two dates - /// - /// - /// - /// - public static int TotalMonths(this DateTime start, DateTime end) - { - return (start.Year * 12 + start.Month) - (end.Year * 12 + end.Month); - } - - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Extensions/EntityValidatorExtensions.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Extensions/EntityValidatorExtensions.cs deleted file mode 100644 index 284baade..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Extensions/EntityValidatorExtensions.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections.Generic; -using Calabonga.Microservices.Core.Validators; - -namespace Calabonga.Microservice.Module.Web.Extensions -{ - /// - /// Entity Validator Extensions - /// - public static class EntityValidatorExtensions - { - /// - /// Returns validator from validation results - /// - /// - /// - public static ValidationContext GetResult(this List source) - { - return new ValidationContext(source); - } - - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/SwaggerFormAttribute.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/SwaggerFormAttribute.cs deleted file mode 100644 index c2a8c977..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/SwaggerFormAttribute.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Attributes -{ - /// - /// Custom attribute for Swagger Upload Form - /// - [AttributeUsage(AttributeTargets.Method)] - public sealed class SwaggerFormAttribute : Attribute - { - /// - public SwaggerFormAttribute(string parameterName, string description, bool hasFileUpload = true) - { - ParameterName = parameterName; - Description = description; - HasFileUpload = hasFileUpload; - } - - /// - /// UploadFile enabled - /// - public bool HasFileUpload { get; } - - /// - /// Name for the parameter - /// - public string ParameterName { get; } - - /// - /// Small description - /// - public string Description { get;} - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/SwaggerGroupAttribute.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/SwaggerGroupAttribute.cs deleted file mode 100644 index b09c0686..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/SwaggerGroupAttribute.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Attributes -{ - /// - /// Swagger controller group attribute - /// - /// - [AttributeUsage(AttributeTargets.Class)] - public class SwaggerGroupAttribute : Attribute - { - /// - public SwaggerGroupAttribute(string groupName) - { - GroupName = groupName; - } - - /// - /// Group name - /// - public string GroupName { get; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/ValidateModelStateAttribute.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/ValidateModelStateAttribute.cs deleted file mode 100644 index 93432272..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/ValidateModelStateAttribute.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Linq; -using Calabonga.OperationResults; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Attributes -{ - /// - /// Custom validation handler for availability to whit OperationResult - /// - public class ValidateModelStateAttribute : ActionFilterAttribute - { - /// - public override void OnActionExecuting(ActionExecutingContext context) - { - if (context.ModelState.IsValid) return; - var operation = OperationResult.CreateResult(); - var messages = context.ModelState.Values.SelectMany(x => x.Errors.Select(xx => xx.ErrorMessage)); - var message = string.Join(" ", messages); - operation.AddError(message); - context.Result = new OkObjectResult(operation); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/DependencyInjection/CommonRegistrations.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/DependencyInjection/CommonRegistrations.cs deleted file mode 100644 index 488bb789..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/DependencyInjection/CommonRegistrations.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Calabonga.Microservice.Module.Data; -using Calabonga.Microservice.Module.Web.Infrastructure.Services; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.DependencyInjection -{ - /// - /// Registrations for both points: API and Scheduler - /// - public partial class DependencyContainer - { - /// - /// Register - /// - /// - public static void Common(IServiceCollection services) - { - services.AddTransient(); - - // services - services.AddTransient(); - services.AddTransient(); - } - } - - -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Engine/EntityManagers/LogManager.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Engine/EntityManagers/LogManager.cs deleted file mode 100644 index 1944040a..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Engine/EntityManagers/LogManager.cs +++ /dev/null @@ -1,21 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.Module.Entities; -using Calabonga.Microservice.Module.Web.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.Validators; -using Calabonga.UnitOfWork.Controllers.Factories; -using Calabonga.UnitOfWork.Controllers.Managers; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Engine.EntityManagers -{ - /// - /// Entity manager for - /// - public class LogManager: EntityManager - { - /// - public LogManager(IMapper mapper, IViewModelFactory viewModelFactory, IEntityValidator validator) - : base(mapper, viewModelFactory, validator) - { - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Engine/EntityValidators/LogValidator.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Engine/EntityValidators/LogValidator.cs deleted file mode 100644 index 70fbbc61..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Engine/EntityValidators/LogValidator.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Calabonga.Microservice.Module.Entities; -using Calabonga.Microservices.Core.Validators; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Engine.EntityValidators -{ - /// - /// Entity Validator for - /// - public class LogValidator: EntityValidator - { - - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Engine/ViewModelFactories/LogViewModelFactory.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Engine/ViewModelFactories/LogViewModelFactory.cs deleted file mode 100644 index 575eedba..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Engine/ViewModelFactories/LogViewModelFactory.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Threading.Tasks; -using AutoMapper; -using Calabonga.Microservice.Module.Entities; -using Calabonga.Microservice.Module.Web.ViewModels.LogViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using Calabonga.UnitOfWork.Controllers.Factories; -using Microsoft.Extensions.Logging; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Engine.ViewModelFactories -{ - /// - /// ViewModel factory for - /// - public class LogViewModelFactory : ViewModelFactory - { - private readonly IUnitOfWork _context; - private readonly IMapper _mapper; - - public LogViewModelFactory(IUnitOfWork context, IMapper mapper) - { - _context = context; - _mapper = mapper; - } - - /// - public override Task> GenerateForCreateAsync() - { - var operation = OperationResult.CreateResult(); - operation.Result = new LogCreateViewModel() - { - CreatedAt = DateTime.Now, - Level = LogLevel.Information.ToString(), - Logger = "Demo purposes only", - Message = $"This is demo message {DateTime.Now}" - }; - return Task.FromResult(operation); - } - - /// - public override async Task> GenerateForUpdateAsync(Guid id) - { - var operation = OperationResult.CreateResult(); - var entity = await _context.GetRepository().GetFirstOrDefaultAsync(predicate: x => x.Id == id); - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("ViewModel generated for Log entity. Please see Additional information in DataObject").AddData(new { Identifier = id }); - - return operation; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/IViewModel.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/IViewModel.cs deleted file mode 100644 index 5d6f12f3..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/IViewModel.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Calabonga.Microservice.Module.Web.Infrastructure.Factories.Base -{ - /// - /// Just a stub for see - /// - public interface IViewModel { } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/IViewModelFactory.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/IViewModelFactory.cs deleted file mode 100644 index a04f0220..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/IViewModelFactory.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Factories.Base -{ - /// - /// ViewModel Factory - /// - /// - /// - /// - public interface IViewModelFactory - where TCreateViewModel : IViewModel, new() - where TUpdateViewModel : IViewModel, new() - where TEntity : class, IHaveId - { - /// - /// Returns ViewModel for entity creation - /// - /// - TCreateViewModel GenerateForCreate(); - - /// - /// Returns ViewModel for entity editing - /// - /// - /// - TUpdateViewModel GenerateForUpdate(Guid id); - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/ViewModelFactory.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/ViewModelFactory.cs deleted file mode 100644 index 18c7a7f8..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/ViewModelFactory.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Factories.Base -{ - /// - /// ViewModelFactory base class - /// - /// - /// - /// - public abstract class ViewModelFactory : IViewModelFactory - where TCreateViewModel : IViewModel, new() - where TUpdateViewModel : IViewModel, new() - where TEntity : class, IHaveId - { - - /// - public abstract TCreateViewModel GenerateForCreate(); - - /// - public abstract TUpdateViewModel GenerateForUpdate(Guid id); - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/AsyncHelper.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/AsyncHelper.cs deleted file mode 100644 index 22a81b1e..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/AsyncHelper.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Helpers -{ - /// - /// Run Asynchronous methods as Synchronous. - /// - public static class AsyncHelper - { - private static readonly TaskFactory AppTaskFactory = new - TaskFactory(CancellationToken.None, - TaskCreationOptions.None, - TaskContinuationOptions.None, - TaskScheduler.Default); - - /// - /// Run asynchronous method as synchronous - /// - /// - /// - /// - public static TResult RunSync(Func> func) - { - return AppTaskFactory - .StartNew(func) - .Unwrap() - .GetAwaiter() - .GetResult(); - } - - /// - /// Run asynchronous method as synchronous - /// - /// - public static void RunSync(Func func) - { - AppTaskFactory - .StartNew(func) - .Unwrap() - .GetAwaiter() - .GetResult(); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/EmailHelper.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/EmailHelper.cs deleted file mode 100644 index bd4c3b31..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/EmailHelper.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Calabonga.Microservice.Module.Core; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Helpers -{ - /// - /// Email validation helper - /// - public static class EmailHelper - { - /// - /// Validates emails entries - /// - /// - /// - public static IEnumerable GetValidEmails(string emails) - { - if (string.IsNullOrWhiteSpace(emails)) - { - return null; - } - var split = emails.Split(new[] { ';', '|', ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); - return split.Where(x => x.IsEmail()); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/EnumHelper.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/EnumHelper.cs deleted file mode 100644 index 1ca3274b..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/EnumHelper.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Reflection; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Helpers -{ - /// - /// Enum Helper - /// - /// - public static class EnumHelper where T: struct - { - /// - /// Returns Enum with DisplayNames - /// - /// - public static Dictionary GetValuesWithDisplayNames() - { - var type = typeof(T); - var r = type.GetEnumValues(); - var list = new Dictionary(); - foreach (var element in r) - { - list.Add((T)element, GetDisplayValue((T)element)); - } - return list; - } - - /// - /// Returns values from enum - /// - /// - public static IList GetValues() - { - return typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public).Select(fi => (T)Enum.Parse(typeof(T), fi.Name, false)).ToList(); - } - - /// - /// Parse value by string from Enum - /// - /// - /// - public static T Parse(string value) - { - return (T)Enum.Parse(typeof(T), value, true); - } - - /// - /// Parse value by string from Enum - /// - /// - /// - public static T? TryParse(string value) - { - if (Enum.TryParse(value, true, out T result)) - { - return result; - } - return null; - - } - - /// - /// Returns values from Enum - /// - /// - public static IEnumerable GetNames() - { - return typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public).Select(fi => fi.Name).ToList(); - } - - /// - /// Returns values from Enum or Resource file if exists - /// - /// - /// - public static IList GetDisplayValues(Enum value) - { - return GetNames().Select(obj => GetDisplayValue(Parse(obj))).ToList(); - } - - private static string LookupResource(Type resourceManagerProvider, string resourceKey) - { - foreach (var staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)) - { - if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager)) - { - var resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null); - return resourceManager.GetString(resourceKey); - } - } - - return resourceKey; // Fallback with the key name - } - - /// - /// Returns display name for Enum - /// - /// - /// - public static string GetDisplayValue(T value) - { - var fieldInfo = value.GetType().GetField(value.ToString()); - - var descriptionAttributes = fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false) as DisplayAttribute[]; - if (descriptionAttributes?.Length > 0 && descriptionAttributes[0].ResourceType != null) - { - return LookupResource(descriptionAttributes[0].ResourceType, descriptionAttributes[0].Name); - } - - if (descriptionAttributes == null) - { - return string.Empty; - } - - return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString(); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/Utilites.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/Utilites.cs deleted file mode 100644 index 04a2431a..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/Utilites.cs +++ /dev/null @@ -1,173 +0,0 @@ -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Calabonga.Microservice.Module.Core.Exceptions; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Helpers -{ - /// - /// System utilities - /// - public static class Utilities - { - /// - /// Compute Hash - /// - /// - /// - public static byte[] ComputeHash(string filePath) - { - var runCount = 1; - while (runCount < 4) - { - try - { - if (!File.Exists(filePath)) - { - throw new FileNotFoundException(); - } - - using (var fs = File.OpenRead(filePath)) - { - return SHA1.Create().ComputeHash(fs); - } - } - catch (IOException ex) - { - if (runCount == 3 || ex.HResult != -2147024864) - { - throw; - } - else - { - Thread.Sleep(TimeSpan.FromSeconds(Math.Pow(2, runCount))); - runCount++; - } - } - } - - return new byte[20]; - } - - /// - /// Return file content - /// - /// - /// - public static async Task GetFileContent(string filePath) - { - try - { - if (!File.Exists(filePath)) - { - throw new FileNotFoundException(); - } - - return await File.ReadAllTextAsync(filePath); - } - catch - { - return null; - } - } - - /// - /// Remove file from directory (physical deleting) - /// - /// - public static void DeleteFile(string filePath) - { - try - { - if (!File.Exists(filePath)) - { - throw new FileNotFoundException(); - } - - File.Delete(filePath); - } - catch - { - // ignored - } - } - - /// - /// Save content to the text file - /// - /// - /// - /// - public static async Task SetFileContent(string filePath, string content) - { - try - { - var folder = Path.GetDirectoryName(filePath); - if (!Directory.Exists(folder)) - { - Directory.CreateDirectory(folder); - } - - if (File.Exists(filePath)) - { - throw new MicroserviceFileAlreadyExistsException(); - } - - using (var fs = File.Create(filePath)) - { - var info = new UTF8Encoding(true).GetBytes(content); - await fs.WriteAsync(info, 0, info.Length); - } - } - catch - { - // ignored - - } - } - - /// - /// Generate ETag for content bytes - /// - /// - /// - /// - public static string GetETag(string key, byte[] contentBytes) - { - var keyBytes = Encoding.UTF8.GetBytes(key); - var combinedBytes = Combine(keyBytes, contentBytes); - return GenerateETag(combinedBytes); - } - - /// - /// Returns Working folder path - /// - /// - public static string GetWorkingFolder() - { - var location = System.Reflection.Assembly.GetEntryAssembly().Location; - return Path.GetDirectoryName(location); - } - - private static string GenerateETag(byte[] data) - { - using (var md5 = MD5.Create()) - { - var hash = md5.ComputeHash(data); - var hex = BitConverter.ToString(hash); - return hex.Replace("-", ""); - } - } - - private static byte[] Combine(byte[] a, byte[] b) - { - var c = new byte[a.Length + b.Length]; - Buffer.BlockCopy(a, 0, c, 0, a.Length); - Buffer.BlockCopy(b, 0, c, a.Length, b.Length); - return c; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/ValidationContextHelper.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/ValidationContextHelper.cs deleted file mode 100644 index b0ceb114..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/ValidationContextHelper.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.ObjectModel; -using System.ComponentModel.DataAnnotations; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Helpers -{ - /// - /// ValidationContext Helper for validation operations - /// - public static class ValidationContextHelper - { - /// - /// Returns validation results of IValidatableObject - /// - /// - /// - /// - /// - public static bool TryValidate(object obj, out Collection results, ValidationContext validationContext = null) - { - var context = validationContext ?? new ValidationContext(obj, serviceProvider: null, items: null); - results = new Collection(); - return Validator.TryValidateObject(obj, context, results, validateAllProperties: true); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/IAutoMapper.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/IAutoMapper.cs deleted file mode 100644 index 87570125..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/IAutoMapper.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Calabonga.Microservice.Module.Web.Infrastructure.Mappers.Base -{ - /// - /// The stub for reflection helper profiles registrations - /// - public interface IAutoMapper { } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/MapperConfigurationBase.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/MapperConfigurationBase.cs deleted file mode 100644 index 8c961fa3..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/MapperConfigurationBase.cs +++ /dev/null @@ -1,10 +0,0 @@ -using AutoMapper; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Mappers.Base { - - /// - /// Base class for mapper configuration. - /// All ViewModel that will be mapped should implement IAutoMapper - /// - public abstract class MapperConfigurationBase : Profile, IAutoMapper { } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/PagedListConverter.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/PagedListConverter.cs deleted file mode 100644 index a82c72ee..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/PagedListConverter.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using AutoMapper; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Mappers.Base { - - /// - /// Generic converter for IPagedList collections - /// - /// - /// - public class PagedListConverter : ITypeConverter, IPagedList> { - - /// Performs conversion from source to destination type - /// Source object - /// Destination object - /// Resolution context - /// Destination object - public IPagedList Convert(IPagedList source, IPagedList destination, ResolutionContext context) { - if (source == null) return null; - var vm = source.Items.Select(m => context.Mapper.Map(m)).ToList(); - - - var pagedList = PagedList.From(source, (con)=> context.Mapper.Map>(con)); - // var pagedList = vm.ToPagedList(source.PageIndex, source.PageSize); - return pagedList; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/LogMapperConfiguration.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/LogMapperConfiguration.cs deleted file mode 100644 index b2af8ca4..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/LogMapperConfiguration.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Calabonga.Microservice.Module.Entities; -using Calabonga.Microservice.Module.Web.Infrastructure.Mappers.Base; -using Calabonga.Microservice.Module.Web.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Mappers -{ - /// - /// Mapper Configuration for entity Log - /// - public class LogMapperConfiguration: MapperConfigurationBase - { - /// - public LogMapperConfiguration() - { - CreateMap() - .ForMember(x=>x.Id, o=>o.Ignore()); - - CreateMap(); - - CreateMap, IPagedList>() - .ConvertUsing>(); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Services/CacheService.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Services/CacheService.cs deleted file mode 100644 index e3222817..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Services/CacheService.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using Calabonga.Microservice.Module.Core.Exceptions; -using Microsoft.Extensions.Caching.Memory; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Services -{ - /// - /// Cache service - /// - public class CacheService : ICacheService - { - private readonly IMemoryCache _cache; - private readonly TimeSpan _defaultSlidingExpiration = TimeSpan.FromSeconds(60); - - /// - public CacheService(IMemoryCache cache) - { - _cache = cache; - } - - /// - public TEntry Get(object key) - { - if (key == null) - { - throw new MicroserviceArgumentNullException(nameof(key)); - } - - return _cache.Get(key); - } - - /// - public void SetForMinute(object key, TEntry cacheEntry) - { - SetWithSlidingExpiration(key, cacheEntry, _defaultSlidingExpiration); - } - - /// - public void SetForThirtyMinutes(object key, TEntry cacheEntry) - { - SetWithSlidingExpiration(key, cacheEntry, TimeSpan.FromMinutes(30)); - } - - /// - /// Default set mechanism - /// - /// - /// - /// - /// - public void SetWithSlidingExpiration(object key, TEntry cacheEntry, TimeSpan slidingExpiration) - { - if (cacheEntry == null) - { - throw new MicroserviceArgumentNullException(nameof(cacheEntry)); - } - - if (key == null) - { - throw new MicroserviceArgumentNullException(nameof(key)); - } - - if (slidingExpiration.Ticks == 0) - { - slidingExpiration = _defaultSlidingExpiration; - } - - var options = new MemoryCacheEntryOptions().SetSlidingExpiration(slidingExpiration); - - _cache.Set(key, cacheEntry, options); - } - - /// - public TEntry GetOrCreate(TKey key, Func findIfNotFoundFunc) - { - return _cache.GetOrCreate(key, findIfNotFoundFunc); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Services/ICacheService.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Services/ICacheService.cs deleted file mode 100644 index 43d0de92..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Services/ICacheService.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using Microsoft.Extensions.Caching.Memory; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Services -{ - /// - /// Cache service interface - /// - public interface ICacheService - { - /// - /// Get the entry from the cache - /// - /// - /// - TEntry Get(object key); - - /// - /// Sets entry cache for one minute sliding expiration - /// - /// - /// - /// - void SetForMinute(object key, TEntry cacheEntry); - - /// - /// Sets entry cache for 30 minutes sliding expiration - /// - /// - /// - /// - void SetForThirtyMinutes(object key, TEntry cacheEntry); - - /// - /// Sets entry cache for custom sliding expiration interval - /// - /// - /// - /// - /// - void SetWithSlidingExpiration(object key, TEntry cacheEntry, TimeSpan slidingExpiration); - - /// - /// Returns already exist entry or first put it to the cache and then return entry - /// - /// - /// - /// - /// - /// - TEntry GetOrCreate(TKey key, Func findIfNotFoundFunc); - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Services/ILogService.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Services/ILogService.cs deleted file mode 100644 index 3c894dc7..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Services/ILogService.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Calabonga.Microservice.Module.Web.Infrastructure.Services -{ - /// - /// Interface for Business logic logger can save messages to database - /// - public interface ILogService - { - /// - /// Log information message - /// - /// - void LogInformation(string message); - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Services/LogService.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Services/LogService.cs deleted file mode 100644 index b44c4efa..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Services/LogService.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using Calabonga.Microservice.Module.Core.Exceptions; -using Calabonga.Microservice.Module.Data; -using Calabonga.Microservice.Module.Entities; -using Calabonga.UnitOfWork; -using Microsoft.Extensions.Logging; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Services -{ - /// - /// Business logic logger can save messages to database - /// - public class LogService : ILogService - { - private readonly IUnitOfWork _unitOfWork; - - /// - public LogService(IUnitOfWork unitOfWork) - { - _unitOfWork = unitOfWork; - } - /// - public void LogInformation(string message) - { - Log(LogLevel.Information, message); - } - - /// - /// Allows to save data logs to the database Logs table - /// - private void Log(LogLevel level, string message, Exception exception = null) - { - var logs = _unitOfWork.GetRepository(); - var log = new Log - { - CreatedAt = DateTime.UtcNow, - Level = level.ToString(), - Logger = GetType().Name, - Message = message, - ThreadId = "0", - ExceptionMessage = exception?.Message - }; - logs.Insert(log); - _unitOfWork.SaveChanges(); - if (!_unitOfWork.LastSaveChangesResult.IsOk) - { - throw new MicroserviceInvalidOperationException(); - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Settings/Base/ServiceBase.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Settings/Base/ServiceBase.cs deleted file mode 100644 index d9df15e9..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Settings/Base/ServiceBase.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Calabonga.Microservice.Module.Web.Infrastructure.Settings.Base -{ - /// - /// Base service behavior - /// - public abstract class ServiceBase - { - /// - /// Indicates that the processing available works is enabled - /// - public bool IsActive { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Settings/CurrentAppSettings.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Settings/CurrentAppSettings.cs deleted file mode 100644 index 97695e48..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Settings/CurrentAppSettings.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Calabonga.Microservice.Module.Web.Infrastructure.Settings -{ - /// - /// Represents configuration file with current application settings - /// - public class CurrentAppSettings - { - /// - /// Default page size - /// - public int PageSize { get; set; } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Validations/LogValidator.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Validations/LogValidator.cs deleted file mode 100644 index ff427d65..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Infrastructure/Validations/LogValidator.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Calabonga.Microservice.Module.Entities; -using Calabonga.Microservices.Core.Validators; - -namespace Calabonga.Microservice.Module.Web.Infrastructure.Validations -{ - /// - /// Validator for entity Log - /// - public class LogValidator : EntityValidator - { - - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/Behaviors/ValidationBehavior.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/Behaviors/ValidationBehavior.cs deleted file mode 100644 index b969c389..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/Behaviors/ValidationBehavior.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Calabonga.AspNetCore.Controllers.Base; -using Calabonga.OperationResults; -using FluentValidation; -using MediatR; - -namespace Calabonga.Microservice.Module.Web.Mediator.Behaviors -{ - /// - /// Base validator for requests - /// - /// - /// - public class ValidatorBehavior : IPipelineBehavior - where TRequest: IRequest - { - private readonly IEnumerable> _validators; - - public ValidatorBehavior(IEnumerable> validators) - { - _validators = validators; - } - - /// - /// Pipeline handler. Perform any additional behavior and await the delegate as necessary - /// - /// Incoming request - /// Cancellation token - /// Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler. - /// Awaitable task returning the - public Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) - { - var failures = _validators - .Select(x => x.Validate(new ValidationContext(request))) - .SelectMany(x => x.Errors) - .Where(x => x != null) - .ToList(); - - if (!failures.Any()) return next(); - - if (request is RequestBase>) - { - var operation = OperationResult.CreateResult(); - operation.AddError(new ValidationException(failures)); - // return Task.FromResult(operation); - } - // return Task.FromResult(operation); - return Task.FromResult(default(TResponse)); - } - - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/GetRoles.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/GetRoles.cs deleted file mode 100644 index 818ec9ce..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/GetRoles.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Security.Claims; -using Calabonga.AspNetCore.Controllers.Base; -using Calabonga.Microservices.Core; -using MediatR; -using Microsoft.AspNetCore.Http; - -namespace Calabonga.Microservice.Module.Web.Mediator.LogsReadonly -{ - /// - /// Request: Returns user roles - /// - public class GetRolesRequest: RequestBase - { - - } - - public class GetRolesRequestHandler : RequestHandler - { - private readonly IHttpContextAccessor _httpContextAccessor; - - public GetRolesRequestHandler(IHttpContextAccessor httpContextAccessor) - { - _httpContextAccessor = httpContextAccessor; - } - - protected override string Handle(GetRolesRequest request) - { - var user = _httpContextAccessor.HttpContext.User; - var roles = ClaimsHelper.GetValues((ClaimsIdentity)user.Identity, "role"); - return $"Current user ({user.Identity.Name}) have following roles: {string.Join("|", roles)}"; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/LogGetById.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/LogGetById.cs deleted file mode 100644 index 84b13d23..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/LogGetById.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.Module.Entities; -using Calabonga.Microservice.Module.Web.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.Module.Web.Mediator.LogsReadonly -{ - /// - /// Request for Log by Identifier - /// - public class LogGetByIdRequest : GetByIdQuery - { - public LogGetByIdRequest(Guid id) : base(id) - { - } - } - - /// - /// Response for Request for Log by Identifier - /// - public class LogGetByIdRequestHandler : GetByIdHandlerBase - { - public LogGetByIdRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/LogGetPaged.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/LogGetPaged.cs deleted file mode 100644 index faa4f21b..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/LogGetPaged.cs +++ /dev/null @@ -1,30 +0,0 @@ -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.Module.Entities; -using Calabonga.Microservice.Module.Web.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.Module.Web.Mediator.LogsReadonly -{ - /// - /// Request for paged list of Logs - /// - public class LogGetPagedRequest : GetPagedQuery - { - public LogGetPagedRequest(PagedListQueryParams queryParams) : base(queryParams) - { - } - } - - /// - /// Request for paged list of Logs - /// - public class LogGetPagedRequestHandler : GetPagedHandlerBase - { - public LogGetPagedRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogCreateViewModel.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogCreateViewModel.cs deleted file mode 100644 index 12eae398..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogCreateViewModel.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Threading.Tasks; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.Module.Web.ViewModels.LogViewModels; -using Microsoft.Extensions.Logging; - -namespace Calabonga.Microservice.Module.Web.Mediator.LogsWritable -{ - /// - /// Request: Returns ViewModel for entity Log creation - /// - public class LogCreateViewModelRequest: CreateViewModelQuery - { - - } - - /// - /// Response: Returns ViewModel for entity Log creation - /// - public class LogCreateViewModelRequestHandler : CreateViewModelHandlerBase - { - protected override ValueTask GenerateCreateViewModel() - { - return new ValueTask(new LogCreateViewModel - { - CreatedAt = DateTime.UtcNow, - Level = LogLevel.Information.ToString(), - Message = "Generated automatically", - Logger = "LogCreateViewModelRequestHandler", - ThreadId = "0" - }); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogDeleteItem.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogDeleteItem.cs deleted file mode 100644 index a61995fc..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogDeleteItem.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.Module.Entities; -using Calabonga.Microservice.Module.Web.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.Module.Web.Mediator.LogsWritable -{ - /// - /// Request: Log delete - /// - public class LogDeleteItemRequest: DeleteByIdQuery - { - public LogDeleteItemRequest(Guid id) : base(id) - { - } - } - - /// - /// Request: Log delete - /// - public class LogDeleteItemRequestHandler : DeleteByIdHandlerBase - { - public LogDeleteItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogPostItem.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogPostItem.cs deleted file mode 100644 index 83bfac0d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogPostItem.cs +++ /dev/null @@ -1,29 +0,0 @@ -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.Module.Entities; -using Calabonga.Microservice.Module.Web.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.Module.Web.Mediator.LogsWritable -{ - /// - /// Request: Log creation - /// - public class LogPostItemRequest: PostItemQuery - { - public LogPostItemRequest(LogCreateViewModel model) : base(model) - { - } - } - - /// - /// Request: Log creation - /// - public class LogPostItemRequestHandler : PostItemHandlerBase - { - public LogPostItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogPutItem.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogPutItem.cs deleted file mode 100644 index 449ea27d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogPutItem.cs +++ /dev/null @@ -1,37 +0,0 @@ -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.Module.Entities; -using Calabonga.Microservice.Module.Web.ViewModels.LogViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.Module.Web.Mediator.LogsWritable -{ - /// - /// Request: Log edit - /// - public class LogPutItemRequest: PutItemQuery - { - public LogPutItemRequest(LogUpdateViewModel model) : base(model) - { - } - } - - /// - /// Request: Log creation - /// - public class LogPutItemRequestHandler : PutItemHandlerBase - { - public LogPutItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - - protected override OperationResult ProcessOperationResult(OperationResult operationResult, LogViewModel response) - { - operationResult.AppendLog("Successfully updated"); - operationResult.Result = response; - return operationResult; - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogUpdateViewModel.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogUpdateViewModel.cs deleted file mode 100644 index 25e91fb1..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogUpdateViewModel.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using Calabonga.Microservice.Module.Entities; -using Calabonga.Microservice.Module.Web.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.Module.Web.Mediator.LogsWritable -{ - /// - /// Request: Returns ViewModel for entity Log creation - /// - public class LogUpdateViewModelRequest: UpdateViewModelQuery - { - public LogUpdateViewModelRequest(Guid id) : base(id) - { - } - } - - /// - /// Response: Returns ViewModel for entity Log creation - /// - public class LogUpdateViewModelRequestHandler : UpdateViewModelHandlerBase - { - public LogUpdateViewModelRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Middlewares/ETagMiddleware.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Middlewares/ETagMiddleware.cs deleted file mode 100644 index 194b9730..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Middlewares/ETagMiddleware.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System.IO; -using System.Security.Cryptography; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Net.Http.Headers; - -namespace Calabonga.Microservice.Module.Web.Middlewares -{ - /// - /// ETagger extension - /// - public static class ApplicationBuilderExtensions - { - /// - /// Use Custom middleware - /// - /// - public static void UseETagger(this IApplicationBuilder app) - { - app.UseMiddleware(); - } - } - - /// - /// ETag middleware from Mads Kristensen. - /// See https://madskristensen.net/blog/send-etag-headers-in-aspnet-core/ - /// - public class ETagMiddleware - { - private readonly RequestDelegate _next; - - /// - public ETagMiddleware(RequestDelegate next) - { - _next = next; - } - - /// - /// Invoke middleware entry point - /// - /// - /// - public async Task InvokeAsync(HttpContext context) - { - var response = context.Response; - var originalStream = response.Body; - - using (var ms = new MemoryStream()) - { - response.Body = ms; - - await _next(context); - - if (IsEtagSupported(response)) - { - var checksum = CalculateChecksum(ms); - - response.Headers[HeaderNames.ETag] = checksum; - - if (context.Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var etag) && checksum == etag) - { - response.StatusCode = StatusCodes.Status304NotModified; - return; - } - } - - ms.Position = 0; - await ms.CopyToAsync(originalStream); - } - } - - private static bool IsEtagSupported(HttpResponse response) - { - if (response.StatusCode != StatusCodes.Status200OK) - return false; - - // The 100kb length limit is not based in science. Feel free to change - if (response.Body.Length > 100 * 1024) - return false; - - if (response.Headers.ContainsKey(HeaderNames.ETag)) - return false; - - return true; - } - - private static string CalculateChecksum(MemoryStream ms) - { - string checksum = ""; - - using (var algo = SHA1.Create()) - { - ms.Position = 0; - byte[] bytes = algo.ComputeHash(ms); - checksum = $"\"{WebEncoders.Base64UrlEncode(bytes)}\""; - } - - return checksum; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Middlewares/ErrorHandle.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Middlewares/ErrorHandle.cs deleted file mode 100644 index f979df89..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Middlewares/ErrorHandle.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Threading.Tasks; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; - -namespace Calabonga.Microservice.Module.Web.Middlewares -{ - /// - /// Custom error handler. It allows to view error messages on UI - /// - public class ErrorHandlingMiddleware - { - private readonly RequestDelegate _next; - - /// - public ErrorHandlingMiddleware(RequestDelegate next) - { - _next = next; - } - - /// - /// Invoke middle ware. Entry point - /// - /// - /// - public async Task Invoke(HttpContext context) - { - try - { - await _next(context); - } - catch (Exception ex) - { - await HandleExceptionAsync(context, ex); - } - } - - private static Task HandleExceptionAsync(HttpContext context, Exception exception) - { - try - { - var result = JsonConvert.SerializeObject(ExceptionHelper.GetMessages(exception), Formatting.Indented); - if (result?.Length > 4000) - { - return context.Response.WriteAsync("Error message to long. Please use DEBUG in method HandleExceptionAsync to handle a whole of text of the exception"); - } - return context.Response.WriteAsync(result); - } - catch - { - return context.Response.WriteAsync($"{exception.Message} For more information please use DEBUG in method HandleExceptionAsync to handle a whole of text of the exception"); - } - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Program.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Program.cs deleted file mode 100644 index 0308d63c..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Program.cs +++ /dev/null @@ -1,36 +0,0 @@ -// --------------------------------------- -// Name: Microservice Template -// Author: Calabonga (calabonga.net) -// Version: 2.2.0 -// Based on: ASP.NET Core 3.1 -// Created Date: 2019-10-06 -// Updated Date 2020-09-27 -// --------------------------------------- - -using System; -using Calabonga.Microservice.Module.Core; -using Calabonga.Microservice.Module.Data.DatabaseInitialization; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; - -namespace Calabonga.Microservice.Module.Web -{ - public class Program - { - public static void Main(string[] args) - { - var webHost = CreateHostBuilder(args).Build(); - using (var scope = webHost.Services.CreateScope()) - { - DatabaseInitializer.Seed(scope.ServiceProvider); - } - Console.Title = $"{AppData.ServiceName} v.{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - webHost.Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()); - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Properties/launchSettings.json b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Properties/launchSettings.json deleted file mode 100644 index d568b0cc..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Properties/launchSettings.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/launchsettings.json", - "profiles": { - "Kestrel_dev": { - "commandName": "Project", - "launchBrowser": true, - "launchUrl": "api/manual", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "http://localhost:20001" - }, - "Kestrel_prod": { - "commandName": "Project", - "launchBrowser": true, - "launchUrl": "api/manual", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Production" - }, - "applicationUrl": "http://localhost:20001" - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Startup.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Startup.cs deleted file mode 100644 index 4567ab7d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Startup.cs +++ /dev/null @@ -1,57 +0,0 @@ -using Calabonga.Microservice.Module.Web.AppStart.Configures; -using Calabonga.Microservice.Module.Web.AppStart.ConfigureServices; -using Calabonga.Microservice.Module.Web.Infrastructure.DependencyInjection; -using Calabonga.UnitOfWork.Controllers.DependencyContainer; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.Module.Web -{ - /// - /// Startup entry - /// - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - /// - /// Configuration - /// - public IConfiguration Configuration { get; } - - /// - /// This method gets called by the runtime. Use this method to add services to the container. - /// - /// - public void ConfigureServices(IServiceCollection services) - { - ConfigureServicesBase.ConfigureServices(services, Configuration); - ConfigureServicesAuthentication.ConfigureServices(services, Configuration); - ConfigureServicesSwagger.ConfigureServices(services, Configuration); - ConfigureServicesCors.ConfigureServices(services, Configuration); - ConfigureServicesControllers.ConfigureServices(services); - ConfigureServicesMediator.ConfigureServices(services); - ConfigureServicesValidators.ConfigureServices(services); - - DependencyContainer.Common(services); - NimbleDependencyContainer.ConfigureServices(services); - } - - /// - /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - /// - /// - /// - /// - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, AutoMapper.IConfigurationProvider mapper) - { - ConfigureCommon.Configure(app, env, mapper); - ConfigureEndpoints.Configure(app); - } - } -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogCreateViewModel.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogCreateViewModel.cs deleted file mode 100644 index 20bf5d8c..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogCreateViewModel.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; -using Calabonga.EntityFrameworkCore.Entities.Base; -using Microsoft.Extensions.Logging; - -namespace Calabonga.Microservice.Module.Web.ViewModels.LogViewModels -{ - /// - /// Data Transfer Object for Log entity - /// - public class LogCreateViewModel : IViewModel - { - /// - /// Log Created At - /// - [Required] - public DateTime CreatedAt { get; set; } - - /// - /// Service name or provider - /// - [Required] - [StringLength(255)] - public string Logger { get; set; } - - /// - /// Log level for logging. See - /// - [Required] - [StringLength(50)] - public string Level { get; set; } - - /// - /// Log Message - /// - [Required] - [StringLength(4000)] - public string Message { get; set; } - - /// - /// Thread identifier - /// - public string ThreadId { get; set; } - - /// - /// Exception message - /// - public string ExceptionMessage { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogUpdateViewModel.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogUpdateViewModel.cs deleted file mode 100644 index df017adb..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogUpdateViewModel.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace Calabonga.Microservice.Module.Web.ViewModels.LogViewModels -{ - /// - /// Log View model for Update operations - /// - public class LogUpdateViewModel : ViewModelBase - { - public string Logger { get; set; } - - public string Level { get; set; } - - public string Message { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogViewModel.cs b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogViewModel.cs deleted file mode 100644 index 726fb6d3..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogViewModel.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace Calabonga.Microservice.Module.Web.ViewModels.LogViewModels -{ - /// - /// Log ViewModel - /// - public class LogViewModel: ViewModelBase - { - /// - /// Created at - /// - public DateTime CreatedAt { get; set; } - - /// - /// Logger name - /// - public string Logger { get; set; } - - /// - /// Level - /// - public string Level { get; set; } - - /// - /// Message text - /// - public string Message { get; set; } - - /// - /// Thread ID - /// - public string ThreadId { get; set; } - - /// - /// - /// - public string ExceptionMessage { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.Development.json b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.Development.json deleted file mode 100644 index 1a1bae9d..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.Development.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=;User ID=;Password=" - }, - "Logging": { - "IncludeScopes": false, - "Debug": { - "LogLevel": { - "Default": "Warning", - "System": "Information", - "Microsoft": "Information" - } - }, - "Console": { - "LogLevel": { - "Default": "Warning", - "System": "Information", - "Microsoft": "Information" - } - } - }, - "Cors": { - "Origins": "*" - }, - "IdentityServer": { - "Url": "http://localhost:10001" - }, - "CurrentAppSettings": { - "PageSize": 50 - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.Production.json b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.Production.json deleted file mode 100644 index 9aa86891..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.Production.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=MicroserviceDb;Trusted_Connection=True;" - }, - "Logging": { - "IncludeScopes": false, - "Debug": { - "LogLevel": { - "Default": "Warning", - "System": "Information", - "Microsoft": "Information" - } - }, - "Console": { - "LogLevel": { - "Default": "Warning", - "System": "Information", - "Microsoft": "Information" - } - } - }, - "Cors": { - "Origins": "*" - }, - "IdentityServer": { - "Url": "http://localhost:10001" - }, - "CurrentAppSettings": { - "PageSize": 50 - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.json b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.json deleted file mode 100644 index def9159a..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.sln b/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.sln deleted file mode 100644 index 7bbc0f71..00000000 --- a/AspNetCore v3.1/Calabonga.Microservice.Module/Calabonga.Microservice.Module.sln +++ /dev/null @@ -1,43 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29318.209 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.Module.Web", "Calabonga.Microservice.Module.Web\Calabonga.Microservice.Module.Web.csproj", "{721D20AC-A069-4CCA-8DBA-361D69B49A80}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.Module.Core", "Calabonga.Microservice.Module.Core\Calabonga.Microservice.Module.Core.csproj", "{516E0183-749E-4931-B297-21BBD45F0161}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.Module.Entities", "Calabonga.Microservice.Module.Entities\Calabonga.Microservice.Module.Entities.csproj", "{6A4B1E96-3932-4737-95E1-BB1D081DC5AB}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.Module.Data", "Calabonga.Microservice.Module.Data\Calabonga.Microservice.Module.Data.csproj", "{2376C6FA-BFFB-4050-B187-CC918C10E09C}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {721D20AC-A069-4CCA-8DBA-361D69B49A80}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {721D20AC-A069-4CCA-8DBA-361D69B49A80}.Debug|Any CPU.Build.0 = Debug|Any CPU - {721D20AC-A069-4CCA-8DBA-361D69B49A80}.Release|Any CPU.ActiveCfg = Release|Any CPU - {721D20AC-A069-4CCA-8DBA-361D69B49A80}.Release|Any CPU.Build.0 = Release|Any CPU - {516E0183-749E-4931-B297-21BBD45F0161}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {516E0183-749E-4931-B297-21BBD45F0161}.Debug|Any CPU.Build.0 = Debug|Any CPU - {516E0183-749E-4931-B297-21BBD45F0161}.Release|Any CPU.ActiveCfg = Release|Any CPU - {516E0183-749E-4931-B297-21BBD45F0161}.Release|Any CPU.Build.0 = Release|Any CPU - {6A4B1E96-3932-4737-95E1-BB1D081DC5AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6A4B1E96-3932-4737-95E1-BB1D081DC5AB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6A4B1E96-3932-4737-95E1-BB1D081DC5AB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6A4B1E96-3932-4737-95E1-BB1D081DC5AB}.Release|Any CPU.Build.0 = Release|Any CPU - {2376C6FA-BFFB-4050-B187-CC918C10E09C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2376C6FA-BFFB-4050-B187-CC918C10E09C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2376C6FA-BFFB-4050-B187-CC918C10E09C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2376C6FA-BFFB-4050-B187-CC918C10E09C}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {E8947A83-D797-4829-9C78-97F54EDD2EDB} - EndGlobalSection -EndGlobal diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/AppData.Common.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/AppData.Common.cs deleted file mode 100644 index 1db9845e..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/AppData.Common.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace $safeprojectname$ -{ - /// - /// Static data container - /// - public static partial class AppData - { - /// - /// Current service name - /// - public const string ServiceName = "IdentityModule"; - - /// - /// "SystemAdministrator" - /// - public const string SystemAdministratorRoleName = "Administrator"; - - /// - /// "BusinessOwner" - /// - public const string ManagerRoleName = "Manager"; - - /// - /// Roles - /// - public static IEnumerable Roles - { - get - { - yield return SystemAdministratorRoleName; - yield return ManagerRoleName; - } - } - - /// - /// IdentityServer4 path - /// - public const string AuthUrl = "/auth"; - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/AppData.Exceptions.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/AppData.Exceptions.cs deleted file mode 100644 index 0db07a4b..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/AppData.Exceptions.cs +++ /dev/null @@ -1,61 +0,0 @@ -namespace $safeprojectname$ -{ - public static partial class AppData - { - /// - /// Exception messages - /// - public static class Exceptions - { - /// - /// "An exception was thrown" - /// - public static string ThrownException => "An exception was thrown"; - - /// - /// "Invalid cast exception" - /// - public static string TypeConverterException => "Invalid cast exception"; - - /// - /// "User not registered in the system" - /// - public static string UserNotFoundException => "User not registered in the system"; - - /// - /// "Object not found" - /// - public static string NotFoundException => "Object not found"; - - /// - /// "Unauthorized access denied" - /// - public static string UnauthorizedException => "Unauthorized access denied"; - - /// - /// "Argument null exception" - /// - public static string ArgumentNullException => "Argument null exception"; - - /// - /// "File already exists" - /// - public static string FileAlreadyExists => "File already exists"; - - /// - /// "Some errors occurred while checking the entity" - /// - public static string EntityValidationException => "Some errors occurred while checking the entity"; - - /// - /// "Invalid operation exception was thrown" - /// - public static string InvalidOperationException => "Invalid operation exception was thrown"; - - /// - /// "Argument out of range" - /// - public static string ArgumentOutOfRangeException => "Argument out of range"; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/AppData.Messages.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/AppData.Messages.cs deleted file mode 100644 index 2f2547f0..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/AppData.Messages.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace $safeprojectname$ -{ - public static partial class AppData - { - /// - /// Common messages - /// - public static class Messages - { - /// - /// "User successfully registered" - /// - public static string UserSuccessfullyRegistered => "User successfully registered"; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/Calabonga.Microservice.IdentityModule.Core.csproj b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/Calabonga.Microservice.IdentityModule.Core.csproj deleted file mode 100644 index cb631906..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/Calabonga.Microservice.IdentityModule.Core.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - - - netcoreapp3.1 - - - diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/MyTemplate.vstemplate b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/MyTemplate.vstemplate deleted file mode 100644 index 0663327b..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/MyTemplate.vstemplate +++ /dev/null @@ -1,25 +0,0 @@ - - - Calabonga.Microservice.IdentityModule.Core - Contracts for microservice - CSharp - - - 1000 - true - Calabonga.Microservice.IdentityModule.Core - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - AppData.Common.cs - AppData.Exceptions.cs - AppData.Messages.cs - - - \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/__PreviewImage.png b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/__PreviewImage.png deleted file mode 100644 index f34977d9..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/__TemplateIcon.png b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Core/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationDbContext.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationDbContext.cs deleted file mode 100644 index 6f35a916..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationDbContext.cs +++ /dev/null @@ -1,26 +0,0 @@ -using $safeprojectname$.Base; -using $ext_projectname$.Entities; -using Microsoft.EntityFrameworkCore; - -namespace $safeprojectname$ -{ - /// - /// Database context for current application - /// - public class ApplicationDbContext : DbContextBase, IApplicationDbContext - { - public ApplicationDbContext(DbContextOptions options) - : base(options) { } - - #region System - - public DbSet Logs { get; set; } - - public DbSet Profiles { get; set; } - - /// - public DbSet Permissions { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationRole.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationRole.cs deleted file mode 100644 index 44d80b04..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationRole.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using Microsoft.AspNetCore.Identity; - -namespace $safeprojectname$ -{ - /// - /// Application role - /// - public class ApplicationRole : IdentityRole - { - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationUser.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationUser.cs deleted file mode 100644 index 3472b254..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationUser.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using Microsoft.AspNetCore.Identity; - -namespace $safeprojectname$ -{ - /// - /// Default user for application. - /// Add profile data for application users by adding properties to the ApplicationUser class - /// - public class ApplicationUser : IdentityUser - { - /// - /// FirstName - /// - public string FirstName { get; set; } - - /// - /// LastName - /// - public string LastName { get; set; } - - /// - /// Profile identity - /// - public Guid? ApplicationUserProfileId { get; set; } - - /// - /// User Profile - /// - public virtual ApplicationUserProfile ApplicationUserProfile { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationUserProfile.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationUserProfile.cs deleted file mode 100644 index 818e21f5..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationUserProfile.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Collections.Generic; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace $safeprojectname$ -{ - /// - /// Represent person with login information (ApplicationUser) - /// - public class ApplicationUserProfile: Auditable - { - /// - /// Account - /// - public virtual ApplicationUser ApplicationUser { get; set; } - - /// - /// Microservice permission for policy-based authorization - /// - public ICollection Permissions { get; set; } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationUserStore.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationUserStore.cs deleted file mode 100644 index c4834b9b..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ApplicationUserStore.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; - -namespace $safeprojectname$ -{ - /// - /// Application store for user - /// - public class ApplicationUserStore : UserStore - { - public ApplicationUserStore(ApplicationDbContext context, IdentityErrorDescriber describer = null) - : base(context, describer) - { - - } - - /// - public override Task FindByIdAsync(string userId, CancellationToken cancellationToken = new CancellationToken()) - { - return Users - .Include(x => x.ApplicationUserProfile) - .ThenInclude(x => x.Permissions) - .FirstOrDefaultAsync(u => u.Id.ToString() == userId, cancellationToken: cancellationToken); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/Base/DbContextBase.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/Base/DbContextBase.cs deleted file mode 100644 index e08ebb56..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/Base/DbContextBase.cs +++ /dev/null @@ -1,264 +0,0 @@ -using System; -using System.Linq; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -using Calabonga.EntityFrameworkCore.Entities.Base; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; - -namespace $safeprojectname$.Base -{ - /// - /// Base DbContext with predefined configuration - /// - public abstract class DbContextBase : IdentityDbContext - { - private const string DefaultUserName = "Anonymous"; - - protected DbContextBase(DbContextOptions options) : base(options) - { - LastSaveChangesResult = new SaveChangesResult(); - } - - public SaveChangesResult LastSaveChangesResult { get; } - - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - /// - /// Saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// The number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override int SaveChanges(bool acceptAllChangesOnSuccess) - { - try - { - DbSaveChanges(); - return base.SaveChanges(acceptAllChangesOnSuccess); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - public override int SaveChanges() - { - try - { - DbSaveChanges(); - return base.SaveChanges(); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - private void DbSaveChanges() - { - var createdEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added); - foreach (var entry in createdEntries) - { - if (!(entry.Entity is IAuditable)) - { - continue; - } - - var creationDate = DateTime.Now.ToUniversalTime(); - var userName = entry.Property("CreatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("CreatedBy").CurrentValue; - var updatedAt = entry.Property("UpdatedAt").CurrentValue; - var createdAt = entry.Property("CreatedAt").CurrentValue; - if (createdAt != null) - { - if (DateTime.Parse(createdAt.ToString()).Year > 1970) - { - entry.Property("CreatedAt").CurrentValue = ((DateTime)createdAt).ToUniversalTime(); - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - - if (updatedAt != null) - { - if (DateTime.Parse(updatedAt.ToString()).Year > 1970) - { - entry.Property("UpdatedAt").CurrentValue = ((DateTime)updatedAt).ToUniversalTime(); - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - - entry.Property("CreatedBy").CurrentValue = userName; - entry.Property("UpdatedBy").CurrentValue = userName; - - LastSaveChangesResult.AddMessage($"ChangeTracker has new entities: {entry.Entity.GetType()}"); - } - - var updatedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified); - foreach (var entry in updatedEntries) - { - if (entry.Entity is IAuditable) - { - var userName = entry.Property("UpdatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("UpdatedBy").CurrentValue; - entry.Property("UpdatedAt").CurrentValue = DateTime.Now.ToUniversalTime(); - entry.Property("UpdatedBy").CurrentValue = userName; - } - - LastSaveChangesResult.AddMessage($"ChangeTracker has modified entities: {entry.Entity.GetType()}"); - } - } - - /// - /// Configures the schema needed for the identity framework. - /// - /// - /// The builder being used to construct the model for this context. - /// - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - var applyGenericMethod = typeof(ModelBuilder).GetMethods(BindingFlags.Instance | BindingFlags.Public).First(x => x.Name == "ApplyConfiguration"); - foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters)) - { - foreach (var item in type.GetInterfaces()) - { - if (!item.IsConstructedGenericType || item.GetGenericTypeDefinition() != typeof(IEntityTypeConfiguration<>)) - { - continue; - } - - var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(item.GenericTypeArguments[0]); - applyConcreteMethod.Invoke(builder, new[] { Activator.CreateInstance(type) }); - break; - } - } - - builder.EnableAutoHistory(2048); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/Calabonga.Microservice.IdentityModule.Data.csproj b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/Calabonga.Microservice.IdentityModule.Data.csproj deleted file mode 100644 index 94ed5e8c..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/Calabonga.Microservice.IdentityModule.Data.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - - netcoreapp3.1 - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/DatabaseInitialization/DatabaseInitializer.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/DatabaseInitialization/DatabaseInitializer.cs deleted file mode 100644 index 437bd8fe..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/DatabaseInitialization/DatabaseInitializer.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using $ext_projectname$.Core; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.DatabaseInitialization -{ - /// - /// Database Initializer - /// - public static class DatabaseInitializer - { - public static async void Seed(IServiceProvider serviceProvider) - { - using var scope = serviceProvider.CreateScope(); - await using var context = scope.ServiceProvider.GetService(); - - // Should be uncomment when using UseSqlServer() settings or any other provider. - // This is should not be used when UseInMemoryDatabase() - // context.Database.Migrate(); - - var roles = AppData.Roles.ToArray(); - - foreach (var role in roles) - { - var roleManager = scope.ServiceProvider.GetRequiredService>(); - if (!context.Roles.Any(r => r.Name == role)) - { - await roleManager.CreateAsync(new ApplicationRole { Name = role, NormalizedName = role.ToUpper() }); - } - } - - #region developer - - var developer1 = new ApplicationUser - { - Email = "microservice@yopmail.com", - NormalizedEmail = "MICROSERVICE@YOPMAIL.COM", - UserName = "microservice@yopmail.com", - FirstName = "Microservice", - LastName = "Administrator", - NormalizedUserName = "MICROSERVICE@YOPMAIL.COM", - PhoneNumber = "+79000000000", - EmailConfirmed = true, - PhoneNumberConfirmed = true, - SecurityStamp = Guid.NewGuid().ToString("D"), - ApplicationUserProfile = new ApplicationUserProfile - { - CreatedAt = DateTime.Now, - CreatedBy = "SEED", - Permissions = new List - { - new MicroservicePermission - { - CreatedAt = DateTime.Now, - CreatedBy = "SEED", - PolicyName = "Logs:UserRoles:View", - Description = "Access policy for Logs controller user view" - } - } - } - }; - - if (!context.Users.Any(u => u.UserName == developer1.UserName)) - { - var password = new PasswordHasher(); - var hashed = password.HashPassword(developer1, "123qwe!@#"); - developer1.PasswordHash = hashed; - var userStore = scope.ServiceProvider.GetService(); - var result = await userStore.CreateAsync(developer1); - if (!result.Succeeded) - { - throw new InvalidOperationException("Cannot create account"); - } - - var userManager = scope.ServiceProvider.GetService>(); - foreach (var role in roles) - { - var roleAdded = await userManager.AddToRoleAsync(developer1, role); - if (roleAdded.Succeeded) - { - await context.SaveChangesAsync(); - } - } - } - #endregion - - await context.SaveChangesAsync(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/IApplicaitonDbContext.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/IApplicaitonDbContext.cs deleted file mode 100644 index 1e1980d5..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/IApplicaitonDbContext.cs +++ /dev/null @@ -1,33 +0,0 @@ -using $ext_projectname$.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.ChangeTracking; -using Microsoft.EntityFrameworkCore.Infrastructure; - -namespace $safeprojectname$ -{ - /// - /// Abstraction for Database (EntityFramework) - /// - public interface IApplicationDbContext - { - #region System - - DbSet Logs { get; set; } - - DbSet Users { get; set; } - - DbSet Profiles { get; set; } - - DbSet Permissions { get; set; } - - DatabaseFacade Database { get; } - - ChangeTracker ChangeTracker { get; } - - DbSet Set() where TEntity : class; - - int SaveChanges(); - - #endregion - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/MicroservicePermission.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/MicroservicePermission.cs deleted file mode 100644 index 2d8a1244..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/MicroservicePermission.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace $safeprojectname$ -{ - /// - /// User permission for microservice - /// - public class MicroservicePermission: Auditable - { - /// - /// Application User profile identifier - /// - public Guid ApplicationUserProfileId { get; set; } - - /// - /// Application User Profile - /// - public virtual ApplicationUserProfile ApplicationUserProfile { get; set; } - - /// - /// Authorize attribute policy name - /// - public string PolicyName { get; set; } - - /// - /// Description for current permission - /// - public string Description { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/ApplicationUserModelConfiguration.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/ApplicationUserModelConfiguration.cs deleted file mode 100644 index b74b55de..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/ApplicationUserModelConfiguration.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace $safeprojectname$.ModelConfigurations -{ - /// - /// Entity Type Configuration for entity - /// - - public class ApplicationUserModelConfiguration : IEntityTypeConfiguration - { - - /// - /// Configures the entity of type . - /// - /// The builder to be used to configure the entity type. - public void Configure(EntityTypeBuilder builder) - { - builder.Property(x => x.LastName).HasMaxLength(128).IsRequired(); - builder.Property(x => x.FirstName).HasMaxLength(128).IsRequired(); - builder.Property(x => x.ApplicationUserProfileId).IsRequired(false); - - builder.HasOne(x => x.ApplicationUserProfile); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/ApplicationUserProfileModelConfiguration.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/ApplicationUserProfileModelConfiguration.cs deleted file mode 100644 index c5a6e74a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/ApplicationUserProfileModelConfiguration.cs +++ /dev/null @@ -1,26 +0,0 @@ -using $safeprojectname$.ModelConfigurations.Base; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace $safeprojectname$.ModelConfigurations -{ - /// - /// Entity Type Configuration for entity - /// - - public class ApplicationUserProfileModelConfiguration : AuditableModelConfigurationBase - { - protected override void AddBuilder(EntityTypeBuilder builder) - { - builder.HasMany(x => x.Permissions); - - builder.HasOne(x => x.ApplicationUser) - .WithOne(x => x.ApplicationUserProfile) - .HasForeignKey(x => x.ApplicationUserProfileId); - } - - protected override string TableName() - { - return "ApplicationUserProfiles"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/Base/AuditableModelConfigurationBase.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/Base/AuditableModelConfigurationBase.cs deleted file mode 100644 index 8890882b..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/Base/AuditableModelConfigurationBase.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace $safeprojectname$.ModelConfigurations.Base -{ - /// - /// Audit-able Model Configuration base - /// - /// - public abstract class AuditableModelConfigurationBase : IEntityTypeConfiguration where T : Auditable - { - public void Configure(EntityTypeBuilder builder) - { - builder.ToTable(TableName()); - builder.HasKey(x => x.Id); - builder.Property(x => x.Id).IsRequired(); - - // audit - builder.Property(x => x.CreatedAt).IsRequired().HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)).IsRequired(); - builder.Property(x => x.CreatedBy).HasMaxLength(256).IsRequired(); - builder.Property(x => x.UpdatedAt).HasConversion(v => v.Value, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); - builder.Property(x => x.UpdatedBy).HasMaxLength(256); - - AddBuilder(builder); - } - - /// - /// Add custom properties for your entity - /// - /// - protected abstract void AddBuilder(EntityTypeBuilder builder); - - /// - /// Table name - /// - /// - protected abstract string TableName(); - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/Base/IdentityModelConfigurationBase.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/Base/IdentityModelConfigurationBase.cs deleted file mode 100644 index 30a6fc0b..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/Base/IdentityModelConfigurationBase.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Calabonga.EntityFrameworkCore.Entities.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace $safeprojectname$.ModelConfigurations.Base -{ - /// - /// Audit-able Model Configuration base - /// - /// - public abstract class IdentityModelConfigurationBase : IEntityTypeConfiguration where T : Identity - { - public void Configure(EntityTypeBuilder builder) - { - builder.ToTable(TableName()); - builder.HasKey(x => x.Id); - builder.Property(x => x.Id).IsRequired(); - - AddBuilder(builder); - } - - /// - /// Add custom properties for your entity - /// - /// - protected abstract void AddBuilder(EntityTypeBuilder builder); - - /// - /// Table name - /// - /// - protected abstract string TableName(); - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/LogModelConfiguration.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/LogModelConfiguration.cs deleted file mode 100644 index f4eadddd..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/LogModelConfiguration.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using $safeprojectname$.ModelConfigurations.Base; -using $ext_projectname$.Entities; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace $safeprojectname$.ModelConfigurations -{ - /// - /// Entity Type Configuration for entity - /// - public class LogModelConfiguration: IdentityModelConfigurationBase - { - protected override void AddBuilder(EntityTypeBuilder builder) - { - builder.Property(x => x.Logger).HasMaxLength(255).IsRequired(); - builder.Property(x => x.Level).HasMaxLength(50).IsRequired(); - builder.Property(x => x.Message).HasMaxLength(4000).IsRequired(); - builder.Property(x => x.CreatedAt).HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)).IsRequired(); - builder.Property(x => x.ThreadId).HasMaxLength(255); - builder.Property(x => x.ExceptionMessage).HasMaxLength(2000); - } - - protected override string TableName() - { - return "Logs"; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/MicroservicePermissionModelConfiguration.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/MicroservicePermissionModelConfiguration.cs deleted file mode 100644 index e86c9941..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/ModelConfigurations/MicroservicePermissionModelConfiguration.cs +++ /dev/null @@ -1,26 +0,0 @@ -using $safeprojectname$.ModelConfigurations.Base; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace $safeprojectname$.ModelConfigurations -{ - /// - /// Entity Type Configuration for entity - /// - - public class MicroservicePermissionModelConfiguration : AuditableModelConfigurationBase - { - protected override void AddBuilder(EntityTypeBuilder builder) - { - builder.Property(x => x.PolicyName).HasMaxLength(64).IsRequired(); - builder.Property(x => x.Description).HasMaxLength(1024); - builder.Property(x => x.ApplicationUserProfileId).IsRequired(); - - builder.HasOne(x => x.ApplicationUserProfile).WithMany(x => x.Permissions); - } - - protected override string TableName() - { - return "MicroservicePermissions"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/MyTemplate.vstemplate b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/MyTemplate.vstemplate deleted file mode 100644 index 210d251e..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/MyTemplate.vstemplate +++ /dev/null @@ -1,45 +0,0 @@ - - - Calabonga.Microservice.IdentityModule.Data - Database for microservice - CSharp - - - 1000 - true - Calabonga.Microservice.IdentityModule.Data - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - DbContextBase.cs - - - DatabaseInitializer.cs - - - - AuditableModelConfigurationBase.cs - IdentityModelConfigurationBase.cs - - ApplicationUserModelConfiguration.cs - ApplicationUserProfileModelConfiguration.cs - LogModelConfiguration.cs - MicroservicePermissionModelConfiguration.cs - - ApplicationDbContext.cs - ApplicationRole.cs - ApplicationUser.cs - ApplicationUserProfile.cs - ApplicationUserStore.cs - IApplicaitonDbContext.cs - MicroservicePermission.cs - - - \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/__PreviewImage.png b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/__PreviewImage.png deleted file mode 100644 index f34977d9..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/__TemplateIcon.png b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Data/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/Calabonga.Microservice.IdentityModule.Entities.csproj b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/Calabonga.Microservice.IdentityModule.Entities.csproj deleted file mode 100644 index 84de3298..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/Calabonga.Microservice.IdentityModule.Entities.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - netcoreapp3.1 - - - - - - - - - - - diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/Log.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/Log.cs deleted file mode 100644 index 01642a04..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/Log.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace $safeprojectname$ -{ - /// - /// Log entity for demo purposes only - /// - public class Log: Identity - { - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } - - public string Level { get; set; } - - public string Message { get; set; } - - public string ThreadId { get; set; } - - public string ExceptionMessage { get; set; } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/MyTemplate.vstemplate b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/MyTemplate.vstemplate deleted file mode 100644 index c2eea6ec..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/MyTemplate.vstemplate +++ /dev/null @@ -1,23 +0,0 @@ - - - Calabonga.Microservice.IdentityModule.Entities - Entities for microservice - CSharp - - - 1000 - true - Calabonga.Microservice.IdentityModule.Entities - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - Log.cs - - - \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/__PreviewImage.png b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/__PreviewImage.png deleted file mode 100644 index f34977d9..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/__TemplateIcon.png b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Entities/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesAuthentication.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesAuthentication.cs deleted file mode 100644 index 35b40976..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesAuthentication.cs +++ /dev/null @@ -1,61 +0,0 @@ -using $ext_projectname$.Core; -using $ext_projectname$.Data; -using $safeprojectname$.Infrastructure.Services; -using IdentityServer4.AccessTokenValidation; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// Authentication path - /// - public static class ConfigureServicesAuthentication - { - /// - /// Configure Authentication & Authorization - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - var url = configuration.GetSection("IdentityServer").GetValue("Url"); - services.AddAuthentication(options => - { - options.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; - options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; - options.DefaultSignInScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; - options.DefaultSignOutScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; - }) - .AddIdentityServerAuthentication(options => - { - options.SupportedTokens = SupportedTokens.Jwt; - options.Authority = $"{url}{AppData.AuthUrl}"; - options.EnableCaching = true; - options.RequireHttpsMetadata = false; - }); - - services.AddIdentityServer(options => - { - options.Authentication.CookieSlidingExpiration = true; - options.IssuerUri = $"{url}{AppData.AuthUrl}"; - options.Events.RaiseErrorEvents = true; - options.Events.RaiseInformationEvents = true; - options.Events.RaiseFailureEvents = true; - options.Events.RaiseSuccessEvents = true; - }) - .AddInMemoryPersistedGrants() - .AddDeveloperSigningCredential() - .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources()) - .AddInMemoryApiResources(IdentityServerConfig.GetApiResources()) - .AddInMemoryClients(IdentityServerConfig.GetClients()) - .AddInMemoryApiScopes(IdentityServerConfig.GetAPiScopes()) - .AddAspNetIdentity() - .AddJwtBearerClientAuthentication() - .AddProfileService(); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesBase.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesBase.cs deleted file mode 100644 index 08da9b81..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesBase.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using AutoMapper; -using $ext_projectname$.Data; -using $safeprojectname$.Extensions; -using $safeprojectname$.Infrastructure.Settings; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesBase - { - /// - /// ConfigureServices Services - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - services - .AddIdentity() - .AddUserStore() - .AddEntityFrameworkStores() - .AddDefaultTokenProviders(); - - services.AddDbContextPool(config => - { - // UseInMemoryDatabase - This for demo purposes only! - // Should uninstall package "Microsoft.EntityFrameworkCore.InMemory" and install what you need. - // For example: "Microsoft.EntityFrameworkCore.SqlServer" - // uncomment line below to use UseSqlServer(). Don't forget setup connection string in appSettings.json - config.UseInMemoryDatabase("DEMO_PURPOSES_ONLY"); - // config.UseSqlServer(configuration.GetConnectionString(nameof(ApplicationDbContext))); - }); - - services.AddAutoMapper(typeof(Startup)); - - services.AddUnitOfWork(); - - services.AddMemoryCache(); - - services.AddRouting(options => options.LowercaseUrls = true); - - services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); - - services.Configure(options => - { - // Password settings. - options.Password.RequireDigit = false; - options.Password.RequireLowercase = false; - options.Password.RequireNonAlphanumeric = false; - options.Password.RequireUppercase = false; - options.Password.RequiredLength = 6; - options.Password.RequiredUniqueChars = 0; - - // Lockout settings. - options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); - options.Lockout.MaxFailedAccessAttempts = 10; - options.Lockout.AllowedForNewUsers = true; - - // User settings. - options.User.AllowedUserNameCharacters = null; - options.User.RequireUniqueEmail = true; - }); - - services.AddOptions(); - services.Configure(configuration.GetSection(nameof(CurrentAppSettings))); - services.Configure(options => options.UseRouteSlugify()); - services.AddLocalization(); - services.AddHttpContextAccessor(); - services.AddResponseCaching(); - services.AddAuthorization(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesControllers.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesControllers.cs deleted file mode 100644 index bb8e9f97..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesControllers.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// Configure controllers - /// - public static class ConfigureServicesControllers - { - /// - /// Configure services - /// - /// - public static void ConfigureServices(IServiceCollection services) - { - services.AddControllers(); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesCors.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesCors.cs deleted file mode 100644 index 6c854c5a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesCors.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.Linq; -using Calabonga.Microservices.Web.Core; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// Cors configurations - /// - public class ConfigureServicesCors - { - /// - /// ConfigureServices - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - var origins = configuration.GetSection("Cors")?.GetSection("Origins")?.Value?.Split(','); - services.AddCors(options => - { - options.AddPolicy("CorsPolicy", builder => - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - if (origins != null && origins.Length > 0) - { - if (origins.Contains("*")) - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - builder.SetIsOriginAllowed(host => true); - builder.AllowCredentials(); - } - else - { - foreach (var origin in origins) - { - builder.WithOrigins(origin); - } - } - } - }); - }); - - services.UseMicroserviceAuthorizationPolicy(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesMediator.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesMediator.cs deleted file mode 100644 index 5c9e092f..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesMediator.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Extensions; -using $ext_projectname$.Data; -using $safeprojectname$.Extensions; -using $safeprojectname$.Infrastructure.Settings; -using $safeprojectname$.Mediator.Behaviors; -using Calabonga.UnitOfWork; -using MediatR; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesMediator - { - /// - /// ConfigureServices Services - /// - /// - public static void ConfigureServices(IServiceCollection services) - { - services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>)); - services.AddCommandAndQueries(typeof(Startup).Assembly); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesSwagger.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesSwagger.cs deleted file mode 100644 index ae1d9cf5..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesSwagger.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using $safeprojectname$.AppStart.SwaggerFilters; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerUI; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// Swagger configuration - /// - public static class ConfigureServicesSwagger - { - private const string AppTitle = "Microservice API (with IdentityServer4)"; - private static readonly string AppVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - private const string SwaggerConfig = "/swagger/v1/swagger.json"; - private const string SwaggerUrl = "api/manual"; - - /// - /// ConfigureServices Swagger services - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - services.AddSwaggerGen(options => - { - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = AppTitle, - Version = AppVersion, - Description = "Microservice API (with IdentityServer4) module API documentation. This template based on ASP.NET Core 3.1." - }); - options.ResolveConflictingActions(x => x.First()); - - var url = configuration.GetSection("IdentityServer").GetValue("Url"); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - Password = new OpenApiOAuthFlow - { - TokenUrl = new Uri($"{url}/auth/connect/token", UriKind.Absolute), - Scopes = new Dictionary - { - { "api1", "Default scope" } - } - } - } - }); - - options.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "oauth2" - }, - Scheme = "oauth2", - Name = "Bearer", - In = ParameterLocation.Header, - - }, - new List() - } - }); - - options.OperationFilter(); - }); - } - - /// - /// Set up some properties for swagger UI - /// - /// - public static void SwaggerSettings(SwaggerUIOptions settings) - { - settings.SwaggerEndpoint(SwaggerConfig, $"{AppTitle} v.{AppVersion}"); - settings.RoutePrefix = SwaggerUrl; - settings.DocumentTitle = "Microservice API"; - settings.DefaultModelExpandDepth(0); - settings.DefaultModelRendering(ModelRendering.Model); - settings.DefaultModelsExpandDepth(0); - settings.DocExpansion(DocExpansion.None); - settings.OAuthClientId("microservice1"); - settings.OAuthScopeSeparator(" "); - settings.OAuthClientSecret("secret"); - settings.DisplayRequestDuration(); - settings.OAuthAppName("Microservice API (with IdentityServer4) module API documentation"); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesValidators.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesValidators.cs deleted file mode 100644 index e5f38861..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/ConfigureServices/ConfigureServicesValidators.cs +++ /dev/null @@ -1,21 +0,0 @@ -using $safeprojectname$.ViewModels.AccountViewModels; -using FluentValidation; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesValidators - { - /// - /// ConfigureServices Services - /// - /// - public static void ConfigureServices(IServiceCollection services) - { - services.AddValidatorsFromAssembly(typeof(Startup).Assembly); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/Configures/ConfigureCommon.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/Configures/ConfigureCommon.cs deleted file mode 100644 index 38d6d30a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/Configures/ConfigureCommon.cs +++ /dev/null @@ -1,61 +0,0 @@ -using $ext_projectname$.Core; -using $safeprojectname$.AppStart.ConfigureServices; -using $safeprojectname$.Infrastructure.Auth; -using $safeprojectname$.Middlewares; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.AppStart.Configures -{ - /// - /// Pipeline configuration - /// - public static class ConfigureCommon - { - /// - /// Configure pipeline - /// - /// - /// - /// - public static void Configure(IApplicationBuilder app, IWebHostEnvironment env, AutoMapper.IConfigurationProvider mapper) - { - if (env.IsDevelopment()) - { - mapper.AssertConfigurationIsValid(); - app.UseDeveloperExceptionPage(); - } - else - { - mapper.CompileMappings(); - } - - app.UseDefaultFiles(); - app.UseStaticFiles(new StaticFileOptions - { - OnPrepareResponse = ctx => - { - ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=600"); - } - }); - - app.UseResponseCaching(); - - app.UseETagger(); - - app.Map($"{AppData.AuthUrl}", authServer => { authServer.UseIdentityServer(); }); - - app.UseMiddleware(typeof(ErrorHandlingMiddleware)); - - app.UseSwaggerUI(ConfigureServicesSwagger.SwaggerSettings); - - app.UseSwagger(); - - // Singleton setup for User Identity - UserIdentity.Instance.Configure(app.ApplicationServices.GetService()); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/Configures/ConfigureEndpoints.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/Configures/ConfigureEndpoints.cs deleted file mode 100644 index b6e8d8bb..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/Configures/ConfigureEndpoints.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.AspNetCore.Builder; - -namespace $safeprojectname$.AppStart.Configures -{ - /// - /// Configure pipeline - /// - public static class ConfigureEndpoints - { - /// - /// Configure Routing - /// - /// - public static void Configure(IApplicationBuilder app) - { - app.UseRouting(); - app.UseCors("CorsPolicy"); - app.UseAuthentication(); - app.UseAuthorization(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/IdentityServerConfig.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/IdentityServerConfig.cs deleted file mode 100644 index cd6e3411..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/IdentityServerConfig.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System.Collections.Generic; -using IdentityServer4; -using IdentityServer4.Models; - -namespace $safeprojectname$.AppStart -{ - /// - /// IdentityServer configuration - /// - public class IdentityServerConfig - { - /// - /// clients want to access resources (aka scopes) - /// - /// - public static IEnumerable GetClients() - { - // client credentials client - return new List - { - // resource owner password grant client - // you can create your own client - new Client - { - ClientId = "microservice1", - AllowAccessTokensViaBrowser = true, - IdentityTokenLifetime = 21600, - AuthorizationCodeLifetime = 21600, - AccessTokenLifetime = 21600, - AllowOfflineAccess = true, - RefreshTokenUsage = TokenUsage.ReUse, - RefreshTokenExpiration = TokenExpiration.Sliding, - SlidingRefreshTokenLifetime = 1296000, //in seconds = 15 days - AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, - RequireClientSecret = false, - AllowedScopes = { - IdentityServerConstants.StandardScopes.OpenId, - IdentityServerConstants.StandardScopes.Profile, - IdentityServerConstants.StandardScopes.Email, - IdentityServerConstants.StandardScopes.Address, - "api1" - } - } - }; - } - - /// - /// scopes define the resources in your system - /// - /// - public static IEnumerable GetIdentityResources() - { - return new List - { - new IdentityResources.OpenId(), - new IdentityResources.Email(), - new IdentityResources.Profile() - }; - } - - /// - /// IdentityServer4 API resources - /// - /// - public static IEnumerable GetApiResources() - { - return new List - { - new ApiResource("api1", "API Default") - }; - } - - public static IEnumerable GetAPiScopes() - { - yield return new ApiScope("api1"); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/MapperRegistration.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/MapperRegistration.cs deleted file mode 100644 index 19f3ace0..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/MapperRegistration.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using AutoMapper; -using $safeprojectname$.Infrastructure.Mappers.Base; - -namespace $safeprojectname$.AppStart -{ - /// - /// AutoMapper profiles registration - /// - public static class MapperRegistration - { - private static List GetProfiles() - { - return (from t in typeof(Startup).GetTypeInfo().Assembly.GetTypes() - where typeof(IAutoMapper).IsAssignableFrom(t) && !t.GetTypeInfo().IsAbstract - select t).ToList(); - } - - /// - /// Create and build mapper profiles - /// - /// - public static MapperConfiguration GetMapperConfiguration() - { - var profiles = GetProfiles(); - return new MapperConfiguration(cfg => - { - foreach (var item in profiles.Select(profile => (Profile)Activator.CreateInstance(profile))) - { - cfg.AddProfile(item); - } - }); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/SwaggerFilters/ApplySummariesOperationFilter.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/SwaggerFilters/ApplySummariesOperationFilter.cs deleted file mode 100644 index 232444d3..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/AppStart/SwaggerFilters/ApplySummariesOperationFilter.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace $safeprojectname$.AppStart.SwaggerFilters -{ - /// - /// Swagger Method Info Generator from summary for - /// - public class ApplySummariesOperationFilter : IOperationFilter - { - /// - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var controllerActionDescriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor; - if (controllerActionDescriptor == null) - { - return; - } - - var actionName = controllerActionDescriptor.ActionName; - if (actionName != "GetPaged") return; - var resourceName = controllerActionDescriptor.ControllerName; - operation.Summary = $"Returns paged list of the {resourceName} as IPagedList wrapped with OperationResult"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj deleted file mode 100644 index cbecfce0..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj +++ /dev/null @@ -1,46 +0,0 @@ - - - - netcoreapp3.1 - - - - - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/Account2Controller.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/Account2Controller.cs deleted file mode 100644 index a927ea2e..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/Account2Controller.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Threading.Tasks; -using $safeprojectname$.Infrastructure.Services; -using $safeprojectname$.ViewModels.AccountViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork.Controllers.Controllers; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Controllers -{ - /// - /// Account Controller - /// - [Route("api/[controller]")] - [Authorize] - public class Account2Controller : OperationResultController - { - private readonly IAccountService _accountService; - - /// - /// Register controller - /// - /// - public Account2Controller(IAccountService accountService) - { - _accountService = accountService; - } - - /// - /// Register new user. Success registration returns UserProfile for new user. - /// - /// - /// - [HttpPost("[action]")] - [AllowAnonymous] - [ProducesResponseType(200, Type = typeof(OperationResult))] - public async Task>> Register([FromBody]RegisterViewModel model) - { - if (!ModelState.IsValid) - { - return ValidationProblem(ModelState); - } - - return OperationResultResponse(await _accountService.RegisterAsync(model)); - } - - /// - /// Returns profile information for authenticated user - /// - /// - [HttpGet("[action]")] - [ProducesResponseType(200, Type = typeof(OperationResult))] - public async Task>> Profile() - { - if (!User.Identity.IsAuthenticated) - { - return OperationResultError(null, new MicroserviceUnauthorizedException()); - } - - var userId = _accountService.GetCurrentUserId(); - if (Guid.Empty == userId) - { - return BadRequest(); - } - - var claimsOperationResult = await _accountService.GetProfileAsync(userId.ToString()); - return Ok(claimsOperationResult); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/AccountController.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/AccountController.cs deleted file mode 100644 index 7eaeb796..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/AccountController.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System.Threading.Tasks; -using $safeprojectname$.Mediator.Account; -using $safeprojectname$.ViewModels.AccountViewModels; -using Calabonga.OperationResults; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Controllers -{ - /// - /// Account Controller - /// - [Route("api/[controller]")] - [Authorize] - public class AccountController : ControllerBase - { - private readonly IMediator _mediator; - - /// - /// Register controller - /// - public AccountController(IMediator mediator) - { - _mediator = mediator; - } - - /// - /// Register new user. Success registration returns UserProfile for new user. - /// - /// - /// - [HttpPost("[action]")] - [AllowAnonymous] - [ProducesResponseType(200, Type = typeof(OperationResult))] - public async Task>> Register([FromBody]RegisterViewModel model) - { - return Ok(await _mediator.Send(new RegisterRequest(model), HttpContext.RequestAborted)); - } - - /// - /// Returns profile information for authenticated user - /// - /// - [HttpGet("[action]")] - [ProducesResponseType(200, Type = typeof(OperationResult))] - public async Task>> Profile() - { - return await _mediator.Send(new ProfileRequest(), HttpContext.RequestAborted); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsReadOnlyController.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsReadOnlyController.cs deleted file mode 100644 index 8534fd6b..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsReadOnlyController.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Security.Claims; -using System.Threading; -using System.Threading.Tasks; -using $ext_projectname$.Core; -using $safeprojectname$.Mediator.LogsReadonly; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Controllers -{ - /// - /// ReadOnlyController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsReadonlyController : ControllerBase - { - private readonly IMediator _mediator; - - public LogsReadonlyController(IMediator mediator) - { - _mediator = mediator; - } - - [HttpGet("[action]")] - [Authorize(Policy = "Logs:UserRoles:View", Roles = AppData.SystemAdministratorRoleName)] - public async Task GetRoles() - { - //Get Roles for current user - return Ok(await _mediator.Send(new GetRolesRequest(), HttpContext.RequestAborted)); - } - - [HttpGet("[action]/{id:guid}")] - [ProducesResponseType(200)] - public async Task GetById(Guid id) - { - return Ok(await _mediator.Send(new LogGetByIdRequest(id), HttpContext.RequestAborted)); - } - - - [HttpGet("[action]")] - [ProducesResponseType(200)] - public async Task GetPaged([FromQuery] PagedListQueryParams queryParams) - { - return Ok(await _mediator.Send(new LogGetPagedRequest(queryParams), HttpContext.RequestAborted)); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsReadonly2Controller.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsReadonly2Controller.cs deleted file mode 100644 index 42bbda05..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsReadonly2Controller.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System.Security.Claims; - -using AutoMapper; - -using $ext_projectname$.Core; -using $ext_projectname$.Data; -using $ext_projectname$.Entities; -using $safeprojectname$.Infrastructure.Settings; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.Microservices.Core.Validators; -using Calabonga.UnitOfWork; -using Calabonga.UnitOfWork.Controllers.Controllers; - -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Options; - -namespace $safeprojectname$.Controllers -{ - /// - /// ReadOnlyController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsReadonly2Controller : ReadOnlyController - { - private readonly CurrentAppSettings _appSettings; - - /// - public LogsReadonly2Controller( - IOptions appSettings, - IUnitOfWork unitOfWork, - IMapper mapper) - : base(unitOfWork, mapper) - { - _appSettings = appSettings.Value; - } - - [HttpGet("[action]")] - [Authorize(Policy = "Logs:UserRoles:View", Roles = AppData.SystemAdministratorRoleName)] - public IActionResult GetRoles() - { - //Get Roles for current user - var roles = ClaimsHelper.GetValues((ClaimsIdentity)User.Identity, "role"); - return Ok($"Current user ({User.Identity.Name}) have following roles: {string.Join("|", roles)}"); - } - - /// - protected override PermissionValidationResult ValidateQueryParams(PagedListQueryParams queryParams) - { - if (queryParams.PageSize <= 0) - { - queryParams.PageSize = _appSettings.PageSize; - } - return new PermissionValidationResult(); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsWritable2Controller.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsWritable2Controller.cs deleted file mode 100644 index 7ea9b873..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsWritable2Controller.cs +++ /dev/null @@ -1,47 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Data; -using $ext_projectname$.Entities; -using $safeprojectname$.Infrastructure.Settings; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.Microservices.Core.Validators; -using Calabonga.UnitOfWork; -using Calabonga.UnitOfWork.Controllers.Controllers; -using Calabonga.UnitOfWork.Controllers.Factories; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Options; - -namespace $safeprojectname$.Controllers -{ - /// - /// WritableController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsWritable2Controller : WritableController - { - private readonly CurrentAppSettings _appSettings; - - /// - public LogsWritable2Controller( - IOptions appSettings, - IEntityManagerFactory entityManagerFactory, - IUnitOfWork unitOfWork, - IMapper mapper) - : base(entityManagerFactory, unitOfWork, mapper) - { - _appSettings = appSettings.Value; - } - - /// - protected override PermissionValidationResult ValidateQueryParams(PagedListQueryParams queryParams) - { - if (queryParams.PageSize <= 0) - { - queryParams.PageSize = _appSettings.PageSize; - } - return new PermissionValidationResult(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsWritableController.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsWritableController.cs deleted file mode 100644 index 2e97a95d..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Controllers/LogsWritableController.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.Threading.Tasks; -using $safeprojectname$.Mediator.LogsReadonly; -using $safeprojectname$.Mediator.LogsWritable; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.QueryParams; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Controllers -{ - /// - /// WritableController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsWritableController : ControllerBase - { - private readonly IMediator _mediator; - - public LogsWritableController(IMediator mediator) - { - _mediator = mediator; - } - - - [HttpGet("[action]/{id:guid}")] - [ProducesResponseType(200)] - public async Task GetById(Guid id) - { - return Ok(await _mediator.Send(new LogGetByIdRequest(id), HttpContext.RequestAborted)); - } - - - [HttpGet("[action]")] - [ProducesResponseType(200)] - public async Task GetPaged([FromQuery] PagedListQueryParams queryParams) - { - return Ok(await _mediator.Send(new LogGetPagedRequest(queryParams), HttpContext.RequestAborted)); - } - - [HttpGet("[action]")] - public async Task GetViewmodelForCreation() - { - return Ok(await _mediator.Send(new LogCreateViewModelRequest(), HttpContext.RequestAborted)); - } - - [HttpGet("[action]/{id:guid}")] - public async Task GetViewmodelForEditing(Guid id) - { - return Ok(await _mediator.Send(new LogUpdateViewModelRequest(id), HttpContext.RequestAborted)); - } - - [HttpPost("[action]")] - public async Task PostItem([FromBody]LogCreateViewModel model) - { - return Ok(await _mediator.Send(new LogPostItemRequest(model), HttpContext.RequestAborted)); - } - - [HttpPut("[action]")] - public async Task PutItem([FromBody]LogUpdateViewModel model) - { - return Ok(await _mediator.Send(new LogPutItemRequest(model), HttpContext.RequestAborted)); - } - - [HttpDelete("[action]/{id:guid}")] - public async Task DeleteItem(Guid id) - { - return Ok(await _mediator.Send(new LogDeleteItemRequest(id), HttpContext.RequestAborted)); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/ApplicationBuilderExtensions.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/ApplicationBuilderExtensions.cs deleted file mode 100644 index aa005461..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/ApplicationBuilderExtensions.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Text.RegularExpressions; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.ApplicationModels; -using Microsoft.AspNetCore.Routing; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.Extensions -{ - /// - /// Extensions for application class - /// - public static class ApplicationBuilderExtensions - { - /// - /// Use special route slugify for Pegasus routing - /// - /// - public static void UseRouteSlugify(this MvcOptions options) - { - options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer())); - } - } - - /// - /// Special route naming convention - /// - public class SlugifyParameterTransformer : IOutboundParameterTransformer - { - /// - public string TransformOutbound(object value) - { - return value == null - ? null - : Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower(); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/AssemblyExtensions.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/AssemblyExtensions.cs deleted file mode 100644 index 1eabfaa6..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/AssemblyExtensions.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace $safeprojectname$.Extensions -{ - /// - /// Assembly helpers - /// - public static class AssemblyExtensions - { - /// - /// Returns types - /// - /// - /// - /// - public static List GetTypesAssignableFrom(this Assembly assembly) - { - return assembly.GetTypesAssignableFrom(typeof(T)); - } - - private static List GetTypesAssignableFrom(this Assembly assembly, Type compareType) - { - var ret = new List(); - foreach (var type in assembly.DefinedTypes) - { - if (compareType.IsAssignableFrom(type) && compareType != type && !type.IsAbstract) - { - ret.Add(type); - } - } - return ret; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/DateTimeExtensions.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/DateTimeExtensions.cs deleted file mode 100644 index 78e7b5cd..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/DateTimeExtensions.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace $safeprojectname$.Extensions -{ - /// - /// DateTime extensions - /// - public static class DateTimeExtensions - { - /// - /// Each day enumeration - /// - /// - /// - /// - private static IEnumerable EachDay(DateTime from, DateTime thru) - { - for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1)) - { - yield return day; - } - } - - /// - /// Each month enumeration - /// - /// - /// - /// - private static IEnumerable EachMonth(DateTime from, DateTime thru) - { - for (var month = from.Date; month.Date <= thru.Date || month.Month == thru.Month; month = month.AddMonths(1)) - { - yield return month; - } - } - - /// - /// Enumerates all days in period - /// - /// - /// - /// - public static IEnumerable EachDayTo(this DateTime dateFrom, DateTime dateTo) - { - return EachDay(dateFrom, dateTo); - } - - /// - /// Enumerates all months in period - /// - /// - /// - /// - public static IEnumerable EachMonthTo(this DateTime dateFrom, DateTime dateTo) - { - return EachMonth(dateFrom, dateTo); - } - - - /// - /// Total Month count between two dates - /// - /// - /// - /// - public static int TotalMonths(this DateTime start, DateTime end) - { - return (start.Year * 12 + start.Month) - (end.Year * 12 + end.Month); - } - - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/EntityValidatorExtensions.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/EntityValidatorExtensions.cs deleted file mode 100644 index b574f8cb..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/EntityValidatorExtensions.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections.Generic; -using Calabonga.Microservices.Core.Validators; - -namespace $safeprojectname$.Extensions -{ - /// - /// Entity Validator Extensions - /// - public static class EntityValidatorExtensions - { - /// - /// Returns validator from validation results - /// - /// - /// - public static ValidationContext GetResult(this List source) - { - return new ValidationContext(source); - } - - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/IdentityExtensions.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/IdentityExtensions.cs deleted file mode 100644 index a594b540..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Extensions/IdentityExtensions.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Security.Principal; -using Calabonga.Microservices.Core.Extensions; -using IdentityServer4.Extensions; - -namespace $safeprojectname$.Extensions -{ - /// - /// Extensions - /// - public static class IdentityExtensions - { - /// - /// Returns true/false user is owner - /// - /// - /// - /// - public static bool IsOwner(this IIdentity source, Guid userId) - { - return source.GetSubjectId().ToGuid() == userId; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/SwaggerFormAttribute.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/SwaggerFormAttribute.cs deleted file mode 100644 index da6e0db3..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/SwaggerFormAttribute.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; - -namespace $safeprojectname$.Infrastructure.Attributes -{ - /// - /// Custom attribute for Swagger Upload Form - /// - [AttributeUsage(AttributeTargets.Method)] - public sealed class SwaggerFormAttribute : Attribute - { - /// - public SwaggerFormAttribute(string parameterName, string description, bool hasFileUpload = true) - { - ParameterName = parameterName; - Description = description; - HasFileUpload = hasFileUpload; - } - - /// - /// UploadFile enabled - /// - public bool HasFileUpload { get; } - - /// - /// Name for the parameter - /// - public string ParameterName { get; } - - /// - /// Small description - /// - public string Description { get;} - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/SwaggerGroupAttribute.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/SwaggerGroupAttribute.cs deleted file mode 100644 index 4ca5bb62..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/SwaggerGroupAttribute.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; - -namespace $safeprojectname$.Infrastructure.Attributes -{ - /// - /// Swagger controller group attribute - /// - /// - [AttributeUsage(AttributeTargets.Class)] - public class SwaggerGroupAttribute : Attribute - { - /// - public SwaggerGroupAttribute(string groupName) - { - GroupName = groupName; - } - - /// - /// Group name - /// - public string GroupName { get; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/ValidateModelStateAttribute.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/ValidateModelStateAttribute.cs deleted file mode 100644 index 8b8ec358..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Attributes/ValidateModelStateAttribute.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Linq; -using Calabonga.OperationResults; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; - -namespace $safeprojectname$.Infrastructure.Attributes -{ - /// - /// Custom validation handler for availability to whit OperationResult - /// - public class ValidateModelStateAttribute : ActionFilterAttribute - { - /// - public override void OnActionExecuting(ActionExecutingContext context) - { - if (context.ModelState.IsValid) return; - var operation = OperationResult.CreateResult(); - var messages = context.ModelState.Values.SelectMany(x => x.Errors.Select(xx => xx.ErrorMessage)); - var message = string.Join(" ", messages); - operation.AddError(message); - context.Result = new OkObjectResult(operation); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/ApplicationClaimsPrincipalFactory.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/ApplicationClaimsPrincipalFactory.cs deleted file mode 100644 index 5de1760f..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/ApplicationClaimsPrincipalFactory.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System.Linq; -using System.Security.Claims; -using System.Threading.Tasks; -using $ext_projectname$.Data; -using IdentityModel; -using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.Options; - -namespace $safeprojectname$.Infrastructure.Auth -{ - /// - /// Application Claims custom factory - /// - public class ApplicationClaimsPrincipalFactory : UserClaimsPrincipalFactory - { - /// - public ApplicationClaimsPrincipalFactory( - UserManager userManager, - RoleManager roleManager, - IOptions optionsAccessor) - : base(userManager, roleManager, optionsAccessor) - { - - } - - /// - /// Creates a from an user asynchronously. - /// - /// The user to create a from. - /// The that represents the asynchronous creation operation, containing the created . - public override async Task CreateAsync(ApplicationUser user) - { - var principal = await base.CreateAsync(user); - - if (user.ApplicationUserProfile?.Permissions != null) - { - var permissions = user.ApplicationUserProfile.Permissions.ToList(); - if (permissions.Any()) - { - permissions.ForEach(x => ((ClaimsIdentity)principal.Identity).AddClaim(new Claim(x.PolicyName, JwtClaimTypes.Role))); - } - } - if (!string.IsNullOrWhiteSpace(user.FirstName)) - { - ((ClaimsIdentity)principal.Identity).AddClaim(new Claim(JwtClaimTypes.GivenName, user.FirstName)); - } - - if (!string.IsNullOrWhiteSpace(user.LastName)) - { - ((ClaimsIdentity)principal.Identity).AddClaim(new Claim(ClaimTypes.Surname, user.LastName)); - } - - return principal; - } - - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/AuthorizationPolicyExtensions.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/AuthorizationPolicyExtensions.cs deleted file mode 100644 index 1fa84dc3..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/AuthorizationPolicyExtensions.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.Infrastructure.Auth -{ - /// - /// Authorization Policy registration - /// - public static class AuthorizationPolicyExtensions - { - /// - /// Registers custom for able to use authorization by policy - /// - /// - public static void UseMicroserviceAuthorizationPolicy(this IServiceCollection services) - { - services.AddSingleton(); - services.AddSingleton(); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/AuthorizationPolicyProvider.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/AuthorizationPolicyProvider.cs deleted file mode 100644 index 27c95c5b..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/AuthorizationPolicyProvider.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.Options; - -namespace $safeprojectname$.Infrastructure.Auth -{ - /// - /// - /// - public class AuthorizationPolicyProvider : DefaultAuthorizationPolicyProvider - { - private readonly AuthorizationOptions _options; - - /// - public AuthorizationPolicyProvider(IOptions options) : base(options) - { - _options = options.Value; - } - - /// - public override async Task GetPolicyAsync(string policyName) - { - var policyExists = await base.GetPolicyAsync(policyName); - if (policyExists != null) return policyExists; - policyExists = new AuthorizationPolicyBuilder().AddRequirements(new PermissionRequirement(policyName)).Build(); - _options.AddPolicy(policyName, policyExists); - return policyExists; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/IdentityServerCorsPolicy.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/IdentityServerCorsPolicy.cs deleted file mode 100644 index 22516ef2..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/IdentityServerCorsPolicy.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Threading.Tasks; -using IdentityServer4.Services; - -namespace $safeprojectname$.Infrastructure.Auth -{ - /// - /// Customized CORS policy for IdentityServer4 - /// - public class IdentityServerCorsPolicy : ICorsPolicyService - { - /// - public Task IsOriginAllowedAsync(string origin) - { - return Task.FromResult(true); - } - - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/MicroservicePermissionHandler.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/MicroservicePermissionHandler.cs deleted file mode 100644 index 1f0a4ab5..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/MicroservicePermissionHandler.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Security.Claims; -using System.Threading.Tasks; -using Calabonga.Microservices.Core; -using Microsoft.AspNetCore.Authorization; - -namespace $safeprojectname$.Infrastructure.Auth -{ - /// - /// Permission handler for custom authorization implementations - /// - public class MicroservicePermissionHandler : AuthorizationHandler - { - /// - protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) - { - var identity = (ClaimsIdentity) context.User.Identity; - var claim = ClaimsHelper.GetValue(identity, requirement.PermissionName); - if (claim == null) - { - return Task.CompletedTask; - } - - context.Succeed(requirement); - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/PermissionRequirement.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/PermissionRequirement.cs deleted file mode 100644 index 45ba12fe..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/PermissionRequirement.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Microsoft.AspNetCore.Authorization; - -namespace $safeprojectname$.Infrastructure.Auth -{ - /// - /// Permission requirement for user or service authorization - /// - public class PermissionRequirement : IAuthorizationRequirement - { - public PermissionRequirement(string permissionName) - { - PermissionName = permissionName; - } - - /// - /// Permission name - /// - public string PermissionName { get; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/UserIdentity.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/UserIdentity.cs deleted file mode 100644 index 6d6af80c..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Auth/UserIdentity.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Security.Claims; -using System.Security.Principal; -using Calabonga.Microservices.Core.Exceptions; -using Microsoft.AspNetCore.Http; - -namespace $safeprojectname$.Infrastructure.Auth -{ - /// - /// Identity helper for Requests operations - /// - public sealed class UserIdentity - { - private UserIdentity() { } - - public static UserIdentity Instance => Lazy.Value; - - public void Configure(IHttpContextAccessor httpContextAccessor) - { - ContextAccessor = httpContextAccessor ?? throw new MicroserviceArgumentNullException(nameof(IHttpContextAccessor)); - IsInitialized = true; - } - - public IIdentity User - { - get - { - if (IsInitialized) - { - return ContextAccessor.HttpContext.User.Identity.IsAuthenticated - ? ContextAccessor.HttpContext.User.Identity - : null; - } - throw new MicroserviceArgumentNullException($"{nameof(UserIdentity)} has not been initialized. Please use {nameof(UserIdentity)}.Instance.Configure(...) in Configure Application method in Startup.cs"); - } - } - - public IEnumerable Claims - { - get - { - if (User != null) - { - return ContextAccessor.HttpContext.User.Claims; - } - return null; - } - } - - private static readonly Lazy Lazy = new Lazy(() => new UserIdentity()); - - private bool IsInitialized { get; set; } - - private static IHttpContextAccessor ContextAccessor { get; set; } - - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/DependencyInjection/CommonRegistrations.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/DependencyInjection/CommonRegistrations.cs deleted file mode 100644 index 482828f1..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/DependencyInjection/CommonRegistrations.cs +++ /dev/null @@ -1,32 +0,0 @@ -using $ext_projectname$.Data; -using $safeprojectname$.Infrastructure.Auth; -using $safeprojectname$.Infrastructure.Services; -using IdentityServer4.Services; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.Infrastructure.DependencyInjection -{ - /// - /// Registrations for both points: API and Scheduler - /// - public partial class DependencyContainer - { - /// - /// Register - /// - /// - public static void Common(IServiceCollection services) - { - services.AddTransient(); - services.AddTransient(); - services.AddScoped(); - - // services - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/EntityManagers/LogManager.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/EntityManagers/LogManager.cs deleted file mode 100644 index f4628543..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/EntityManagers/LogManager.cs +++ /dev/null @@ -1,21 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.Validators; -using Calabonga.UnitOfWork.Controllers.Factories; -using Calabonga.UnitOfWork.Controllers.Managers; - -namespace $safeprojectname$.Infrastructure.Engine.EntityManagers -{ - /// - /// Entity manager for - /// - public class LogManager: EntityManager - { - /// - public LogManager(IMapper mapper, IViewModelFactory viewModelFactory, IEntityValidator validator) - : base(mapper, viewModelFactory, validator) - { - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/EntityValidators/LogValidator.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/EntityValidators/LogValidator.cs deleted file mode 100644 index 77d22084..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/EntityValidators/LogValidator.cs +++ /dev/null @@ -1,13 +0,0 @@ -using $ext_projectname$.Entities; -using Calabonga.Microservices.Core.Validators; - -namespace $safeprojectname$.Infrastructure.Engine.EntityValidators -{ - /// - /// Entity Validator for - /// - public class LogValidator: EntityValidator - { - - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/ViewModelFactories/LogViewModelFactory.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/ViewModelFactories/LogViewModelFactory.cs deleted file mode 100644 index 83267295..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Engine/ViewModelFactories/LogViewModelFactory.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Threading.Tasks; -using AutoMapper; -using $ext_projectname$.Data; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using Calabonga.UnitOfWork.Controllers.Factories; -using Microsoft.Extensions.Logging; - -namespace $safeprojectname$.Infrastructure.Engine.ViewModelFactories -{ - /// - /// ViewModel factory for - /// - public class LogViewModelFactory: ViewModelFactory - { - private readonly IUnitOfWork _context; - private readonly IMapper _mapper; - - public LogViewModelFactory( - IUnitOfWork context, - IMapper mapper) - { - _context = context; - _mapper = mapper; - } - - /// - public override Task> GenerateForCreateAsync() - { - var operation = OperationResult.CreateResult(); - operation.Result = new LogCreateViewModel() - { - CreatedAt = DateTime.Now, - Level = LogLevel.Information.ToString(), - Logger = "Demo purposes only", - Message = $"This is demo message {DateTime.Now}" - }; - return Task.FromResult(operation); - } - - /// - public override async Task> GenerateForUpdateAsync(Guid id) - { - var operation = OperationResult.CreateResult(); - var entity = await _context.GetRepository().GetFirstOrDefaultAsync(predicate: x => x.Id == id); - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("ViewModel generated for Log entity. Please see Additional information in DataObject").AddData(new { Identifier = id }); - - return operation; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Helpers/ValidationContextHelper.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Helpers/ValidationContextHelper.cs deleted file mode 100644 index 923a379b..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Helpers/ValidationContextHelper.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.ObjectModel; -using System.ComponentModel.DataAnnotations; - -namespace $safeprojectname$.Infrastructure.Helpers -{ - /// - /// ValidationContext Helper for validation operations - /// - public static class ValidationContextHelper - { - /// - /// Returns validation results of IValidatableObject - /// - /// - /// - /// - /// - public static bool TryValidate(object obj, out Collection results, ValidationContext validationContext = null) - { - var context = validationContext ?? new ValidationContext(obj, serviceProvider: null, items: null); - results = new Collection(); - return Validator.TryValidateObject(obj, context, results, validateAllProperties: true); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/ApplicationUserProfileMapperConfiguration.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/ApplicationUserProfileMapperConfiguration.cs deleted file mode 100644 index 9fbf0c25..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/ApplicationUserProfileMapperConfiguration.cs +++ /dev/null @@ -1,19 +0,0 @@ -using $ext_projectname$.Data; -using $safeprojectname$.Infrastructure.Mappers.Base; -using $safeprojectname$.ViewModels.AccountViewModels; - -namespace $safeprojectname$.Infrastructure.Mappers -{ - /// - /// Mapper Configuration for entity Person - /// - public class ApplicationUserProfileMapperConfiguration : MapperConfigurationBase - { - /// - public ApplicationUserProfileMapperConfiguration() - { - CreateMap() - .ForAllOtherMembers(x => x.Ignore()); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/IAutoMapper.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/IAutoMapper.cs deleted file mode 100644 index 30150fdf..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/IAutoMapper.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace $safeprojectname$.Infrastructure.Mappers.Base -{ - /// - /// The stub for reflection helper profiles registrations - /// - public interface IAutoMapper { } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/MapperConfigurationBase.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/MapperConfigurationBase.cs deleted file mode 100644 index 8b01c887..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/MapperConfigurationBase.cs +++ /dev/null @@ -1,10 +0,0 @@ -using AutoMapper; - -namespace $safeprojectname$.Infrastructure.Mappers.Base { - - /// - /// Base class for mapper configuration. - /// All ViewModel that will be mapped should implement IAutoMapper - /// - public abstract class MapperConfigurationBase : Profile, IAutoMapper { } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/PagedListConverter.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/PagedListConverter.cs deleted file mode 100644 index ca98c68a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/Base/PagedListConverter.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using AutoMapper; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Infrastructure.Mappers.Base { - - /// - /// Generic converter for IPagedList collections - /// - /// - /// - public class PagedListConverter : ITypeConverter, IPagedList> { - - /// Performs conversion from source to destination type - /// Source object - /// Destination object - /// Resolution context - /// Destination object - public IPagedList Convert(IPagedList source, IPagedList destination, ResolutionContext context) { - if (source == null) return null; - var vm = source.Items.Select(m => context.Mapper.Map(m)).ToList(); - - - var pagedList = PagedList.From(source, (con)=> context.Mapper.Map>(con)); - // var pagedList = vm.ToPagedList(source.PageIndex, source.PageSize); - return pagedList; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/LogMapperConfiguration.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/LogMapperConfiguration.cs deleted file mode 100644 index 81c83047..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/LogMapperConfiguration.cs +++ /dev/null @@ -1,32 +0,0 @@ -using $ext_projectname$.Entities; -using $safeprojectname$.Infrastructure.Mappers.Base; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Infrastructure.Mappers -{ - /// - /// Mapper Configuration for entity Log - /// - public class LogMapperConfiguration : MapperConfigurationBase - { - /// - public LogMapperConfiguration() - { - CreateMap() - .ForMember(x => x.Id, o => o.Ignore()); - - CreateMap(); - - CreateMap(); - - CreateMap() - .ForMember(x => x.CreatedAt, o => o.Ignore()) - .ForMember(x => x.ThreadId, o => o.Ignore()) - .ForMember(x => x.ExceptionMessage, o => o.Ignore()); - - CreateMap, IPagedList>() - .ConvertUsing>(); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/UserMapperConfiguration.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/UserMapperConfiguration.cs deleted file mode 100644 index 40764c74..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Mappers/UserMapperConfiguration.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Security.Claims; -using $ext_projectname$.Data; -using $safeprojectname$.Infrastructure.Mappers.Base; -using $safeprojectname$.ViewModels.AccountViewModels; -using Calabonga.Microservices.Core; -using IdentityModel; - -namespace $safeprojectname$.Infrastructure.Mappers -{ - /// - /// Mapper Configuration for entity ApplicationUser - /// - public class UserMapperConfiguration : MapperConfigurationBase - { - /// - public UserMapperConfiguration() - { - CreateMap() - .ForMember(x => x.UserName, o => o.MapFrom(p => p.Email)) - .ForMember(x => x.Email, o => o.MapFrom(p => p.Email)) - .ForMember(x => x.EmailConfirmed, o => o.MapFrom(src => true)) - .ForMember(x => x.FirstName, o => o.MapFrom(p => p.FirstName)) - .ForMember(x => x.LastName, o => o.MapFrom(p => p.LastName)) - .ForMember(x => x.PhoneNumberConfirmed, o => o.MapFrom(src => true)) - .ForAllOtherMembers(x => x.Ignore()); - - CreateMap() - .ForMember(x => x.Id, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, JwtClaimTypes.Subject))) - .ForMember(x => x.PositionName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Actor))) - .ForMember(x => x.FirstName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, JwtClaimTypes.GivenName))) - .ForMember(x => x.LastName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Surname))) - .ForMember(x => x.Roles, o => o.MapFrom(claims => ClaimsHelper.GetValues(claims, JwtClaimTypes.Role))) - .ForMember(x => x.Email, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, JwtClaimTypes.Name))) - .ForMember(x => x.PhoneNumber, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, JwtClaimTypes.PhoneNumber))) - .ForAllOtherMembers(x => x.Ignore()); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/AccountService.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/AccountService.cs deleted file mode 100644 index a82163c7..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/AccountService.cs +++ /dev/null @@ -1,248 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Claims; -using System.Threading.Tasks; -using AutoMapper; -using $ext_projectname$.Core; -using $ext_projectname$.Data; -using $safeprojectname$.Infrastructure.Auth; -using $safeprojectname$.ViewModels.AccountViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.Microservices.Core.Extensions; -using Calabonga.Microservices.Core.Validators; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using IdentityModel; -using IdentityServer4.Extensions; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; - -namespace $safeprojectname$.Infrastructure.Services -{ - /// - /// Account service - /// - public class AccountService : IAccountService - { - private readonly IUnitOfWork _unitOfWork; - private readonly ILogger _logger; - private readonly ApplicationClaimsPrincipalFactory _claimsFactory; - private readonly IHttpContextAccessor _httpContext; - private readonly IMapper _mapper; - private readonly UserManager _userManager; - private readonly RoleManager _roleManager; - - public AccountService( - IUserStore userStore, - IOptions optionsAccessor, - IPasswordHasher passwordHasher, - IEnumerable> userValidators, - IEnumerable> passwordValidators, - ILookupNormalizer keyNormalizer, - IdentityErrorDescriber errors, - IServiceProvider services, - ILogger> loggerRole, - IEnumerable> roleValidators, - IUnitOfWork unitOfWork, - ILogger logger, - ILogger> loggerUser, - ApplicationClaimsPrincipalFactory claimsFactory, - IHttpContextAccessor httpContext, - IMapper mapper) - { - _unitOfWork = unitOfWork; - _logger = logger; - _claimsFactory = claimsFactory; - _httpContext = httpContext; - _mapper = mapper; - - // We need to created a custom instance for current service - // It'll help to use Transaction in the Unit Of Work - _userManager = new UserManager(userStore, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, loggerUser); - var roleStore = new RoleStore(_unitOfWork.DbContext); - _roleManager = new RoleManager(roleStore, roleValidators, keyNormalizer, errors, loggerRole); - } - - /// - public Guid GetCurrentUserId() - { - var identity = _httpContext.HttpContext?.User.Identity; - var identitySub = identity.GetSubjectId(); - return identitySub.ToGuid(); - } - - /// - /// Returns instance after successful registration - /// - /// - /// - public async Task> RegisterAsync(RegisterViewModel model) - { - var operation = OperationResult.CreateResult(); - var user = _mapper.Map(model); - await using var transaction = await _unitOfWork.BeginTransactionAsync(); - var result = await _userManager.CreateAsync(user, model.Password); - const string role = AppData.ManagerRoleName; - - if (result.Succeeded) - { - if (await _roleManager.FindByNameAsync(role) == null) - { - operation.Exception = new MicroserviceUserNotFoundException(); - operation.AddError(AppData.Exceptions.UserNotFoundException); - return await Task.FromResult(operation); - } - await _userManager.AddToRoleAsync(user, role); - await AddClaimsToUser(_userManager, user, role); - var profile = _mapper.Map(model); - var profileRepository = _unitOfWork.GetRepository(); - - await profileRepository.InsertAsync(profile); - await _unitOfWork.SaveChangesAsync(); - if (_unitOfWork.LastSaveChangesResult.IsOk) - { - var principal = await _claimsFactory.CreateAsync(user); - operation.Result = _mapper.Map(principal.Identity); - operation.AddSuccess(AppData.Messages.UserSuccessfullyRegistered); - _logger.LogInformation(operation.GetMetadataMessages()); - transaction.Commit(); - return await Task.FromResult(operation); - } - } - var errors = result.Errors.Select(x => $"{x.Code}: {x.Description}"); - operation.AddError(string.Join(", ", errors)); - operation.Exception = _unitOfWork.LastSaveChangesResult.Exception; - transaction.Rollback(); - return await Task.FromResult(operation); - } - - /// - /// Returns user profile - /// - /// - /// - public async Task> GetProfileAsync(string identifier) - { - var operation = OperationResult.CreateResult(); - var claimsPrincipal = await GetUserClaimsAsync(identifier); - operation.Result = _mapper.Map(claimsPrincipal.Identity); - return await Task.FromResult(operation); - } - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - /// - public async Task GetUserClaimsAsync(string identifier) - { - if (string.IsNullOrEmpty(identifier)) - { - throw new MicroserviceException(); - } - var userManager = _userManager; - var user = await userManager.FindByIdAsync(identifier); - if (user == null) - { - throw new MicroserviceUserNotFoundException(); - } - - var defaultClaims = await _claimsFactory.CreateAsync(user); - return defaultClaims; - } - - /// - /// Returns user by his identifier - /// - /// - /// - public Task GetByIdAsync(Guid id) - { - var userManager = _userManager; - return userManager.FindByIdAsync(id.ToString()); - } - - /// - /// Returns current user account information or null when user does not logged in - /// - /// - public async Task GetCurrentUserAsync() - { - var userManager = _userManager; - var userId = GetCurrentUserId().ToString(); - var user = await userManager.FindByIdAsync(userId); - return user; - } - - /// - public async Task> GetUsersByEmailsAsync(IEnumerable emails) - { - var userManager = _userManager; - var result = new List(); - foreach (var email in emails) - { - var user = await userManager.FindByEmailAsync(email); - if (user != null && !result.Contains(user)) - { - result.Add(user); - } - } - return await Task.FromResult(result); - } - - /// - /// Check roles for current user - /// - /// - /// - public async Task IsInRolesAsync(string[] roleNames) - { - var userManager = _userManager; - var userId = GetCurrentUserId().ToString(); - var user = await userManager.FindByIdAsync(userId); - if (user == null) - { - var resultUserNotFound = new PermissionValidationResult(); - resultUserNotFound.AddError(AppData.Exceptions.UnauthorizedException); - return await Task.FromResult(resultUserNotFound); - } - foreach (var roleName in roleNames) - { - var ok = await userManager.IsInRoleAsync(user, roleName); - if (ok) - { - return new PermissionValidationResult(); - } - } - - var result = new PermissionValidationResult(); - result.AddError(AppData.Exceptions.UnauthorizedException); - return result; - } - - /// - public async Task> GetUsersInRoleAsync(string roleName) - { - var userManager = _userManager; - return await userManager.GetUsersInRoleAsync(roleName); - } - - #region privates - - private async Task AddClaimsToUser(UserManager userManager, ApplicationUser user, string role) - { - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.Name, user.UserName)); - await userManager.AddClaimAsync(user, new Claim(JwtClaimTypes.GivenName, user.FirstName)); - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.Surname, user.LastName)); - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.Email, user.Email)); - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, role)); - } - - #endregion - } -} - diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/CacheService.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/CacheService.cs deleted file mode 100644 index 2643bef8..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/CacheService.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using Calabonga.Microservices.Core.Exceptions; -using Microsoft.Extensions.Caching.Memory; - -namespace $safeprojectname$.Infrastructure.Services -{ - /// - /// Cache service - /// - public class CacheService : ICacheService - { - private readonly IMemoryCache _cache; - private readonly TimeSpan _defaultSlidingExpiration = TimeSpan.FromSeconds(60); - - /// - public CacheService(IMemoryCache cache) - { - _cache = cache; - } - - /// - public TEntry Get(object key) - { - if (key == null) - { - throw new MicroserviceArgumentNullException(nameof(key)); - } - - return _cache.Get(key); - } - - /// - public void SetForMinute(object key, TEntry cacheEntry) - { - SetWithSlidingExpiration(key, cacheEntry, _defaultSlidingExpiration); - } - - /// - public void SetForThirtyMinutes(object key, TEntry cacheEntry) - { - SetWithSlidingExpiration(key, cacheEntry, TimeSpan.FromMinutes(30)); - } - - /// - /// Default set mechanism - /// - /// - /// - /// - /// - public void SetWithSlidingExpiration(object key, TEntry cacheEntry, TimeSpan slidingExpiration) - { - if (cacheEntry == null) - { - throw new MicroserviceArgumentNullException(nameof(cacheEntry)); - } - - if (key == null) - { - throw new MicroserviceArgumentNullException(nameof(key)); - } - - if (slidingExpiration.Ticks == 0) - { - slidingExpiration = _defaultSlidingExpiration; - } - - var options = new MemoryCacheEntryOptions().SetSlidingExpiration(slidingExpiration); - - _cache.Set(key, cacheEntry, options); - } - - /// - public TEntry GetOrCreate(TKey key, Func findIfNotFoundFunc) - { - return _cache.GetOrCreate(key, findIfNotFoundFunc); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/IAccountService.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/IAccountService.cs deleted file mode 100644 index de3288dc..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/IAccountService.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Security.Claims; -using System.Threading.Tasks; -using $ext_projectname$.Data; -using $safeprojectname$.ViewModels.AccountViewModels; -using Calabonga.Microservices.Core.Validators; -using Calabonga.OperationResults; - -namespace $safeprojectname$.Infrastructure.Services -{ - /// - /// Represent interface for account management - /// - public interface IAccountService - { - /// - /// Returns a collection of the by emails - /// - /// - /// - Task> GetUsersByEmailsAsync(IEnumerable emails); - - /// - /// Get User Id from HttpContext - /// - /// - Guid GetCurrentUserId(); - - /// - /// Returns instance after successful registration - /// - /// - /// - Task> RegisterAsync(RegisterViewModel model); - - /// - /// Returns user profile - /// - /// - /// - Task> GetProfileAsync(string identifier); - - /// - /// Returns User by user identifier - /// - /// - /// - Task GetByIdAsync(Guid id); - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - /// - Task GetUserClaimsAsync(string identifier); - - /// - /// Returns current user account information or null when user does not logged in - /// - /// - Task GetCurrentUserAsync(); - - /// - /// Check roles for current user - /// - /// - /// - Task IsInRolesAsync(string[] roleNames); - - /// - /// Returns all system administrators registered in the system - /// - /// - /// - Task> GetUsersInRoleAsync(string roleName); - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/ICacheService.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/ICacheService.cs deleted file mode 100644 index 8be8816d..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/ICacheService.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using Microsoft.Extensions.Caching.Memory; - -namespace $safeprojectname$.Infrastructure.Services -{ - /// - /// Cache service interface - /// - public interface ICacheService - { - /// - /// Get the entry from the cache - /// - /// - /// - TEntry Get(object key); - - /// - /// Sets entry cache for one minute sliding expiration - /// - /// - /// - /// - void SetForMinute(object key, TEntry cacheEntry); - - /// - /// Sets entry cache for 30 minutes sliding expiration - /// - /// - /// - /// - void SetForThirtyMinutes(object key, TEntry cacheEntry); - - /// - /// Sets entry cache for custom sliding expiration interval - /// - /// - /// - /// - /// - void SetWithSlidingExpiration(object key, TEntry cacheEntry, TimeSpan slidingExpiration); - - /// - /// Returns already exist entry or first put it to the cache and then return entry - /// - /// - /// - /// - /// - /// - TEntry GetOrCreate(TKey key, Func findIfNotFoundFunc); - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/ILogService.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/ILogService.cs deleted file mode 100644 index 37bb6f89..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/ILogService.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace $safeprojectname$.Infrastructure.Services -{ - /// - /// Interface for Business logic logger can save messages to database - /// - public interface ILogService - { - /// - /// Log information message - /// - /// - void LogInformation(string message); - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/IdentityProfileService.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/IdentityProfileService.cs deleted file mode 100644 index 16155e49..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/IdentityProfileService.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Linq; -using System.Threading.Tasks; -using Calabonga.Microservices.Core.Extensions; -using IdentityServer4.Extensions; -using IdentityServer4.Models; -using IdentityServer4.Services; - -namespace $safeprojectname$.Infrastructure.Services -{ - /// - /// Custom implementation of the IProfileService - /// - public class IdentityProfileService : IProfileService - { - private readonly IAccountService _accountService; - /// - /// Identity Profile Service - /// - /// - public IdentityProfileService(IAccountService accountService) - { - _accountService = accountService; - } - - /// - /// This method is called whenever claims about the user are requested (e.g. during token creation or via the user info endpoint) - /// - /// The context. - /// - public async Task GetProfileDataAsync(ProfileDataRequestContext context) - { - var identifier = context.Subject.GetSubjectId(); - var profile = await _accountService.GetUserClaimsAsync(identifier); - context.IssuedClaims = profile.Claims.ToList(); - } - - /// - /// Returns IsActive (IdentityServer4) - /// - /// - /// - public async Task IsActiveAsync(IsActiveContext context) - { - var identifier = context.Subject.GetSubjectId(); - var user = await _accountService.GetByIdAsync(identifier.ToGuid()); - context.IsActive = user != null; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/LogService.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/LogService.cs deleted file mode 100644 index 3c4fdaea..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Services/LogService.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using $ext_projectname$.Data; -using $ext_projectname$.Entities; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.UnitOfWork; -using Microsoft.Extensions.Logging; - -namespace $safeprojectname$.Infrastructure.Services -{ - /// - /// Business logic logger can save messages to database - /// - public class LogService : ILogService - { - private readonly IUnitOfWork _unitOfWork; - - /// - public LogService(IUnitOfWork unitOfWork) - { - _unitOfWork = unitOfWork; - } - /// - public void LogInformation(string message) - { - Log(LogLevel.Information, message); - } - - /// - /// Allows to save data logs to the database Logs table - /// - private void Log(LogLevel level, string message, Exception exception = null) - { - var logs = _unitOfWork.GetRepository(); - var log = new Log - { - CreatedAt = DateTime.UtcNow, - Level = level.ToString(), - Logger = GetType().Name, - Message = message, - ThreadId = "0", - ExceptionMessage = exception?.Message - }; - logs.Insert(log); - _unitOfWork.SaveChanges(); - if (!_unitOfWork.LastSaveChangesResult.IsOk) - { - throw new MicroserviceArgumentNullException(); - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Settings/CurrentAppSettings.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Settings/CurrentAppSettings.cs deleted file mode 100644 index 319e4c7a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Infrastructure/Settings/CurrentAppSettings.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace $safeprojectname$.Infrastructure.Settings -{ - /// - /// Represents configuration file with current application settings - /// - public class CurrentAppSettings - { - /// - /// Default page size - /// - public int PageSize { get; set; } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/Account/Profile.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/Account/Profile.cs deleted file mode 100644 index b1353601..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/Account/Profile.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; - -using Calabonga.AspNetCore.Controllers.Base; -using $safeprojectname$.Infrastructure.Services; -using $safeprojectname$.ViewModels.AccountViewModels; -using Calabonga.OperationResults; - -using IdentityServer4.Extensions; - -using Microsoft.AspNetCore.Http; - -namespace $safeprojectname$.Mediator.Account -{ - /// - /// Request: Profile - /// - public class ProfileRequest : RequestBase> - { - } - - /// - /// Response: Profile - /// - public class ProfileRequestHandler : OperationResultRequestHandlerBase - { - private readonly IAccountService _accountService; - private readonly IHttpContextAccessor _httpContextAccessor; - - public ProfileRequestHandler( - IAccountService accountService, - IHttpContextAccessor httpContextAccessor) - { - _accountService = accountService; - _httpContextAccessor = httpContextAccessor; - } - - public override async Task> Handle(ProfileRequest request, CancellationToken cancellationToken) - { - var user = _httpContextAccessor.HttpContext.User; - if (user != null) - { - return await _accountService.GetProfileAsync(user.Identity.GetSubjectId()); - } - - var operation = OperationResult.CreateResult(); - operation.AddWarning("User not found"); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/Account/Register.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/Account/Register.cs deleted file mode 100644 index 1fc4e4ee..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/Account/Register.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; - -using Calabonga.AspNetCore.Controllers.Base; -using $safeprojectname$.Infrastructure.Services; -using $safeprojectname$.ViewModels.AccountViewModels; -using Calabonga.OperationResults; - -namespace $safeprojectname$.Mediator.Account -{ - /// - /// Request: Register new account - /// - public class RegisterRequest : RequestBase> - { - public RegisterViewModel Model { get; } - - public RegisterRequest(RegisterViewModel model) - { - Model = model; - } - } - - /// - /// Response: Register new account - /// - public class RegisterRequestHandler : OperationResultRequestHandlerBase - { - private readonly IAccountService _accountService; - - public RegisterRequestHandler(IAccountService accountService) - { - _accountService = accountService; - } - - public override Task> Handle(RegisterRequest request, CancellationToken cancellationToken) - { - return _accountService.RegisterAsync(request.Model); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/Behaviors/ValidatorBehavior.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/Behaviors/ValidatorBehavior.cs deleted file mode 100644 index 7ea5d30f..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/Behaviors/ValidatorBehavior.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Calabonga.AspNetCore.Controllers.Base; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using FluentValidation; -using MediatR; - -namespace $safeprojectname$.Mediator.Behaviors -{ - /// - /// Base validator for requests - /// - /// - /// - public class ValidatorBehavior : IPipelineBehavior - where TRequest : IRequest - { - private readonly IEnumerable> _validators; - - public ValidatorBehavior(IEnumerable> validators) - { - _validators = validators; - } - - /// - /// Pipeline handler. Perform any additional behavior and await the delegate as necessary - /// - /// Incoming request - /// Cancellation token - /// Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler. - /// Awaitable task returning the - public Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) - { - var failures = _validators - .Select(x => x.Validate(new ValidationContext(request))) - .SelectMany(x => x.Errors) - .Where(x => x != null) - .ToList(); - - if (!failures.Any()) return next(); - - var type = typeof(TResponse); - if (!type.IsSubclassOf(typeof(OperationResult))) - { - var exception = new ValidationException(failures); - throw exception; - } - - var result = Activator.CreateInstance(type); - (result as OperationResult).AddError(new MicroserviceEntityValidationException()); - foreach (var failure in failures) - { - (result as OperationResult)?.AppendLog($"{failure.PropertyName}: {failure.ErrorMessage}"); - } - return Task.FromResult((TResponse) result); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/GetRoles.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/GetRoles.cs deleted file mode 100644 index c9f33edb..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/GetRoles.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Security.Claims; -using Calabonga.AspNetCore.Controllers.Base; -using Calabonga.Microservices.Core; -using MediatR; -using Microsoft.AspNetCore.Http; - -namespace $safeprojectname$.Mediator.LogsReadonly -{ - /// - /// Request: Returns user roles - /// - public class GetRolesRequest: RequestBase - { - - } - - public class GetRolesRequestHandler : RequestHandler - { - private readonly IHttpContextAccessor _httpContextAccessor; - - public GetRolesRequestHandler(IHttpContextAccessor httpContextAccessor) - { - _httpContextAccessor = httpContextAccessor; - } - - protected override string Handle(GetRolesRequest request) - { - var user = _httpContextAccessor.HttpContext.User; - var roles = ClaimsHelper.GetValues((ClaimsIdentity)user.Identity, "role"); - return $"Current user ({user.Identity.Name}) have following roles: {string.Join("|", roles)}"; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/LogGetById.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/LogGetById.cs deleted file mode 100644 index 7056e3c2..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/LogGetById.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Mediator.LogsReadonly -{ - /// - /// Request for Log by Identifier - /// - public class LogGetByIdRequest : GetByIdQuery - { - public LogGetByIdRequest(Guid id) : base(id) - { - } - } - - /// - /// Response for Request for Log by Identifier - /// - public class LogGetByIdRequestHandler : GetByIdHandlerBase - { - public LogGetByIdRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/LogGetPaged.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/LogGetPaged.cs deleted file mode 100644 index 0f2f63fc..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsReadonly/LogGetPaged.cs +++ /dev/null @@ -1,30 +0,0 @@ -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Mediator.LogsReadonly -{ - /// - /// Request for paged list of Logs - /// - public class LogGetPagedRequest : GetPagedQuery - { - public LogGetPagedRequest(PagedListQueryParams queryParams) : base(queryParams) - { - } - } - - /// - /// Request for paged list of Logs - /// - public class LogGetPagedRequestHandler : GetPagedHandlerBase - { - public LogGetPagedRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogCreateViewModel.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogCreateViewModel.cs deleted file mode 100644 index 5b64452c..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogCreateViewModel.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Threading.Tasks; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $safeprojectname$.ViewModels.LogViewModels; -using Microsoft.Extensions.Logging; - -namespace $safeprojectname$.Mediator.LogsWritable -{ - /// - /// Request: Returns ViewModel for entity Log creation - /// - public class LogCreateViewModelRequest: CreateViewModelQuery - { - - } - - /// - /// Response: Returns ViewModel for entity Log creation - /// - public class LogCreateViewModelRequestHandler : CreateViewModelHandlerBase - { - protected override ValueTask GenerateCreateViewModel() - { - return new ValueTask(new LogCreateViewModel - { - CreatedAt = DateTime.UtcNow, - Level = LogLevel.Information.ToString(), - Message = "Generated automatically", - Logger = "LogCreateViewModelRequestHandler", - ThreadId = "0" - }); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogDeleteItem.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogDeleteItem.cs deleted file mode 100644 index 98e42636..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogDeleteItem.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Mediator.LogsWritable -{ - /// - /// Request: Log delete - /// - public class LogDeleteItemRequest: DeleteByIdQuery - { - public LogDeleteItemRequest(Guid id) : base(id) - { - } - } - - /// - /// Request: Log delete - /// - public class LogDeleteItemRequestHandler : DeleteByIdHandlerBase - { - public LogDeleteItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogPostItem.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogPostItem.cs deleted file mode 100644 index 61a1db35..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogPostItem.cs +++ /dev/null @@ -1,29 +0,0 @@ -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Mediator.LogsWritable -{ - /// - /// Request: Log creation - /// - public class LogPostItemRequest: PostItemQuery - { - public LogPostItemRequest(LogCreateViewModel model) : base(model) - { - } - } - - /// - /// Request: Log creation - /// - public class LogPostItemRequestHandler : PostItemHandlerBase - { - public LogPostItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogPutItem.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogPutItem.cs deleted file mode 100644 index ff48a71f..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogPutItem.cs +++ /dev/null @@ -1,37 +0,0 @@ -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Mediator.LogsWritable -{ - /// - /// Request: Log edit - /// - public class LogPutItemRequest: PutItemQuery - { - public LogPutItemRequest(LogUpdateViewModel model) : base(model) - { - } - } - - /// - /// Request: Log creation - /// - public class LogPutItemRequestHandler : PutItemHandlerBase - { - public LogPutItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - - protected override OperationResult ProcessOperationResult(OperationResult operationResult, LogViewModel response) - { - operationResult.AppendLog("Successfully updated"); - operationResult.Result = response; - return operationResult; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogUpdateViewModel.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogUpdateViewModel.cs deleted file mode 100644 index 23b85cbd..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Mediator/LogsWritable/LogUpdateViewModel.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Mediator.LogsWritable -{ - /// - /// Request: Returns ViewModel for entity Log creation - /// - public class LogUpdateViewModelRequest: UpdateViewModelQuery - { - public LogUpdateViewModelRequest(Guid id) : base(id) - { - } - } - - /// - /// Response: Returns ViewModel for entity Log creation - /// - public class LogUpdateViewModelRequestHandler : UpdateViewModelHandlerBase - { - public LogUpdateViewModelRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Middlewares/ETagMiddleware.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Middlewares/ETagMiddleware.cs deleted file mode 100644 index 154f2cb0..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Middlewares/ETagMiddleware.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System.IO; -using System.Security.Cryptography; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Net.Http.Headers; - -namespace $safeprojectname$.Middlewares -{ - /// - /// ETagger extension - /// - public static class ApplicationBuilderExtensions - { - /// - /// Use Custom middleware - /// - /// - public static void UseETagger(this IApplicationBuilder app) - { - app.UseMiddleware(); - } - } - - /// - /// ETag middleware from Mads Kristensen. - /// See https://madskristensen.net/blog/send-etag-headers-in-aspnet-core/ - /// - public class ETagMiddleware - { - private readonly RequestDelegate _next; - - /// - public ETagMiddleware(RequestDelegate next) - { - _next = next; - } - - /// - /// Invoke middleware entry point - /// - /// - /// - public async Task InvokeAsync(HttpContext context) - { - var response = context.Response; - var originalStream = response.Body; - - using (var ms = new MemoryStream()) - { - response.Body = ms; - - await _next(context); - - if (IsEtagSupported(response)) - { - var checksum = CalculateChecksum(ms); - - response.Headers[HeaderNames.ETag] = checksum; - - if (context.Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var etag) && checksum == etag) - { - response.StatusCode = StatusCodes.Status304NotModified; - return; - } - } - - ms.Position = 0; - await ms.CopyToAsync(originalStream); - } - } - - private static bool IsEtagSupported(HttpResponse response) - { - if (response.StatusCode != StatusCodes.Status200OK) - return false; - - // The 100kb length limit is not based in science. Feel free to change - if (response.Body.Length > 100 * 1024) - return false; - - if (response.Headers.ContainsKey(HeaderNames.ETag)) - return false; - - return true; - } - - private static string CalculateChecksum(MemoryStream ms) - { - string checksum = ""; - - using (var algo = SHA1.Create()) - { - ms.Position = 0; - byte[] bytes = algo.ComputeHash(ms); - checksum = $"\"{WebEncoders.Base64UrlEncode(bytes)}\""; - } - - return checksum; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Middlewares/ErrorHandle.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Middlewares/ErrorHandle.cs deleted file mode 100644 index baa03412..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Middlewares/ErrorHandle.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Threading.Tasks; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; - -namespace $safeprojectname$.Middlewares -{ - /// - /// Custom error handler. It allows to view error messages on UI - /// - public class ErrorHandlingMiddleware - { - private readonly RequestDelegate _next; - - /// - public ErrorHandlingMiddleware(RequestDelegate next) - { - _next = next; - } - - /// - /// Invoke middle ware. Entry point - /// - /// - /// - public async Task Invoke(HttpContext context) - { - try - { - await _next(context); - } - catch (Exception ex) - { - await HandleExceptionAsync(context, ex); - } - } - - private static Task HandleExceptionAsync(HttpContext context, Exception exception) - { - try - { - var result = JsonConvert.SerializeObject(ExceptionHelper.GetMessages(exception), Formatting.Indented); - if (result?.Length > 4000) - { - return context.Response.WriteAsync("Error message to long. Please use DEBUG in method HandleExceptionAsync to handle a whole of text of the exception"); - } - return context.Response.WriteAsync(result); - } - catch - { - return context.Response.WriteAsync($"{exception.Message} For more information please use DEBUG in method HandleExceptionAsync to handle a whole of text of the exception"); - } - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/MyTemplate.vstemplate b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/MyTemplate.vstemplate deleted file mode 100644 index f11d4d45..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/MyTemplate.vstemplate +++ /dev/null @@ -1,159 +0,0 @@ - - - Calabonga.Microservice.IdentityModule.Web - API for microservice - CSharp - - - 1000 - true - Calabonga.Microservice.IdentityModule.Web - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - launchSettings.json - - - - ConfigureCommon.cs - ConfigureEndpoints.cs - - - ConfigureServicesAuthentication.cs - ConfigureServicesBase.cs - ConfigureServicesControllers.cs - ConfigureServicesCors.cs - ConfigureServicesMediator.cs - ConfigureServicesSwagger.cs - ConfigureServicesValidators.cs - - - ApplySummariesOperationFilter.cs - - IdentityServerConfig.cs - MapperRegistration.cs - - - Account2Controller.cs - AccountController.cs - LogsReadonly2Controller.cs - LogsReadOnlyController.cs - LogsWritable2Controller.cs - LogsWritableController.cs - - - ApplicationBuilderExtensions.cs - AssemblyExtensions.cs - DateTimeExtensions.cs - EntityValidatorExtensions.cs - IdentityExtensions.cs - - - - SwaggerFormAttribute.cs - SwaggerGroupAttribute.cs - ValidateModelStateAttribute.cs - - - ApplicationClaimsPrincipalFactory.cs - AuthorizationPolicyExtensions.cs - AuthorizationPolicyProvider.cs - IdentityServerCorsPolicy.cs - MicroservicePermissionHandler.cs - PermissionRequirement.cs - UserIdentity.cs - - - CommonRegistrations.cs - - - - LogManager.cs - - - LogValidator.cs - - - LogViewModelFactory.cs - - - - ValidationContextHelper.cs - - - - IAutoMapper.cs - MapperConfigurationBase.cs - PagedListConverter.cs - - ApplicationUserProfileMapperConfiguration.cs - LogMapperConfiguration.cs - UserMapperConfiguration.cs - - - AccountService.cs - CacheService.cs - IAccountService.cs - ICacheService.cs - IdentityProfileService.cs - ILogService.cs - LogService.cs - - - CurrentAppSettings.cs - - - - - Profile.cs - Register.cs - - - ValidatorBehavior.cs - - - GetRoles.cs - LogGetById.cs - LogGetPaged.cs - - - LogCreateViewModel.cs - LogDeleteItem.cs - LogPostItem.cs - LogPutItem.cs - LogUpdateViewModel.cs - - - - ErrorHandle.cs - ETagMiddleware.cs - - - - RegisterViewModel.cs - RegisterViewModelValidator.cs - UserProfileViewModel.cs - - - LogCreateViewModel.cs - LogUpdateViewModel.cs - LogViewModel.cs - - - appsettings.json - appsettings.Development.json - appsettings.Production.json - Program.cs - Startup.cs - tempkey.jwk - tempkey.rsa - - - \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Program.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Program.cs deleted file mode 100644 index 7627dbfe..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Program.cs +++ /dev/null @@ -1,39 +0,0 @@ -// --------------------------------------- -// Name: Microservice Template -// Author: Calabonga (calabonga.net) -// Version: 2.2.0 -// Based on: ASP.NET Core 3.1 -// Created Date: 2019-10-06 -// Updated Date 2020-09-27 -// --------------------------------------- - -using System; -using $ext_projectname$.Core; -using $ext_projectname$.Data.DatabaseInitialization; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -namespace $safeprojectname$ -{ - public class Program - { - public static void Main(string[] args) - { - var webHost = CreateHostBuilder(args).Build(); - using (var scope = webHost.Services.CreateScope()) - { - DatabaseInitializer.Seed(scope.ServiceProvider); - } - - Console.Title = $"{AppData.ServiceName} v.{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - webHost.Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Startup.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Startup.cs deleted file mode 100644 index 13d1c382..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/Startup.cs +++ /dev/null @@ -1,56 +0,0 @@ -using $safeprojectname$.AppStart.Configures; -using $safeprojectname$.AppStart.ConfigureServices; -using $safeprojectname$.Infrastructure.DependencyInjection; -using Calabonga.UnitOfWork.Controllers.DependencyContainer; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$ -{ - /// - /// Entry point - /// - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - /// - /// Configuration - /// - public IConfiguration Configuration { get; } - - /// - /// This method gets called by the runtime. Use this method to add services to the container. - /// - /// - public void ConfigureServices(IServiceCollection services) - { - ConfigureServicesBase.ConfigureServices(services, Configuration); - ConfigureServicesAuthentication.ConfigureServices(services, Configuration); - ConfigureServicesSwagger.ConfigureServices(services, Configuration); - ConfigureServicesCors.ConfigureServices(services, Configuration); - ConfigureServicesControllers.ConfigureServices(services); - ConfigureServicesMediator.ConfigureServices(services); - ConfigureServicesValidators.ConfigureServices(services); - - DependencyContainer.Common(services); - NimbleDependencyContainer.ConfigureServices(services); - } - /// - /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - /// - /// - /// - /// - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, AutoMapper.IConfigurationProvider mapper) - { - ConfigureCommon.Configure(app, env, mapper); - ConfigureEndpoints.Configure(app); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/RegisterViewModel.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/RegisterViewModel.cs deleted file mode 100644 index 96830cbc..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/RegisterViewModel.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace $safeprojectname$.ViewModels.AccountViewModels -{ - /// - /// Data transfer object for user registration - /// - public class RegisterViewModel - { - /// - /// FirstName - /// - [Required] - [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)] - [Display(Name = "First Name")] - public string FirstName { get; set; } - - /// - /// LastName - /// - [Required] - [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)] - [Display(Name = "Last Name")] - public string LastName { get; set; } - - /// - /// Email - /// - [Required] - [EmailAddress] - [Display(Name = "Email")] - public string Email { get; set; } - - /// - /// Password - /// - [Required] - [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] - [DataType(DataType.Password)] - [Display(Name = "Password")] - public string Password { get; set; } - - /// - /// Password confirmation - /// - [DataType(DataType.Password)] - [Display(Name = "Confirm password")] - [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] - public string ConfirmPassword { get; set; } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/RegisterViewModelValidator.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/RegisterViewModelValidator.cs deleted file mode 100644 index 4c0ef110..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/RegisterViewModelValidator.cs +++ /dev/null @@ -1,24 +0,0 @@ -using $safeprojectname$.Mediator.Account; -using FluentValidation; - -namespace $safeprojectname$.ViewModels.AccountViewModels -{ - /// - /// RegisterViewModel Validator - /// - public class RegisterRequestValidator : AbstractValidator - { - public RegisterRequestValidator() - { - RuleSet("default", () => - { - RuleFor(x => x.Model.Email).NotNull().EmailAddress(); - RuleFor(x => x.Model.FirstName).NotEmpty().NotNull().MaximumLength(50); - RuleFor(x => x.Model.LastName).NotEmpty().NotNull().MaximumLength(50); - RuleFor(x => x.Model.Password).NotNull().NotEmpty().MaximumLength(50); - RuleFor(x => x.Model.ConfirmPassword).NotNull().MaximumLength(50).Equal(x => x.Model.Password).When(x => !string.IsNullOrEmpty(x.Model.Password)); - }); - - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/UserProfileViewModel.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/UserProfileViewModel.cs deleted file mode 100644 index c300b746..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/AccountViewModels/UserProfileViewModel.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace $safeprojectname$.ViewModels.AccountViewModels -{ - /// - /// Application User Profile - /// - public class UserProfileViewModel - { - /// - /// Identifier - /// - public Guid Id { get; set; } - - /// - /// FirstName - /// - public string FirstName { get; set; } - - /// - /// LastName - /// - public string LastName { get; set; } - - /// - /// Email - /// - public string Email { get; set; } - - /// - /// User Roles - /// - public List Roles { get; set; } - - /// - /// User PhoneNumber - /// - public string PhoneNumber { get; set; } - - /// - /// Position Name - /// - public string PositionName { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogCreateViewModel.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogCreateViewModel.cs deleted file mode 100644 index ef1c0f1c..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogCreateViewModel.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; -using Calabonga.EntityFrameworkCore.Entities.Base; -using Microsoft.Extensions.Logging; - -namespace $safeprojectname$.ViewModels.LogViewModels -{ - /// - /// Data Transfer Object for Log entity - /// - public class LogCreateViewModel : IViewModel - { - /// - /// Log Created At - /// - [Required] - public DateTime CreatedAt { get; set; } - - /// - /// Service name or provider - /// - [Required] - [StringLength(255)] - public string Logger { get; set; } - - /// - /// Log level for logging. See - /// - [Required] - [StringLength(50)] - public string Level { get; set; } - - /// - /// Log Message - /// - [Required] - [StringLength(4000)] - public string Message { get; set; } - - /// - /// Thread identifier - /// - public string ThreadId { get; set; } - - /// - /// Exception message - /// - public string ExceptionMessage { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogUpdateViewModel.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogUpdateViewModel.cs deleted file mode 100644 index f10d6efb..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogUpdateViewModel.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace $safeprojectname$.ViewModels.LogViewModels -{ - /// - /// Log View model for Update operations - /// - public class LogUpdateViewModel : ViewModelBase - { - public string Logger { get; set; } - - public string Level { get; set; } - - public string Message { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogViewModel.cs b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogViewModel.cs deleted file mode 100644 index 7f07e20a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/ViewModels/LogViewModels/LogViewModel.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace $safeprojectname$.ViewModels.LogViewModels -{ - /// - /// Log ViewModel - /// - public class LogViewModel: ViewModelBase - { - /// - /// Created at - /// - public DateTime CreatedAt { get; set; } - - /// - /// Logger name - /// - public string Logger { get; set; } - - /// - /// Level - /// - public string Level { get; set; } - - /// - /// Message text - /// - public string Message { get; set; } - - /// - /// Thread ID - /// - public string ThreadId { get; set; } - - /// - /// - /// - public string ExceptionMessage { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/__PreviewImage.png b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/__PreviewImage.png deleted file mode 100644 index f34977d9..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/__TemplateIcon.png b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json deleted file mode 100644 index 1a1bae9d..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=;User ID=;Password=" - }, - "Logging": { - "IncludeScopes": false, - "Debug": { - "LogLevel": { - "Default": "Warning", - "System": "Information", - "Microsoft": "Information" - } - }, - "Console": { - "LogLevel": { - "Default": "Warning", - "System": "Information", - "Microsoft": "Information" - } - } - }, - "Cors": { - "Origins": "*" - }, - "IdentityServer": { - "Url": "http://localhost:10001" - }, - "CurrentAppSettings": { - "PageSize": 50 - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/appsettings.Production.json b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/appsettings.Production.json deleted file mode 100644 index 0e5d7f22..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/appsettings.Production.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=MicroserviceWithIdentityDb;Trusted_Connection=True;" - }, - "Logging": { - "IncludeScopes": false, - "Debug": { - "LogLevel": { - "Default": "Warning", //"Debug" - "System": "Information", - "Microsoft": "Information" - } - }, - "Console": { - "LogLevel": { - "Default": "Warning", //"Debug" - "System": "Information", - "Microsoft": "Information" - } - } - }, - "Cors": { - "Origins": "*" - }, - "IdentityServer": { - "Url": "http://localhost:4455" - }, - "CurrentAppSettings": { - "PageSize": 50 - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/appsettings.json b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/appsettings.json deleted file mode 100644 index d9d9a9bf..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/appsettings.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - }, - "AllowedHosts": "*" -} diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk deleted file mode 100644 index 15aac77f..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk +++ /dev/null @@ -1 +0,0 @@ -{"alg":"RS256","d":"MR0gmrThHp6iHjLVL8ofRvz30UDV-L3B0QBLey15bVRo-nTDpTduvPaNDdh3WmbDCCTyoZ4dfWY3YREMtD7PeoG3otgBxnIL6ZBEwvT2QrutJnuPNQ0wU2LVQCFbNRYaA1GebDeTQt7qpUxlqx_Dm8zDoOWYw52cAjkq0UuesCq7maI0_ffGGIOyv-yyHpmVpu9c5aakmdHeP4vj9P3HrLEc8OI2RwYgH1FflIexHOs0tjmskK2TB1HwGLBlgD5YX36tAWsxLRtNxAuZdKvmQxwVqEpkffuCfm3X8LE_7J6qXxcsoVOB_oyQm_1TUocuOLwrHnFab6UITjlusPP00Q","dp":"LiHZEkcE9c_w6Wt29WfVrqd7Kr4s_q-ApWZAMqdndJqbfoGUQYQ6F0x6U8P_UkUmyJTRCtGWRjwajDZI0f6St297xjg-jSO_2rbcpqvmAdYOZEAA6OM-CDWyN7MxhHNaA_piOK7DByV3oFp7jaQ_1U5BqAPLr9vp4_nOIyhHDMM","dq":"8KFJso4RZE6hJALNTGdSHRhxC4ulQhd-jP0pPft_IGLBQe5GceX3lEGi3He2MpzxIAVQpAZ7kOkLpunMBqQ9t75ROL5jNIA8z0cIf390sdWz53A1599InL2imX8oce5IAbqBUSuIB80-CtA4HGqvttAXGQN9Au6FZWBH-E3gbZE","e":"AQAB","kid":"ED43460F57D930E62A56FC8BEEF8A283","kty":"RSA","n":"1Sne51c04wn7MwM-oyZvXs8V37s5DwzcPZyGMjLwYeM3ysuMEhdCdwlTJbsNizD8hd2Y5cS3BfZzizsHWI6-t4bIrD4ySsvj_GitY4NgoW53zBDqGzNKibeVt4zoTmp0H2RTyDj0lK-7tuEx1elUFSoaaHSImV51lm7CQz7dI8T-z2vHGN6mVCYpzR8h7Zuz0UixV5LWHI3ulYOI0IApk7obbH-2X3xHC6zEJMgPnFJ1cjXP474Y-FslF1u7Dx8h0v0zeD-fJ12P6L8Nsgo0NP_4OBAtrHFfThnugQC5WEA2mFXNMS0N_8SgLZlavv-NLNS74QXbzJC59SkGS60vZQ","p":"2rhU-K-zyaRzg9mPTeQEo5bEUIyZEGY3nQJrLDMUbXQaUZ5Np9E_pNsVPy1gEUTukV-cbjRucvpwpMSgPS2qJGBv0UGX1TmFxwvSiysbuCTlUYzdcJ9AMr1H5sPZ_ZvHdwjWcVKcmisg6A5LrKgwCELy1mAvxlvalnyajCp9Bz8","q":"-X8WBAyWajXfWbv2mbqXVJOtEdbrOMkl1IAjfeWdKQ9Ee3IeIjNtIqyIE4xW4Ftixzopk2u7Rm0MNwn1gP1DeZWyRCuHzdt0_3b5tVDK5mm3FhTrlnVsTOFg4BeYhAdc5MLOki4tHZp6o0s25-_6buATm2fN_7kCxRXsuUrZZFs","qi":"slbCpR9QO_FXiU2ciHEhtZCN4Vj4wXfTtQj2G0-WooOUSan_SFZsAXEfA-ihE0Fl1xQtcMwcMUsD9EGDDNjC_7ESlUojU_AOWRX_b8AcTJU28wqnXj4DP6gwptiywL-agwWrjnBWu8dMCogU8-hJFp3f8ruIx06hVecZXGzR-v8"} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/tempkey.rsa b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/tempkey.rsa deleted file mode 100644 index 2dbfd2b8..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Calabonga.Microservice.IdentityModule.Web/tempkey.rsa +++ /dev/null @@ -1 +0,0 @@ -{"KeyId":"YV6cLgCDMZMat6HrRL-K6g","Parameters":{"D":"KPGMhbGs2Nnl881go6X6QtFvN7x9KHAxOKIrt00GWhJ/7tZKbY/wrAimXxHWLNj/t3t0f7yY/zgTEwbXhTRY2Qz0LS2vTCc5SW/PrtKPfoAlgiaxcl3AUwzL0CG/84f1RwiarJQ139PrQLZylr5m7Chr7t8SOcx04RhliJ50afsUU2DoQ2ydNHVkNFHmD4LtKsUTe1HW2YZLhKlaaof7I/B5CYDJhOMktvssZnYn6tldaCPLFhlb2qKqJ5IIoLRbxSW49OgknBxvRPFhvuNgJy5U0G5Zj6hnGqVYkFAWpy8SvKr+y3x3utHas+5ad0Tl4Jni2oY5Hy5CsbjVJyq1XQ==","DP":"vb5xD/KvgM3vrWWvbrPHn/dkxn3v093fG3fTqusD1J8H3VSDlLAXFl1yLme3aGHFdfqU6Kh0fm2ljp1hcxzaSqIG6nm/eXtQKlPmUCfhVgaQd6kKpBTNR+fKi2GmJnYPq/j9YOtbRrvgfEOJjcr9pPnwvm462NXY/whBU20/1/U=","DQ":"KKF2T1Yjrx5x3DxY6uu5eDKCULwtOj1WcRt3sknVytVuXzdnHALQYPx3GlZGd69Os2783YTl27bA568NGdRTTDgH1WsbUEJ/L6HnmMjF2c9tFOuJTNkt9liepi1DE+vweNP47J7vC56RnB53cJxH9NrUJgwLOrduk0KOg51S9O0=","Exponent":"AQAB","InverseQ":"F/c6r8Lz5GFEvZ4pVoANwiLBJ6ygoU0epbNSJOctlh1WXSqK6vubx9kLaKXiPwvL1lKI3wLli90hS27IMQ0TGRbx2whCsQmYkQbZ/N8bQFbqLq17QGjlOtHTVyb1xVdpWBsbUsm2CyNcrcLwehNq1BQKZGhuMzRS2vjWdALWV8E=","Modulus":"ozV6PBtB42xupEMGErHRRM2BHbBie/73jtJeCiHwYkvcdQCwckO0owQZ98At0e26h8u+dyJIZsi+YteiI8eacAtqvXa0LuBV9hU5k0HSpKPuCTCfFoy1cZtNIwMRmXL41lif5lJoaye87kKZ47UpUXDX3OtC2+7Z/BCbuV7bph+fmr0HenPWy+s7kgKR0z6Zvb7DrQcbYxdm1L5Ocym3u/MjUifwNd7jpXUvzKSoKhRbY8aXa47JDzWAxZRReFQQsfsnq5bxtcFG8lyeAVsn6hLGLwtwnAx/abTTITAkKCY/DAHHg8uTr52WO9vwLbsXOP9VMMg3GaQDByzbFj1wjQ==","P":"xJrNIiraGxuADMd6GKuB1RwE8gweioaxwJzoRNVX1fupwkEBY5se9ONOUTL7De+fmvnutM/2LzvtG48HQ1m4lcW9TOVRssUmIBaae4lV2o2CHiKbVCj3K97SK/CPqwVgInyeJiE429IVMWMIJAY7E3+0Elrgyl/Vmkj38b9Ni6s=","Q":"1IPhc5uKlqkbT0bBbOkAsWwMptls8kgtFG3acWHdsIxtHVWSUImMmhEVBPjyg8Zu9I1jbWxk3BhI3aJcSMNsvqXmiCFbuNsCNY0ph6DYdSLqEHBqaY5hKPSeruMi4SEQumvUXx+pQuyIsnyJxH/T5G8qOm++GvEHsjjVlryB/Kc="}} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Root.vstemplate b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Root.vstemplate deleted file mode 100644 index 24a9afa5..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/Root.vstemplate +++ /dev/null @@ -1,27 +0,0 @@ - - - Microservice Template with IdentityServer4 - This template gives you a possibility to start developing a microservices system with integrated UI (Swagger) and Authorization Server (IdentityServer4). Template developed for ASP.NET Core 3.1. - CSharp - - 1000 - true - Calabonga.Microservice.IdentityModule - true - Enabled - true - __TemplateIcon.png - __PreviewImage.png - - - - - - - Calabonga.Microservice.IdentityModule.Web\MyTemplate.vstemplate - Calabonga.Microservice.IdentityModule.Data\MyTemplate.vstemplate - Calabonga.Microservice.IdentityModule.Entities\MyTemplate.vstemplate - Calabonga.Microservice.IdentityModule.Core\MyTemplate.vstemplate - - - \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/__PreviewImage.png b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/__PreviewImage.png deleted file mode 100644 index f34977d9..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/__TemplateIcon.png b/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceIdentityModuleV3/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/AppData.Common.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/AppData.Common.cs deleted file mode 100644 index 76f4a2e4..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/AppData.Common.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Collections.Generic; - -namespace $safeprojectname$ -{ - /// - /// Static data container - /// - public static partial class AppData - { - /// - /// Current service name - /// - public const string ServiceName = "Module"; - - /// - /// "SystemAdministrator" - /// - public const string SystemAdministratorRoleName = "Administrator"; - - /// - /// "BusinessOwner" - /// - public const string ManagerRoleName = "Manager"; - - /// - /// Roles - /// - public static IEnumerable Roles - { - get - { - yield return SystemAdministratorRoleName; - yield return ManagerRoleName; - } - } - - /// - /// IdentityServer4 path - /// - public const string AuthUrl = "/auth"; - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/AppData.Exceptions.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/AppData.Exceptions.cs deleted file mode 100644 index c9d89424..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/AppData.Exceptions.cs +++ /dev/null @@ -1,61 +0,0 @@ -namespace $safeprojectname$ -{ - public static partial class AppData - { - /// - /// Exception messages - /// - public static class Exceptions - { - /// - /// "An exception was thrown" - /// - public static string ThrownException => "An exception was thrown"; - - /// - /// "Invalid cast exception" - /// - public static string TypeConverterException => "Invalid cast exception"; - - /// - /// "User not registered in the system" - /// - public static string UserNotFoundException => "User not registered in the system"; - - /// - /// "Object not found" - /// - public static string NotFoundException => "Object not found"; - - /// - /// "Unauthorized access denied" - /// - public static string UnauthorizedException => "Unauthorized access denied"; - - /// - /// "Argument null exception" - /// - public static string ArgumentNullException => "Argument null exception"; - - /// - /// "File already exists" - /// - public static string FileAlreadyExists => "File already exists"; - - /// - /// "Email Service Unavailable or SMTP provider error occupied" - /// - public static string EmailServiceUnavailable => "Email Service Unavailable or SMTP provider error occupied"; - - /// - /// "Some errors occurred while checking the entity" - /// - public static string EntityValidationException => "Some errors occurred while checking the entity"; - - /// - /// "Invalid operation exception was thrown" - /// - public static string InvalidOperationException => "Invalid operation exception was thrown"; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/AppData.Messages.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/AppData.Messages.cs deleted file mode 100644 index 44856b3c..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/AppData.Messages.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace $safeprojectname$ -{ - public static partial class AppData - { - /// - /// Common messages - /// - public static class Messages - { - - /// - /// "Entity successfully deleted" - /// - public static string EntitySuccessfullyDeleted => "Entity successfully deleted"; - - /// - /// "Automatically generated by {0}" - /// - public static string ViewModelFactoryGenerationText => "Automatically generated by {0}"; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Calabonga.Microservice.Module.Core.csproj b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Calabonga.Microservice.Module.Core.csproj deleted file mode 100644 index cb631906..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Calabonga.Microservice.Module.Core.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - - - netcoreapp3.1 - - - diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/EmailMessage.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/EmailMessage.cs deleted file mode 100644 index a0236c6d..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/EmailMessage.cs +++ /dev/null @@ -1,37 +0,0 @@ -namespace $safeprojectname$ -{ - /// - /// Mail Message to send - /// - public class EmailMessage : IEmailMessage - { - - /// - public EmailMessage() - { - Result = new SendEmailResult(); - } - - /// - public string MailTo { get; set; } - - /// - public string Subject { get; set; } - - /// - public string Body { get; set; } - - /// - /// Sent result info - /// - public SendEmailResult Result { get; } - - /// - /// Use HTML in the Body - /// - public bool IsHtml { get; set; } - - /// - public string MailFrom { get; set; } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceArgumentNullException.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceArgumentNullException.cs deleted file mode 100644 index 8d0a49af..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceArgumentNullException.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; - -namespace $safeprojectname$.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceArgumentNullException : Exception - { - public MicroserviceArgumentNullException() : base(AppData.Exceptions.ArgumentNullException) - { - - } - - public MicroserviceArgumentNullException(string message) : base(message) - { - - } - - public MicroserviceArgumentNullException(string message, Exception exception) : base(message, exception) - { - - } - - public MicroserviceArgumentNullException(Exception exception) : base(AppData.Exceptions.ArgumentNullException, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceEntityValidationException.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceEntityValidationException.cs deleted file mode 100644 index 9b3918cf..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceEntityValidationException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace $safeprojectname$.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceEntityValidationException : Exception - { - public MicroserviceEntityValidationException() : base(AppData.Exceptions.EntityValidationException) - { - - } - - public MicroserviceEntityValidationException(string message) : base(message) - { - - } - - public MicroserviceEntityValidationException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceException.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceException.cs deleted file mode 100644 index 3b848b8e..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace $safeprojectname$.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceException : Exception - { - public MicroserviceException() : base(AppData.Exceptions.ThrownException) - { - - } - - public MicroserviceException(string message) : base(message) - { - - } - - public MicroserviceException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceFileAlreadyExistsException.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceFileAlreadyExistsException.cs deleted file mode 100644 index 9ea13a19..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceFileAlreadyExistsException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace $safeprojectname$.Exceptions -{ - /// - /// FileAlreadyExists - /// - public class MicroserviceFileAlreadyExistsException : Exception - { - public MicroserviceFileAlreadyExistsException() : base(AppData.Exceptions.FileAlreadyExists) - { - - } - - public MicroserviceFileAlreadyExistsException(string message) : base(message) - { - - } - - public MicroserviceFileAlreadyExistsException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceInvalidCastException.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceInvalidCastException.cs deleted file mode 100644 index a9334b93..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceInvalidCastException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace $safeprojectname$.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceInvalidCastException : Exception - { - public MicroserviceInvalidCastException() : base(AppData.Exceptions.TypeConverterException) - { - - } - - public MicroserviceInvalidCastException(string message) : base(message) - { - - } - - public MicroserviceInvalidCastException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceInvalidOperationException.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceInvalidOperationException.cs deleted file mode 100644 index 24538e8f..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceInvalidOperationException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace $safeprojectname$.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceInvalidOperationException : Exception - { - public MicroserviceInvalidOperationException() : base(AppData.Exceptions.InvalidOperationException) - { - - } - - public MicroserviceInvalidOperationException(string message) : base(message) - { - - } - - public MicroserviceInvalidOperationException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceNotFoundException.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceNotFoundException.cs deleted file mode 100644 index b881205d..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceNotFoundException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace $safeprojectname$.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceNotFoundException : Exception - { - public MicroserviceNotFoundException() : base(AppData.Exceptions.NotFoundException) - { - - } - - public MicroserviceNotFoundException(string message) : base(message) - { - - } - - public MicroserviceNotFoundException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceUnauthorizedException.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceUnauthorizedException.cs deleted file mode 100644 index eec7e4b0..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceUnauthorizedException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace $safeprojectname$.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceUnauthorizedException : Exception - { - public MicroserviceUnauthorizedException() : base(AppData.Exceptions.UnauthorizedException) - { - - } - - public MicroserviceUnauthorizedException(string message) : base(message) - { - - } - - public MicroserviceUnauthorizedException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceUserNotFoundException.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceUserNotFoundException.cs deleted file mode 100644 index 0fa7dbe9..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/Exceptions/MicroserviceUserNotFoundException.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; - -namespace $safeprojectname$.Exceptions -{ - /// - /// Represent Price Point Exception - /// - public class MicroserviceUserNotFoundException : Exception - { - public MicroserviceUserNotFoundException() : base(AppData.Exceptions.UserNotFoundException) - { - - } - - public MicroserviceUserNotFoundException(string message) : base(message) - { - } - - public MicroserviceUserNotFoundException(string message, Exception exception) : base(message, exception) - { - - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/IMailMessage.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/IMailMessage.cs deleted file mode 100644 index faf62792..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/IMailMessage.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace $safeprojectname$ -{ - /// - /// Mail message interface - /// - public interface IEmailMessage - { - /// - /// Mail to - /// - string MailTo { get; set; } - - /// - /// Mail from - /// - string MailFrom { get; set; } - - /// - /// Subject or title of the message - /// - string Subject { get; set; } - - /// - /// Message content - /// - string Body { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/MyTemplate.vstemplate b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/MyTemplate.vstemplate deleted file mode 100644 index ed1eaf65..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/MyTemplate.vstemplate +++ /dev/null @@ -1,40 +0,0 @@ - - - Calabonga.Microservice.Module.Core - Contracts for microservice - CSharp - - - 1000 - true - Calabonga.Microservice.Module.Core - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - MicroserviceArgumentNullException.cs - MicroserviceEntityValidationException.cs - MicroserviceException.cs - MicroserviceFileAlreadyExistsException.cs - MicroserviceInvalidCastException.cs - MicroserviceInvalidOperationException.cs - MicroserviceNotFoundException.cs - MicroserviceUnauthorizedException.cs - MicroserviceUserNotFoundException.cs - - AppData.Common.cs - AppData.Exceptions.cs - AppData.Messages.cs - EmailMessage.cs - IMailMessage.cs - SendEmailResult.cs - StringExtensions.cs - - - \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/SendEmailResult.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/SendEmailResult.cs deleted file mode 100644 index eb5bd2e7..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/SendEmailResult.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace $safeprojectname$ -{ - /// - /// MailKit send result - /// - public class SendEmailResult - { - /// - /// Indicate mail sent - /// - public bool IsSent { get; set; } - - /// - /// Indicate sending in process - /// - public bool IsInProcess { get; set; } - - /// - /// Exception while sending - /// - public Exception Exception { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/StringExtensions.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/StringExtensions.cs deleted file mode 100644 index 02eadcca..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/StringExtensions.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Diagnostics; -using System.Globalization; -using System.Text.RegularExpressions; - -namespace $safeprojectname$ -{ - public static class StringExtensions - { - private static readonly Regex WebUrlExpression = new Regex(@"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)", RegexOptions.Singleline | RegexOptions.Compiled); - private static readonly Regex EmailExpression = new Regex(@"^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$", RegexOptions.Singleline | RegexOptions.Compiled); - private static readonly Regex StripHtmlExpression = new Regex("<\\S[^><]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled); - - [DebuggerStepThrough] - public static Guid ToGuid(this string value) - { - Guid.TryParse(value, out var result); - return result; - } - - [DebuggerStepThrough] - public static bool IsWebUrl(this string target) - { - return !string.IsNullOrEmpty(target) && WebUrlExpression.IsMatch(target); - } - - [DebuggerStepThrough] - public static bool IsEmail(this string target) - { - return !string.IsNullOrEmpty(target) && EmailExpression.IsMatch(target); - } - - [DebuggerStepThrough] - public static string NullSafe(this string target) - { - return (target ?? string.Empty).Trim(); - } - - [DebuggerStepThrough] - public static string FormatWith(this string target, params object[] args) - { - if (target == null) { return string.Empty; } - return string.Format(CultureInfo.CurrentCulture, target, args); - } - - [DebuggerStepThrough] - public static string StripHtml(this string target) - { - return StripHtmlExpression.Replace(target, string.Empty); - } - - - [DebuggerStepThrough] - public static T ToEnum(this string target, T defaultValue) where T : IComparable, IFormattable - { - T convertedValue = defaultValue; - - if (!string.IsNullOrEmpty(target)) - { - try - { - convertedValue = (T)Enum.Parse(typeof(T), target.Trim(), true); - } - catch (ArgumentException) - { - } - } - - return convertedValue; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/__PreviewImage.png b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/__PreviewImage.png deleted file mode 100644 index f34977d9..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/__TemplateIcon.png b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Core/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/ApplicationDbContext.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/ApplicationDbContext.cs deleted file mode 100644 index 4e0bdb06..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/ApplicationDbContext.cs +++ /dev/null @@ -1,23 +0,0 @@ -using $safeprojectname$.Base; -using $ext_projectname$.Entities; -using Microsoft.EntityFrameworkCore; - -namespace $safeprojectname$ -{ - /// - /// Database for application - /// - public class ApplicationDbContext : DbContextBase, IApplicationDbContext - { - /// - public ApplicationDbContext(DbContextOptions options) : base(options) - { - } - - #region System - - public DbSet Logs { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/Base/DbContextBase.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/Base/DbContextBase.cs deleted file mode 100644 index 936c166a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/Base/DbContextBase.cs +++ /dev/null @@ -1,262 +0,0 @@ -using System; -using System.Linq; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -using Calabonga.EntityFrameworkCore.Entities.Base; -using Calabonga.UnitOfWork; -using Microsoft.EntityFrameworkCore; - -namespace $safeprojectname$.Base -{ - /// - /// Base DbContext with predefined configuration - /// - public abstract class DbContextBase : DbContext where TContext : DbContext - { - private const string DefaultUserName = "Anonymous"; - - protected DbContextBase( DbContextOptions options): base(options) - { - LastSaveChangesResult = new SaveChangesResult(); - } - - public SaveChangesResult LastSaveChangesResult { get; } - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - /// - /// Saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// The number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override int SaveChanges(bool acceptAllChangesOnSuccess) - { - try - { - DbSaveChanges(); - return base.SaveChanges(acceptAllChangesOnSuccess); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - public override int SaveChanges() - { - try - { - DbSaveChanges(); - return base.SaveChanges(); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - private void DbSaveChanges() - { - var createdEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added); - foreach (var entry in createdEntries) - { - if (!(entry.Entity is IAuditable)) - { - continue; - } - - var creationDate = DateTime.Now.ToUniversalTime(); - var userName = entry.Property("CreatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("CreatedBy").CurrentValue; - var updatedAt = entry.Property("UpdatedAt").CurrentValue; - var createdAt = entry.Property("CreatedAt").CurrentValue; - if (createdAt != null) - { - if (DateTime.Parse(createdAt.ToString()).Year > 1970) - { - entry.Property("CreatedAt").CurrentValue = ((DateTime)createdAt).ToUniversalTime(); - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - - if (updatedAt != null) - { - if (DateTime.Parse(updatedAt.ToString()).Year > 1970) - { - entry.Property("UpdatedAt").CurrentValue = ((DateTime)updatedAt).ToUniversalTime(); - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - - entry.Property("CreatedBy").CurrentValue = userName; - entry.Property("UpdatedBy").CurrentValue = userName; - - LastSaveChangesResult.AddMessage($"ChangeTracker has new entities: {entry.Entity.GetType()}"); - } - - var updatedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified); - foreach (var entry in updatedEntries) - { - if (entry.Entity is IAuditable) - { - var userName = entry.Property("UpdatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("UpdatedBy").CurrentValue; - entry.Property("UpdatedAt").CurrentValue = DateTime.Now.ToUniversalTime(); - entry.Property("UpdatedBy").CurrentValue = userName; - } - - LastSaveChangesResult.AddMessage($"ChangeTracker has modified entities: {entry.Entity.GetType()}"); - } - } - - /// - /// Configures the schema needed for the identity framework. - /// - /// - /// The builder being used to construct the model for this context. - /// - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - var applyGenericMethod = typeof(ModelBuilder).GetMethods(BindingFlags.Instance | BindingFlags.Public).First(x => x.Name == "ApplyConfiguration"); - foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters)) - { - foreach (var item in type.GetInterfaces()) - { - if (!item.IsConstructedGenericType || item.GetGenericTypeDefinition() != typeof(IEntityTypeConfiguration<>)) - { - continue; - } - - var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(item.GenericTypeArguments[0]); - applyConcreteMethod.Invoke(builder, new[] { Activator.CreateInstance(type) }); - break; - } - } - - builder.EnableAutoHistory(2048); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/Calabonga.Microservice.Module.Data.csproj b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/Calabonga.Microservice.Module.Data.csproj deleted file mode 100644 index f6ff3523..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/Calabonga.Microservice.Module.Data.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - netcoreapp3.1 - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/DatabaseInitialization/DatabaseInitializer.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/DatabaseInitialization/DatabaseInitializer.cs deleted file mode 100644 index bd9e1ddc..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/DatabaseInitialization/DatabaseInitializer.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.DatabaseInitialization -{ - /// - /// Database Initializer - /// - public static class DatabaseInitializer - { - public static async void Seed(IServiceProvider serviceProvider) - { - using var scope = serviceProvider.CreateScope(); - await using var context = scope.ServiceProvider.GetService(); - - // Should be uncomment when using UseSqlServer() settings or any other provider. - // This is should not be used when UseInMemoryDatabase() - // context.Database.Migrate(); - - // TODO: Add your seed data here - - if (context.ChangeTracker.HasChanges()) - { - await context.SaveChangesAsync(); - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/IApplicaitonDbContext.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/IApplicaitonDbContext.cs deleted file mode 100644 index c9fd95b5..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/IApplicaitonDbContext.cs +++ /dev/null @@ -1,29 +0,0 @@ -using $ext_projectname$.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.ChangeTracking; -using Microsoft.EntityFrameworkCore.Infrastructure; - -namespace $safeprojectname$ -{ - /// - /// Abstraction for Database (EntityFramework) - /// - public interface IApplicationDbContext - { - #region System - - DbSet Logs { get; set; } - - DatabaseFacade Database { get; } - - ChangeTracker ChangeTracker { get; } - - DbSet Set() where TEntity : class; - - DbQuery Query() where TQuery : class; - - int SaveChanges(); - - #endregion - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/ModelConfigurations/Base/AuditableModelConfigurationBase.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/ModelConfigurations/Base/AuditableModelConfigurationBase.cs deleted file mode 100644 index 8890882b..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/ModelConfigurations/Base/AuditableModelConfigurationBase.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace $safeprojectname$.ModelConfigurations.Base -{ - /// - /// Audit-able Model Configuration base - /// - /// - public abstract class AuditableModelConfigurationBase : IEntityTypeConfiguration where T : Auditable - { - public void Configure(EntityTypeBuilder builder) - { - builder.ToTable(TableName()); - builder.HasKey(x => x.Id); - builder.Property(x => x.Id).IsRequired(); - - // audit - builder.Property(x => x.CreatedAt).IsRequired().HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)).IsRequired(); - builder.Property(x => x.CreatedBy).HasMaxLength(256).IsRequired(); - builder.Property(x => x.UpdatedAt).HasConversion(v => v.Value, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); - builder.Property(x => x.UpdatedBy).HasMaxLength(256); - - AddBuilder(builder); - } - - /// - /// Add custom properties for your entity - /// - /// - protected abstract void AddBuilder(EntityTypeBuilder builder); - - /// - /// Table name - /// - /// - protected abstract string TableName(); - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/ModelConfigurations/Base/IdentityModelConfigurationBase.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/ModelConfigurations/Base/IdentityModelConfigurationBase.cs deleted file mode 100644 index 30a6fc0b..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/ModelConfigurations/Base/IdentityModelConfigurationBase.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Calabonga.EntityFrameworkCore.Entities.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace $safeprojectname$.ModelConfigurations.Base -{ - /// - /// Audit-able Model Configuration base - /// - /// - public abstract class IdentityModelConfigurationBase : IEntityTypeConfiguration where T : Identity - { - public void Configure(EntityTypeBuilder builder) - { - builder.ToTable(TableName()); - builder.HasKey(x => x.Id); - builder.Property(x => x.Id).IsRequired(); - - AddBuilder(builder); - } - - /// - /// Add custom properties for your entity - /// - /// - protected abstract void AddBuilder(EntityTypeBuilder builder); - - /// - /// Table name - /// - /// - protected abstract string TableName(); - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/ModelConfigurations/LogModelConfiguration.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/ModelConfigurations/LogModelConfiguration.cs deleted file mode 100644 index 2a4fe770..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/ModelConfigurations/LogModelConfiguration.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using $safeprojectname$.ModelConfigurations.Base; -using $ext_projectname$.Entities; -using Microsoft.EntityFrameworkCore.Metadata.Builders; - -namespace $safeprojectname$.ModelConfigurations -{ - /// - /// Entity Type Configuration for Log entity - /// - public class LogModelConfiguration : IdentityModelConfigurationBase - { - protected override void AddBuilder(EntityTypeBuilder builder) - { - builder.Property(x => x.Logger).HasMaxLength(255).IsRequired(); - builder.Property(x => x.Level).HasMaxLength(50).IsRequired(); - builder.Property(x => x.Message).HasMaxLength(4000).IsRequired(); - builder.Property(x => x.CreatedAt).HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)).IsRequired(); - builder.Property(x => x.ThreadId).HasMaxLength(255); - builder.Property(x => x.ExceptionMessage).HasMaxLength(2000); - } - - protected override string TableName() - { - return "Logs"; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/MyTemplate.vstemplate b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/MyTemplate.vstemplate deleted file mode 100644 index 0d2b2653..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/MyTemplate.vstemplate +++ /dev/null @@ -1,37 +0,0 @@ - - - Calabonga.Microservice.Module.Data - Database for microservice - CSharp - - - 1000 - true - Calabonga.Microservice.Module.Data - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - DbContextBase.cs - - - DatabaseInitializer.cs - - - - AuditableModelConfigurationBase.cs - IdentityModelConfigurationBase.cs - - LogModelConfiguration.cs - - ApplicationDbContext.cs - IApplicaitonDbContext.cs - - - \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/__PreviewImage.png b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/__PreviewImage.png deleted file mode 100644 index f34977d9..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/__TemplateIcon.png b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Data/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/Calabonga.Microservice.Module.Entities.csproj b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/Calabonga.Microservice.Module.Entities.csproj deleted file mode 100644 index 84de3298..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/Calabonga.Microservice.Module.Entities.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - netcoreapp3.1 - - - - - - - - - - - diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/Log.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/Log.cs deleted file mode 100644 index 680eb9e8..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/Log.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace $safeprojectname$ -{ - /// - /// Logs - /// - public class Log : Identity - { - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } - - public string Level { get; set; } - - public string Message { get; set; } - - public string ThreadId { get; set; } - - public string ExceptionMessage { get; set; } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/MyTemplate.vstemplate b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/MyTemplate.vstemplate deleted file mode 100644 index 11c48968..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/MyTemplate.vstemplate +++ /dev/null @@ -1,23 +0,0 @@ - - - Calabonga.Microservice.Module.Entities - Entities for microservice - CSharp - - - 1000 - true - Calabonga.Microservice.Module.Entities - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - Log.cs - - - \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/__PreviewImage.png b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/__PreviewImage.png deleted file mode 100644 index f34977d9..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/__TemplateIcon.png b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Entities/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesAuthentication.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesAuthentication.cs deleted file mode 100644 index d5c878cd..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesAuthentication.cs +++ /dev/null @@ -1,42 +0,0 @@ -using $ext_projectname$.Core; -using IdentityServer4.AccessTokenValidation; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesAuthentication - { - /// - /// ConfigureServices Services - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - var url = configuration.GetSection("IdentityServer").GetValue("Url"); - - services - .AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; - }) - .AddIdentityServerAuthentication(options => - { - options.SupportedTokens = SupportedTokens.Jwt; - options.Authority = $"{url}{AppData.AuthUrl}"; - options.EnableCaching = true; - options.RequireHttpsMetadata = false; - }); - - services.AddAuthorization(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesBase.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesBase.cs deleted file mode 100644 index 4e1f1836..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesBase.cs +++ /dev/null @@ -1,49 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Data; -using $safeprojectname$.Extensions; -using $safeprojectname$.Infrastructure.Settings; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesBase - { - /// - /// ConfigureServices Services - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - services.AddDbContextPool(config => - { - // UseInMemoryDatabase - This for demo purposes only! - // Should uninstall package "Microsoft.EntityFrameworkCore.InMemory" and install what you need. - // For example: "Microsoft.EntityFrameworkCore.SqlServer" - // uncomment line below to use UseSqlServer(). Don't forget setup connection string in appSettings.json - config.UseInMemoryDatabase("DEMO_PURPOSES_ONLY"); - // config.UseSqlServer(configuration.GetConnectionString(nameof(ApplicationDbContext))); - }); - - services.AddAutoMapper(typeof(Startup)); - services.AddControllers(); - services.AddUnitOfWork(); - services.AddMemoryCache(); - services.AddRouting(); - services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); - services.AddOptions(); - services.Configure(configuration.GetSection(nameof(CurrentAppSettings))); - services.Configure(options => options.UseRouteSlugify()); - services.AddLocalization(); - services.AddHttpContextAccessor(); - services.AddResponseCaching(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesControllers.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesControllers.cs deleted file mode 100644 index 19a8159f..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesControllers.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Calabonga.AspNetCore.Controllers.Extensions; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// Configure controllers - /// - public static class ConfigureServicesControllers - { - /// - /// Configure services - /// - /// - public static void ConfigureServices(IServiceCollection services) - { - services.AddControllers(); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesCors.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesCors.cs deleted file mode 100644 index 6c854c5a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesCors.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.Linq; -using Calabonga.Microservices.Web.Core; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// Cors configurations - /// - public class ConfigureServicesCors - { - /// - /// ConfigureServices - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - var origins = configuration.GetSection("Cors")?.GetSection("Origins")?.Value?.Split(','); - services.AddCors(options => - { - options.AddPolicy("CorsPolicy", builder => - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - if (origins != null && origins.Length > 0) - { - if (origins.Contains("*")) - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - builder.SetIsOriginAllowed(host => true); - builder.AllowCredentials(); - } - else - { - foreach (var origin in origins) - { - builder.WithOrigins(origin); - } - } - } - }); - }); - - services.UseMicroserviceAuthorizationPolicy(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesMediator.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesMediator.cs deleted file mode 100644 index 5e556b4a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesMediator.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Calabonga.AspNetCore.Controllers.Extensions; -using $safeprojectname$.Mediator.Behaviors; -using MediatR; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesMediator - { - /// - /// ConfigureServices Services - /// - /// - public static void ConfigureServices(IServiceCollection services) - { - services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>)); - services.AddCommandAndQueries(typeof(Startup).Assembly); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesSwagger.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesSwagger.cs deleted file mode 100644 index bf4f5992..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesSwagger.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using $safeprojectname$.AppStart.SwaggerFilters; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerUI; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// Swagger configuration - /// - public static class ConfigureServicesSwagger - { - private const string AppTitle = "Microservice API"; - private static readonly string AppVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - private const string SwaggerConfig = "/swagger/v1/swagger.json"; - private const string SwaggerUrl = "api/manual"; - - /// - /// ConfigureServices Swagger services - /// - /// - /// - public static void ConfigureServices(IServiceCollection services, IConfiguration configuration) - { - services.AddSwaggerGen(options => - { - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = AppTitle, - Version = AppVersion, - Description = "Microservice API module API documentation. This template based on ASP.NET Core 3.1." - }); - options.ResolveConflictingActions(x => x.First()); - - var url = configuration.GetSection("IdentityServer").GetValue("Url"); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - Password = new OpenApiOAuthFlow - { - TokenUrl = new Uri($"{url}/auth/connect/token", UriKind.Absolute), - Scopes = new Dictionary - { - { "api1", "Default scope" } - } - } - } - }); - - options.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "oauth2" - }, - Scheme = "oauth2", - Name = "Bearer", - In = ParameterLocation.Header, - - }, - new List() - } - }); - - options.OperationFilter(); - }); - } - - /// - /// Set up some properties for swagger UI - /// - /// - public static void SwaggerSettings(SwaggerUIOptions settings) - { - settings.SwaggerEndpoint(SwaggerConfig, $"{AppTitle} v.{AppVersion}"); - settings.RoutePrefix = SwaggerUrl; - settings.DocumentTitle = "Microservice API"; - settings.DefaultModelExpandDepth(0); - settings.DefaultModelRendering(ModelRendering.Model); - settings.DefaultModelsExpandDepth(0); - settings.DocExpansion(DocExpansion.None); - settings.OAuthClientId("microservice1"); - settings.OAuthScopeSeparator(" "); - settings.OAuthClientSecret("secret"); - settings.DisplayRequestDuration(); - settings.OAuthAppName("Microservice API module API documentation"); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesValidators.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesValidators.cs deleted file mode 100644 index 855df4bf..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/ConfigureServices/ConfigureServicesValidators.cs +++ /dev/null @@ -1,20 +0,0 @@ -using FluentValidation; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.AppStart.ConfigureServices -{ - /// - /// ASP.NET Core services registration and configurations - /// - public static class ConfigureServicesValidators - { - /// - /// ConfigureServices Services - /// - /// - public static void ConfigureServices(IServiceCollection services) - { - services.AddValidatorsFromAssembly(typeof(Startup).Assembly); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/Configures/ConfigureCommon.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/Configures/ConfigureCommon.cs deleted file mode 100644 index 80de9e2c..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/Configures/ConfigureCommon.cs +++ /dev/null @@ -1,54 +0,0 @@ -using $safeprojectname$.AppStart.ConfigureServices; -using $safeprojectname$.Middlewares; -using Calabonga.Microservices.Web.Core; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; - -namespace $safeprojectname$.AppStart.Configures -{ - /// - /// Pipeline configuration - /// - public static class ConfigureCommon - { - /// - /// Configure pipeline - /// - /// - /// - /// - public static void Configure(IApplicationBuilder app, IWebHostEnvironment env, AutoMapper.IConfigurationProvider mapper) - { - if (env.IsDevelopment()) - { - mapper.AssertConfigurationIsValid(); - app.UseDeveloperExceptionPage(); - } - else - { - mapper.CompileMappings(); - } - - app.UseDefaultFiles(); - app.UseStaticFiles(new StaticFileOptions - { - OnPrepareResponse = ctx => - { - ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=600"); - } - }); - - app.UseResponseCaching(); - app.UseETagger(); - app.UseMiddleware(typeof(ErrorHandlingMiddleware)); - app.UseSwagger(); - app.UseSwaggerUI(ConfigureServicesSwagger.SwaggerSettings); - - // Singleton setup for User Identity - UserIdentity.Instance.Configure(app.ApplicationServices.GetService()); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/Configures/ConfigureEndpoints.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/Configures/ConfigureEndpoints.cs deleted file mode 100644 index b6e8d8bb..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/Configures/ConfigureEndpoints.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.AspNetCore.Builder; - -namespace $safeprojectname$.AppStart.Configures -{ - /// - /// Configure pipeline - /// - public static class ConfigureEndpoints - { - /// - /// Configure Routing - /// - /// - public static void Configure(IApplicationBuilder app) - { - app.UseRouting(); - app.UseCors("CorsPolicy"); - app.UseAuthentication(); - app.UseAuthorization(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/SwaggerFilters/ApplySummariesOperationFilter.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/SwaggerFilters/ApplySummariesOperationFilter.cs deleted file mode 100644 index 232444d3..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/AppStart/SwaggerFilters/ApplySummariesOperationFilter.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace $safeprojectname$.AppStart.SwaggerFilters -{ - /// - /// Swagger Method Info Generator from summary for - /// - public class ApplySummariesOperationFilter : IOperationFilter - { - /// - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var controllerActionDescriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor; - if (controllerActionDescriptor == null) - { - return; - } - - var actionName = controllerActionDescriptor.ActionName; - if (actionName != "GetPaged") return; - var resourceName = controllerActionDescriptor.ControllerName; - operation.Summary = $"Returns paged list of the {resourceName} as IPagedList wrapped with OperationResult"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj deleted file mode 100644 index 887852aa..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj +++ /dev/null @@ -1,50 +0,0 @@ - - - - netcoreapp3.1 - - - - - - - - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Controllers/LogsReadOnlyController.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Controllers/LogsReadOnlyController.cs deleted file mode 100644 index f3b18192..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Controllers/LogsReadOnlyController.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Threading.Tasks; -using $ext_projectname$.Core; -using $safeprojectname$.Mediator.LogsReadonly; -using Calabonga.Microservices.Core.QueryParams; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Controllers -{ - /// - /// ReadOnlyController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsReadonlyController : ControllerBase - { - private readonly IMediator _mediator; - - public LogsReadonlyController(IMediator mediator) - { - _mediator = mediator; - } - - [HttpGet("[action]")] - [Authorize(Policy = "Logs:UserRoles:View", Roles = AppData.SystemAdministratorRoleName)] - public async Task GetRoles() - { - //Get Roles for current user - return Ok(await _mediator.Send(new GetRolesRequest(), HttpContext.RequestAborted)); - } - - [HttpGet("[action]/{id:guid}")] - [ProducesResponseType(200)] - public async Task GetById(Guid id) - { - return Ok(await _mediator.Send(new LogGetByIdRequest(id), HttpContext.RequestAborted)); - } - - - [HttpGet("[action]")] - [ProducesResponseType(200)] - public async Task GetPaged([FromQuery] PagedListQueryParams queryParams) - { - return Ok(await _mediator.Send(new LogGetPagedRequest(queryParams), HttpContext.RequestAborted)); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Controllers/LogsReadonly2Controller.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Controllers/LogsReadonly2Controller.cs deleted file mode 100644 index 06217b52..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Controllers/LogsReadonly2Controller.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Security.Claims; -using AutoMapper; -using $ext_projectname$.Data; -using $ext_projectname$.Entities; -using $safeprojectname$.Infrastructure.Settings; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.Microservices.Core.Validators; -using Calabonga.UnitOfWork; -using Calabonga.UnitOfWork.Controllers.Controllers; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Options; - -namespace $safeprojectname$.Controllers -{ - /// - /// ReadOnlyController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsReadonly2Controller : ReadOnlyController - { - private readonly CurrentAppSettings _appSettings; - - /// - public LogsReadonly2Controller( - IOptions appSettings, - IUnitOfWork unitOfWork, - IMapper mapper) - : base(unitOfWork, mapper) - { - _appSettings = appSettings.Value; - } - - [HttpGet("user-roles")] - [Authorize(Policy = "Logs:UserRoles:View")] - public IActionResult Get() - { - //Get Roles for current user - var roles = ClaimsHelper.GetValues((ClaimsIdentity)User.Identity, "role"); - return Ok($"Current user ({User.Identity.Name}) have following roles: {string.Join("|", roles)}"); - } - - /// - protected override PermissionValidationResult ValidateQueryParams(PagedListQueryParams queryParams) - { - if (queryParams.PageSize <= 0) - { - queryParams.PageSize = _appSettings.PageSize; - } - return new PermissionValidationResult(); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Controllers/LogsWritable2Controller.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Controllers/LogsWritable2Controller.cs deleted file mode 100644 index 491872bd..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Controllers/LogsWritable2Controller.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Threading.Tasks; -using AutoMapper; -using $ext_projectname$.Data; -using $ext_projectname$.Entities; -using $safeprojectname$.Infrastructure.Settings; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.Microservices.Core.Validators; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using Calabonga.UnitOfWork.Controllers.Controllers; -using Calabonga.UnitOfWork.Controllers.Factories; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Options; - -namespace $safeprojectname$.Controllers -{ - /// - /// WritableController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsWritable2Controller : WritableController - { - private readonly CurrentAppSettings _appSettings; - - /// - public LogsWritable2Controller( - IOptions appSettings, - IEntityManagerFactory entityManagerFactory, - IUnitOfWork unitOfWork, - IMapper mapper) - : base(entityManagerFactory, unitOfWork, mapper) - { - _appSettings = appSettings.Value; - } - - /// - [Authorize(Policy = "LogsWritable:GetCreateViewModelAsync:View")] - public override Task>> GetViewmodelForCreation() - { - return base.GetViewmodelForCreation(); - } - - /// - protected override PermissionValidationResult ValidateQueryParams(PagedListQueryParams queryParams) - { - if (queryParams.PageSize <= 0) - { - queryParams.PageSize = _appSettings.PageSize; - } - return new PermissionValidationResult(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Controllers/LogsWritableController.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Controllers/LogsWritableController.cs deleted file mode 100644 index 2e97a95d..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Controllers/LogsWritableController.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.Threading.Tasks; -using $safeprojectname$.Mediator.LogsReadonly; -using $safeprojectname$.Mediator.LogsWritable; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.QueryParams; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Controllers -{ - /// - /// WritableController Demo - /// - [Route("api/[controller]")] - [Authorize] - public class LogsWritableController : ControllerBase - { - private readonly IMediator _mediator; - - public LogsWritableController(IMediator mediator) - { - _mediator = mediator; - } - - - [HttpGet("[action]/{id:guid}")] - [ProducesResponseType(200)] - public async Task GetById(Guid id) - { - return Ok(await _mediator.Send(new LogGetByIdRequest(id), HttpContext.RequestAborted)); - } - - - [HttpGet("[action]")] - [ProducesResponseType(200)] - public async Task GetPaged([FromQuery] PagedListQueryParams queryParams) - { - return Ok(await _mediator.Send(new LogGetPagedRequest(queryParams), HttpContext.RequestAborted)); - } - - [HttpGet("[action]")] - public async Task GetViewmodelForCreation() - { - return Ok(await _mediator.Send(new LogCreateViewModelRequest(), HttpContext.RequestAborted)); - } - - [HttpGet("[action]/{id:guid}")] - public async Task GetViewmodelForEditing(Guid id) - { - return Ok(await _mediator.Send(new LogUpdateViewModelRequest(id), HttpContext.RequestAborted)); - } - - [HttpPost("[action]")] - public async Task PostItem([FromBody]LogCreateViewModel model) - { - return Ok(await _mediator.Send(new LogPostItemRequest(model), HttpContext.RequestAborted)); - } - - [HttpPut("[action]")] - public async Task PutItem([FromBody]LogUpdateViewModel model) - { - return Ok(await _mediator.Send(new LogPutItemRequest(model), HttpContext.RequestAborted)); - } - - [HttpDelete("[action]/{id:guid}")] - public async Task DeleteItem(Guid id) - { - return Ok(await _mediator.Send(new LogDeleteItemRequest(id), HttpContext.RequestAborted)); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Extensions/ApplicationBuilderExtensions.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Extensions/ApplicationBuilderExtensions.cs deleted file mode 100644 index 01c98472..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Extensions/ApplicationBuilderExtensions.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Text.RegularExpressions; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.ApplicationModels; -using Microsoft.AspNetCore.Routing; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.Extensions -{ - /// - /// Extensions for application class - /// - public static class ApplicationBuilderExtensions - { - /// - /// Use special route slugify for Pegasus routing - /// - /// - public static void UseRouteSlugify(this MvcOptions options) - { - options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer())); - } - } - - /// - /// Special route naming convention - /// - public class SlugifyParameterTransformer : IOutboundParameterTransformer - { - /// - public string TransformOutbound(object value) - { - return value == null - ? null - : Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2").ToLower(); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Extensions/AssemblyExtensions.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Extensions/AssemblyExtensions.cs deleted file mode 100644 index 1eabfaa6..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Extensions/AssemblyExtensions.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace $safeprojectname$.Extensions -{ - /// - /// Assembly helpers - /// - public static class AssemblyExtensions - { - /// - /// Returns types - /// - /// - /// - /// - public static List GetTypesAssignableFrom(this Assembly assembly) - { - return assembly.GetTypesAssignableFrom(typeof(T)); - } - - private static List GetTypesAssignableFrom(this Assembly assembly, Type compareType) - { - var ret = new List(); - foreach (var type in assembly.DefinedTypes) - { - if (compareType.IsAssignableFrom(type) && compareType != type && !type.IsAbstract) - { - ret.Add(type); - } - } - return ret; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Extensions/DateTimeExtensions.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Extensions/DateTimeExtensions.cs deleted file mode 100644 index 78e7b5cd..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Extensions/DateTimeExtensions.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace $safeprojectname$.Extensions -{ - /// - /// DateTime extensions - /// - public static class DateTimeExtensions - { - /// - /// Each day enumeration - /// - /// - /// - /// - private static IEnumerable EachDay(DateTime from, DateTime thru) - { - for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1)) - { - yield return day; - } - } - - /// - /// Each month enumeration - /// - /// - /// - /// - private static IEnumerable EachMonth(DateTime from, DateTime thru) - { - for (var month = from.Date; month.Date <= thru.Date || month.Month == thru.Month; month = month.AddMonths(1)) - { - yield return month; - } - } - - /// - /// Enumerates all days in period - /// - /// - /// - /// - public static IEnumerable EachDayTo(this DateTime dateFrom, DateTime dateTo) - { - return EachDay(dateFrom, dateTo); - } - - /// - /// Enumerates all months in period - /// - /// - /// - /// - public static IEnumerable EachMonthTo(this DateTime dateFrom, DateTime dateTo) - { - return EachMonth(dateFrom, dateTo); - } - - - /// - /// Total Month count between two dates - /// - /// - /// - /// - public static int TotalMonths(this DateTime start, DateTime end) - { - return (start.Year * 12 + start.Month) - (end.Year * 12 + end.Month); - } - - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Extensions/EntityValidatorExtensions.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Extensions/EntityValidatorExtensions.cs deleted file mode 100644 index b574f8cb..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Extensions/EntityValidatorExtensions.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections.Generic; -using Calabonga.Microservices.Core.Validators; - -namespace $safeprojectname$.Extensions -{ - /// - /// Entity Validator Extensions - /// - public static class EntityValidatorExtensions - { - /// - /// Returns validator from validation results - /// - /// - /// - public static ValidationContext GetResult(this List source) - { - return new ValidationContext(source); - } - - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/SwaggerFormAttribute.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/SwaggerFormAttribute.cs deleted file mode 100644 index da6e0db3..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/SwaggerFormAttribute.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; - -namespace $safeprojectname$.Infrastructure.Attributes -{ - /// - /// Custom attribute for Swagger Upload Form - /// - [AttributeUsage(AttributeTargets.Method)] - public sealed class SwaggerFormAttribute : Attribute - { - /// - public SwaggerFormAttribute(string parameterName, string description, bool hasFileUpload = true) - { - ParameterName = parameterName; - Description = description; - HasFileUpload = hasFileUpload; - } - - /// - /// UploadFile enabled - /// - public bool HasFileUpload { get; } - - /// - /// Name for the parameter - /// - public string ParameterName { get; } - - /// - /// Small description - /// - public string Description { get;} - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/SwaggerGroupAttribute.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/SwaggerGroupAttribute.cs deleted file mode 100644 index 4ca5bb62..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/SwaggerGroupAttribute.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; - -namespace $safeprojectname$.Infrastructure.Attributes -{ - /// - /// Swagger controller group attribute - /// - /// - [AttributeUsage(AttributeTargets.Class)] - public class SwaggerGroupAttribute : Attribute - { - /// - public SwaggerGroupAttribute(string groupName) - { - GroupName = groupName; - } - - /// - /// Group name - /// - public string GroupName { get; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/ValidateModelStateAttribute.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/ValidateModelStateAttribute.cs deleted file mode 100644 index 663397fa..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Attributes/ValidateModelStateAttribute.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Linq; -using Calabonga.OperationResults; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; - -namespace $safeprojectname$.Infrastructure.Attributes -{ - /// - /// Custom validation handler for availability to whit OperationResult - /// - public class ValidateModelStateAttribute : ActionFilterAttribute - { - /// - public override void OnActionExecuting(ActionExecutingContext context) - { - if (context.ModelState.IsValid) return; - var operation = OperationResult.CreateResult(); - var messages = context.ModelState.Values.SelectMany(x => x.Errors.Select(xx => xx.ErrorMessage)); - var message = string.Join(" ", messages); - operation.AddError(message); - context.Result = new OkObjectResult(operation); - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/DependencyInjection/CommonRegistrations.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/DependencyInjection/CommonRegistrations.cs deleted file mode 100644 index 137bd5fd..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/DependencyInjection/CommonRegistrations.cs +++ /dev/null @@ -1,27 +0,0 @@ -using $ext_projectname$.Data; -using $safeprojectname$.Infrastructure.Services; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.Infrastructure.DependencyInjection -{ - /// - /// Registrations for both points: API and Scheduler - /// - public partial class DependencyContainer - { - /// - /// Register - /// - /// - public static void Common(IServiceCollection services) - { - services.AddTransient(); - - // services - services.AddTransient(); - services.AddTransient(); - } - } - - -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Engine/EntityManagers/LogManager.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Engine/EntityManagers/LogManager.cs deleted file mode 100644 index f4628543..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Engine/EntityManagers/LogManager.cs +++ /dev/null @@ -1,21 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.Validators; -using Calabonga.UnitOfWork.Controllers.Factories; -using Calabonga.UnitOfWork.Controllers.Managers; - -namespace $safeprojectname$.Infrastructure.Engine.EntityManagers -{ - /// - /// Entity manager for - /// - public class LogManager: EntityManager - { - /// - public LogManager(IMapper mapper, IViewModelFactory viewModelFactory, IEntityValidator validator) - : base(mapper, viewModelFactory, validator) - { - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Engine/EntityValidators/LogValidator.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Engine/EntityValidators/LogValidator.cs deleted file mode 100644 index 77d22084..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Engine/EntityValidators/LogValidator.cs +++ /dev/null @@ -1,13 +0,0 @@ -using $ext_projectname$.Entities; -using Calabonga.Microservices.Core.Validators; - -namespace $safeprojectname$.Infrastructure.Engine.EntityValidators -{ - /// - /// Entity Validator for - /// - public class LogValidator: EntityValidator - { - - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Engine/ViewModelFactories/LogViewModelFactory.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Engine/ViewModelFactories/LogViewModelFactory.cs deleted file mode 100644 index c95f4615..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Engine/ViewModelFactories/LogViewModelFactory.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Threading.Tasks; -using AutoMapper; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using Calabonga.UnitOfWork.Controllers.Factories; -using Microsoft.Extensions.Logging; - -namespace $safeprojectname$.Infrastructure.Engine.ViewModelFactories -{ - /// - /// ViewModel factory for - /// - public class LogViewModelFactory : ViewModelFactory - { - private readonly IUnitOfWork _context; - private readonly IMapper _mapper; - - public LogViewModelFactory(IUnitOfWork context, IMapper mapper) - { - _context = context; - _mapper = mapper; - } - - /// - public override Task> GenerateForCreateAsync() - { - var operation = OperationResult.CreateResult(); - operation.Result = new LogCreateViewModel() - { - CreatedAt = DateTime.Now, - Level = LogLevel.Information.ToString(), - Logger = "Demo purposes only", - Message = $"This is demo message {DateTime.Now}" - }; - return Task.FromResult(operation); - } - - /// - public override async Task> GenerateForUpdateAsync(Guid id) - { - var operation = OperationResult.CreateResult(); - var entity = await _context.GetRepository().GetFirstOrDefaultAsync(predicate: x => x.Id == id); - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("ViewModel generated for Log entity. Please see Additional information in DataObject").AddData(new { Identifier = id }); - - return operation; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/IViewModel.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/IViewModel.cs deleted file mode 100644 index c36030b4..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/IViewModel.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace $safeprojectname$.Infrastructure.Factories.Base -{ - /// - /// Just a stub for see - /// - public interface IViewModel { } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/IViewModelFactory.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/IViewModelFactory.cs deleted file mode 100644 index 67c444c3..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/IViewModelFactory.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace $safeprojectname$.Infrastructure.Factories.Base -{ - /// - /// ViewModel Factory - /// - /// - /// - /// - public interface IViewModelFactory - where TCreateViewModel : IViewModel, new() - where TUpdateViewModel : IViewModel, new() - where TEntity : class, IHaveId - { - /// - /// Returns ViewModel for entity creation - /// - /// - TCreateViewModel GenerateForCreate(); - - /// - /// Returns ViewModel for entity editing - /// - /// - /// - TUpdateViewModel GenerateForUpdate(Guid id); - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/ViewModelFactory.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/ViewModelFactory.cs deleted file mode 100644 index f68d9c1c..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Factories/Base/ViewModelFactory.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace $safeprojectname$.Infrastructure.Factories.Base -{ - /// - /// ViewModelFactory base class - /// - /// - /// - /// - public abstract class ViewModelFactory : IViewModelFactory - where TCreateViewModel : IViewModel, new() - where TUpdateViewModel : IViewModel, new() - where TEntity : class, IHaveId - { - - /// - public abstract TCreateViewModel GenerateForCreate(); - - /// - public abstract TUpdateViewModel GenerateForUpdate(Guid id); - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/AsyncHelper.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/AsyncHelper.cs deleted file mode 100644 index b55ccaed..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/AsyncHelper.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace $safeprojectname$.Infrastructure.Helpers -{ - /// - /// Run Asynchronous methods as Synchronous. - /// - public static class AsyncHelper - { - private static readonly TaskFactory AppTaskFactory = new - TaskFactory(CancellationToken.None, - TaskCreationOptions.None, - TaskContinuationOptions.None, - TaskScheduler.Default); - - /// - /// Run asynchronous method as synchronous - /// - /// - /// - /// - public static TResult RunSync(Func> func) - { - return AppTaskFactory - .StartNew(func) - .Unwrap() - .GetAwaiter() - .GetResult(); - } - - /// - /// Run asynchronous method as synchronous - /// - /// - public static void RunSync(Func func) - { - AppTaskFactory - .StartNew(func) - .Unwrap() - .GetAwaiter() - .GetResult(); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/EmailHelper.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/EmailHelper.cs deleted file mode 100644 index 8f3c0571..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/EmailHelper.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using $ext_projectname$.Core; - -namespace $safeprojectname$.Infrastructure.Helpers -{ - /// - /// Email validation helper - /// - public static class EmailHelper - { - /// - /// Validates emails entries - /// - /// - /// - public static IEnumerable GetValidEmails(string emails) - { - if (string.IsNullOrWhiteSpace(emails)) - { - return null; - } - var split = emails.Split(new[] { ';', '|', ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); - return split.Where(x => x.IsEmail()); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/EnumHelper.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/EnumHelper.cs deleted file mode 100644 index 95ff7ff5..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/EnumHelper.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Reflection; - -namespace $safeprojectname$.Infrastructure.Helpers -{ - /// - /// Enum Helper - /// - /// - public static class EnumHelper where T: struct - { - /// - /// Returns Enum with DisplayNames - /// - /// - public static Dictionary GetValuesWithDisplayNames() - { - var type = typeof(T); - var r = type.GetEnumValues(); - var list = new Dictionary(); - foreach (var element in r) - { - list.Add((T)element, GetDisplayValue((T)element)); - } - return list; - } - - /// - /// Returns values from enum - /// - /// - public static IList GetValues() - { - return typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public).Select(fi => (T)Enum.Parse(typeof(T), fi.Name, false)).ToList(); - } - - /// - /// Parse value by string from Enum - /// - /// - /// - public static T Parse(string value) - { - return (T)Enum.Parse(typeof(T), value, true); - } - - /// - /// Parse value by string from Enum - /// - /// - /// - public static T? TryParse(string value) - { - if (Enum.TryParse(value, true, out T result)) - { - return result; - } - return null; - - } - - /// - /// Returns values from Enum - /// - /// - public static IEnumerable GetNames() - { - return typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public).Select(fi => fi.Name).ToList(); - } - - /// - /// Returns values from Enum or Resource file if exists - /// - /// - /// - public static IList GetDisplayValues(Enum value) - { - return GetNames().Select(obj => GetDisplayValue(Parse(obj))).ToList(); - } - - private static string LookupResource(Type resourceManagerProvider, string resourceKey) - { - foreach (var staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)) - { - if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager)) - { - var resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null); - return resourceManager.GetString(resourceKey); - } - } - - return resourceKey; // Fallback with the key name - } - - /// - /// Returns display name for Enum - /// - /// - /// - public static string GetDisplayValue(T value) - { - var fieldInfo = value.GetType().GetField(value.ToString()); - - var descriptionAttributes = fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false) as DisplayAttribute[]; - if (descriptionAttributes?.Length > 0 && descriptionAttributes[0].ResourceType != null) - { - return LookupResource(descriptionAttributes[0].ResourceType, descriptionAttributes[0].Name); - } - - if (descriptionAttributes == null) - { - return string.Empty; - } - - return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString(); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/Utilites.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/Utilites.cs deleted file mode 100644 index dc9e3dda..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/Utilites.cs +++ /dev/null @@ -1,173 +0,0 @@ -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using $ext_projectname$.Core.Exceptions; - -namespace $safeprojectname$.Infrastructure.Helpers -{ - /// - /// System utilities - /// - public static class Utilities - { - /// - /// Compute Hash - /// - /// - /// - public static byte[] ComputeHash(string filePath) - { - var runCount = 1; - while (runCount < 4) - { - try - { - if (!File.Exists(filePath)) - { - throw new FileNotFoundException(); - } - - using (var fs = File.OpenRead(filePath)) - { - return SHA1.Create().ComputeHash(fs); - } - } - catch (IOException ex) - { - if (runCount == 3 || ex.HResult != -2147024864) - { - throw; - } - else - { - Thread.Sleep(TimeSpan.FromSeconds(Math.Pow(2, runCount))); - runCount++; - } - } - } - - return new byte[20]; - } - - /// - /// Return file content - /// - /// - /// - public static async Task GetFileContent(string filePath) - { - try - { - if (!File.Exists(filePath)) - { - throw new FileNotFoundException(); - } - - return await File.ReadAllTextAsync(filePath); - } - catch - { - return null; - } - } - - /// - /// Remove file from directory (physical deleting) - /// - /// - public static void DeleteFile(string filePath) - { - try - { - if (!File.Exists(filePath)) - { - throw new FileNotFoundException(); - } - - File.Delete(filePath); - } - catch - { - // ignored - } - } - - /// - /// Save content to the text file - /// - /// - /// - /// - public static async Task SetFileContent(string filePath, string content) - { - try - { - var folder = Path.GetDirectoryName(filePath); - if (!Directory.Exists(folder)) - { - Directory.CreateDirectory(folder); - } - - if (File.Exists(filePath)) - { - throw new MicroserviceFileAlreadyExistsException(); - } - - using (var fs = File.Create(filePath)) - { - var info = new UTF8Encoding(true).GetBytes(content); - await fs.WriteAsync(info, 0, info.Length); - } - } - catch - { - // ignored - - } - } - - /// - /// Generate ETag for content bytes - /// - /// - /// - /// - public static string GetETag(string key, byte[] contentBytes) - { - var keyBytes = Encoding.UTF8.GetBytes(key); - var combinedBytes = Combine(keyBytes, contentBytes); - return GenerateETag(combinedBytes); - } - - /// - /// Returns Working folder path - /// - /// - public static string GetWorkingFolder() - { - var location = System.Reflection.Assembly.GetEntryAssembly().Location; - return Path.GetDirectoryName(location); - } - - private static string GenerateETag(byte[] data) - { - using (var md5 = MD5.Create()) - { - var hash = md5.ComputeHash(data); - var hex = BitConverter.ToString(hash); - return hex.Replace("-", ""); - } - } - - private static byte[] Combine(byte[] a, byte[] b) - { - var c = new byte[a.Length + b.Length]; - Buffer.BlockCopy(a, 0, c, 0, a.Length); - Buffer.BlockCopy(b, 0, c, a.Length, b.Length); - return c; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/ValidationContextHelper.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/ValidationContextHelper.cs deleted file mode 100644 index 923a379b..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Helpers/ValidationContextHelper.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.ObjectModel; -using System.ComponentModel.DataAnnotations; - -namespace $safeprojectname$.Infrastructure.Helpers -{ - /// - /// ValidationContext Helper for validation operations - /// - public static class ValidationContextHelper - { - /// - /// Returns validation results of IValidatableObject - /// - /// - /// - /// - /// - public static bool TryValidate(object obj, out Collection results, ValidationContext validationContext = null) - { - var context = validationContext ?? new ValidationContext(obj, serviceProvider: null, items: null); - results = new Collection(); - return Validator.TryValidateObject(obj, context, results, validateAllProperties: true); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/IAutoMapper.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/IAutoMapper.cs deleted file mode 100644 index 30150fdf..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/IAutoMapper.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace $safeprojectname$.Infrastructure.Mappers.Base -{ - /// - /// The stub for reflection helper profiles registrations - /// - public interface IAutoMapper { } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/MapperConfigurationBase.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/MapperConfigurationBase.cs deleted file mode 100644 index 8b01c887..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/MapperConfigurationBase.cs +++ /dev/null @@ -1,10 +0,0 @@ -using AutoMapper; - -namespace $safeprojectname$.Infrastructure.Mappers.Base { - - /// - /// Base class for mapper configuration. - /// All ViewModel that will be mapped should implement IAutoMapper - /// - public abstract class MapperConfigurationBase : Profile, IAutoMapper { } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/PagedListConverter.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/PagedListConverter.cs deleted file mode 100644 index ca98c68a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/Base/PagedListConverter.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using AutoMapper; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Infrastructure.Mappers.Base { - - /// - /// Generic converter for IPagedList collections - /// - /// - /// - public class PagedListConverter : ITypeConverter, IPagedList> { - - /// Performs conversion from source to destination type - /// Source object - /// Destination object - /// Resolution context - /// Destination object - public IPagedList Convert(IPagedList source, IPagedList destination, ResolutionContext context) { - if (source == null) return null; - var vm = source.Items.Select(m => context.Mapper.Map(m)).ToList(); - - - var pagedList = PagedList.From(source, (con)=> context.Mapper.Map>(con)); - // var pagedList = vm.ToPagedList(source.PageIndex, source.PageSize); - return pagedList; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/LogMapperConfiguration.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/LogMapperConfiguration.cs deleted file mode 100644 index 7adc4c61..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Mappers/LogMapperConfiguration.cs +++ /dev/null @@ -1,25 +0,0 @@ -using $ext_projectname$.Entities; -using $safeprojectname$.Infrastructure.Mappers.Base; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Infrastructure.Mappers -{ - /// - /// Mapper Configuration for entity Log - /// - public class LogMapperConfiguration: MapperConfigurationBase - { - /// - public LogMapperConfiguration() - { - CreateMap() - .ForMember(x=>x.Id, o=>o.Ignore()); - - CreateMap(); - - CreateMap, IPagedList>() - .ConvertUsing>(); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Services/CacheService.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Services/CacheService.cs deleted file mode 100644 index b835e9b9..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Services/CacheService.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using $ext_projectname$.Core.Exceptions; -using Microsoft.Extensions.Caching.Memory; - -namespace $safeprojectname$.Infrastructure.Services -{ - /// - /// Cache service - /// - public class CacheService : ICacheService - { - private readonly IMemoryCache _cache; - private readonly TimeSpan _defaultSlidingExpiration = TimeSpan.FromSeconds(60); - - /// - public CacheService(IMemoryCache cache) - { - _cache = cache; - } - - /// - public TEntry Get(object key) - { - if (key == null) - { - throw new MicroserviceArgumentNullException(nameof(key)); - } - - return _cache.Get(key); - } - - /// - public void SetForMinute(object key, TEntry cacheEntry) - { - SetWithSlidingExpiration(key, cacheEntry, _defaultSlidingExpiration); - } - - /// - public void SetForThirtyMinutes(object key, TEntry cacheEntry) - { - SetWithSlidingExpiration(key, cacheEntry, TimeSpan.FromMinutes(30)); - } - - /// - /// Default set mechanism - /// - /// - /// - /// - /// - public void SetWithSlidingExpiration(object key, TEntry cacheEntry, TimeSpan slidingExpiration) - { - if (cacheEntry == null) - { - throw new MicroserviceArgumentNullException(nameof(cacheEntry)); - } - - if (key == null) - { - throw new MicroserviceArgumentNullException(nameof(key)); - } - - if (slidingExpiration.Ticks == 0) - { - slidingExpiration = _defaultSlidingExpiration; - } - - var options = new MemoryCacheEntryOptions().SetSlidingExpiration(slidingExpiration); - - _cache.Set(key, cacheEntry, options); - } - - /// - public TEntry GetOrCreate(TKey key, Func findIfNotFoundFunc) - { - return _cache.GetOrCreate(key, findIfNotFoundFunc); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Services/ICacheService.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Services/ICacheService.cs deleted file mode 100644 index 8be8816d..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Services/ICacheService.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using Microsoft.Extensions.Caching.Memory; - -namespace $safeprojectname$.Infrastructure.Services -{ - /// - /// Cache service interface - /// - public interface ICacheService - { - /// - /// Get the entry from the cache - /// - /// - /// - TEntry Get(object key); - - /// - /// Sets entry cache for one minute sliding expiration - /// - /// - /// - /// - void SetForMinute(object key, TEntry cacheEntry); - - /// - /// Sets entry cache for 30 minutes sliding expiration - /// - /// - /// - /// - void SetForThirtyMinutes(object key, TEntry cacheEntry); - - /// - /// Sets entry cache for custom sliding expiration interval - /// - /// - /// - /// - /// - void SetWithSlidingExpiration(object key, TEntry cacheEntry, TimeSpan slidingExpiration); - - /// - /// Returns already exist entry or first put it to the cache and then return entry - /// - /// - /// - /// - /// - /// - TEntry GetOrCreate(TKey key, Func findIfNotFoundFunc); - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Services/ILogService.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Services/ILogService.cs deleted file mode 100644 index 37bb6f89..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Services/ILogService.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace $safeprojectname$.Infrastructure.Services -{ - /// - /// Interface for Business logic logger can save messages to database - /// - public interface ILogService - { - /// - /// Log information message - /// - /// - void LogInformation(string message); - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Services/LogService.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Services/LogService.cs deleted file mode 100644 index b9633417..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Services/LogService.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using $ext_projectname$.Core.Exceptions; -using $ext_projectname$.Data; -using $ext_projectname$.Entities; -using Calabonga.UnitOfWork; -using Microsoft.Extensions.Logging; - -namespace $safeprojectname$.Infrastructure.Services -{ - /// - /// Business logic logger can save messages to database - /// - public class LogService : ILogService - { - private readonly IUnitOfWork _unitOfWork; - - /// - public LogService(IUnitOfWork unitOfWork) - { - _unitOfWork = unitOfWork; - } - /// - public void LogInformation(string message) - { - Log(LogLevel.Information, message); - } - - /// - /// Allows to save data logs to the database Logs table - /// - private void Log(LogLevel level, string message, Exception exception = null) - { - var logs = _unitOfWork.GetRepository(); - var log = new Log - { - CreatedAt = DateTime.UtcNow, - Level = level.ToString(), - Logger = GetType().Name, - Message = message, - ThreadId = "0", - ExceptionMessage = exception?.Message - }; - logs.Insert(log); - _unitOfWork.SaveChanges(); - if (!_unitOfWork.LastSaveChangesResult.IsOk) - { - throw new MicroserviceInvalidOperationException(); - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Settings/Base/ServiceBase.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Settings/Base/ServiceBase.cs deleted file mode 100644 index fa133761..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Settings/Base/ServiceBase.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace $safeprojectname$.Infrastructure.Settings.Base -{ - /// - /// Base service behavior - /// - public abstract class ServiceBase - { - /// - /// Indicates that the processing available works is enabled - /// - public bool IsActive { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Settings/CurrentAppSettings.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Settings/CurrentAppSettings.cs deleted file mode 100644 index 319e4c7a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Settings/CurrentAppSettings.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace $safeprojectname$.Infrastructure.Settings -{ - /// - /// Represents configuration file with current application settings - /// - public class CurrentAppSettings - { - /// - /// Default page size - /// - public int PageSize { get; set; } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Validations/LogValidator.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Validations/LogValidator.cs deleted file mode 100644 index e9feda14..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Infrastructure/Validations/LogValidator.cs +++ /dev/null @@ -1,13 +0,0 @@ -using $ext_projectname$.Entities; -using Calabonga.Microservices.Core.Validators; - -namespace $safeprojectname$.Infrastructure.Validations -{ - /// - /// Validator for entity Log - /// - public class LogValidator : EntityValidator - { - - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/Behaviors/ValidationBehavior.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/Behaviors/ValidationBehavior.cs deleted file mode 100644 index d5d3e580..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/Behaviors/ValidationBehavior.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Calabonga.AspNetCore.Controllers.Base; -using Calabonga.OperationResults; -using FluentValidation; -using MediatR; - -namespace $safeprojectname$.Mediator.Behaviors -{ - /// - /// Base validator for requests - /// - /// - /// - public class ValidatorBehavior : IPipelineBehavior - where TRequest: IRequest - { - private readonly IEnumerable> _validators; - - public ValidatorBehavior(IEnumerable> validators) - { - _validators = validators; - } - - /// - /// Pipeline handler. Perform any additional behavior and await the delegate as necessary - /// - /// Incoming request - /// Cancellation token - /// Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler. - /// Awaitable task returning the - public Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) - { - var failures = _validators - .Select(x => x.Validate(new ValidationContext(request))) - .SelectMany(x => x.Errors) - .Where(x => x != null) - .ToList(); - - if (!failures.Any()) return next(); - - if (request is RequestBase>) - { - var operation = OperationResult.CreateResult(); - operation.AddError(new ValidationException(failures)); - // return Task.FromResult(operation); - } - // return Task.FromResult(operation); - return Task.FromResult(default(TResponse)); - } - - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/GetRoles.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/GetRoles.cs deleted file mode 100644 index c9f33edb..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/GetRoles.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Security.Claims; -using Calabonga.AspNetCore.Controllers.Base; -using Calabonga.Microservices.Core; -using MediatR; -using Microsoft.AspNetCore.Http; - -namespace $safeprojectname$.Mediator.LogsReadonly -{ - /// - /// Request: Returns user roles - /// - public class GetRolesRequest: RequestBase - { - - } - - public class GetRolesRequestHandler : RequestHandler - { - private readonly IHttpContextAccessor _httpContextAccessor; - - public GetRolesRequestHandler(IHttpContextAccessor httpContextAccessor) - { - _httpContextAccessor = httpContextAccessor; - } - - protected override string Handle(GetRolesRequest request) - { - var user = _httpContextAccessor.HttpContext.User; - var roles = ClaimsHelper.GetValues((ClaimsIdentity)user.Identity, "role"); - return $"Current user ({user.Identity.Name}) have following roles: {string.Join("|", roles)}"; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/LogGetById.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/LogGetById.cs deleted file mode 100644 index 7056e3c2..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/LogGetById.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Mediator.LogsReadonly -{ - /// - /// Request for Log by Identifier - /// - public class LogGetByIdRequest : GetByIdQuery - { - public LogGetByIdRequest(Guid id) : base(id) - { - } - } - - /// - /// Response for Request for Log by Identifier - /// - public class LogGetByIdRequestHandler : GetByIdHandlerBase - { - public LogGetByIdRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/LogGetPaged.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/LogGetPaged.cs deleted file mode 100644 index 0f2f63fc..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsReadonly/LogGetPaged.cs +++ /dev/null @@ -1,30 +0,0 @@ -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.Microservices.Core.QueryParams; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Mediator.LogsReadonly -{ - /// - /// Request for paged list of Logs - /// - public class LogGetPagedRequest : GetPagedQuery - { - public LogGetPagedRequest(PagedListQueryParams queryParams) : base(queryParams) - { - } - } - - /// - /// Request for paged list of Logs - /// - public class LogGetPagedRequestHandler : GetPagedHandlerBase - { - public LogGetPagedRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogCreateViewModel.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogCreateViewModel.cs deleted file mode 100644 index 5b64452c..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogCreateViewModel.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Threading.Tasks; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $safeprojectname$.ViewModels.LogViewModels; -using Microsoft.Extensions.Logging; - -namespace $safeprojectname$.Mediator.LogsWritable -{ - /// - /// Request: Returns ViewModel for entity Log creation - /// - public class LogCreateViewModelRequest: CreateViewModelQuery - { - - } - - /// - /// Response: Returns ViewModel for entity Log creation - /// - public class LogCreateViewModelRequestHandler : CreateViewModelHandlerBase - { - protected override ValueTask GenerateCreateViewModel() - { - return new ValueTask(new LogCreateViewModel - { - CreatedAt = DateTime.UtcNow, - Level = LogLevel.Information.ToString(), - Message = "Generated automatically", - Logger = "LogCreateViewModelRequestHandler", - ThreadId = "0" - }); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogDeleteItem.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogDeleteItem.cs deleted file mode 100644 index 98e42636..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogDeleteItem.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Mediator.LogsWritable -{ - /// - /// Request: Log delete - /// - public class LogDeleteItemRequest: DeleteByIdQuery - { - public LogDeleteItemRequest(Guid id) : base(id) - { - } - } - - /// - /// Request: Log delete - /// - public class LogDeleteItemRequestHandler : DeleteByIdHandlerBase - { - public LogDeleteItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogPostItem.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogPostItem.cs deleted file mode 100644 index 61a1db35..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogPostItem.cs +++ /dev/null @@ -1,29 +0,0 @@ -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Mediator.LogsWritable -{ - /// - /// Request: Log creation - /// - public class LogPostItemRequest: PostItemQuery - { - public LogPostItemRequest(LogCreateViewModel model) : base(model) - { - } - } - - /// - /// Request: Log creation - /// - public class LogPostItemRequestHandler : PostItemHandlerBase - { - public LogPostItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogPutItem.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogPutItem.cs deleted file mode 100644 index ff48a71f..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogPutItem.cs +++ /dev/null @@ -1,37 +0,0 @@ -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Mediator.LogsWritable -{ - /// - /// Request: Log edit - /// - public class LogPutItemRequest: PutItemQuery - { - public LogPutItemRequest(LogUpdateViewModel model) : base(model) - { - } - } - - /// - /// Request: Log creation - /// - public class LogPutItemRequestHandler : PutItemHandlerBase - { - public LogPutItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - - protected override OperationResult ProcessOperationResult(OperationResult operationResult, LogViewModel response) - { - operationResult.AppendLog("Successfully updated"); - operationResult.Result = response; - return operationResult; - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogUpdateViewModel.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogUpdateViewModel.cs deleted file mode 100644 index 23b85cbd..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Mediator/LogsWritable/LogUpdateViewModel.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using AutoMapper; -using Calabonga.AspNetCore.Controllers.Handlers; -using Calabonga.AspNetCore.Controllers.Queries; -using $ext_projectname$.Entities; -using $safeprojectname$.ViewModels.LogViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Mediator.LogsWritable -{ - /// - /// Request: Returns ViewModel for entity Log creation - /// - public class LogUpdateViewModelRequest: UpdateViewModelQuery - { - public LogUpdateViewModelRequest(Guid id) : base(id) - { - } - } - - /// - /// Response: Returns ViewModel for entity Log creation - /// - public class LogUpdateViewModelRequestHandler : UpdateViewModelHandlerBase - { - public LogUpdateViewModelRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper) - { - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Middlewares/ETagMiddleware.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Middlewares/ETagMiddleware.cs deleted file mode 100644 index 154f2cb0..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Middlewares/ETagMiddleware.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System.IO; -using System.Security.Cryptography; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Net.Http.Headers; - -namespace $safeprojectname$.Middlewares -{ - /// - /// ETagger extension - /// - public static class ApplicationBuilderExtensions - { - /// - /// Use Custom middleware - /// - /// - public static void UseETagger(this IApplicationBuilder app) - { - app.UseMiddleware(); - } - } - - /// - /// ETag middleware from Mads Kristensen. - /// See https://madskristensen.net/blog/send-etag-headers-in-aspnet-core/ - /// - public class ETagMiddleware - { - private readonly RequestDelegate _next; - - /// - public ETagMiddleware(RequestDelegate next) - { - _next = next; - } - - /// - /// Invoke middleware entry point - /// - /// - /// - public async Task InvokeAsync(HttpContext context) - { - var response = context.Response; - var originalStream = response.Body; - - using (var ms = new MemoryStream()) - { - response.Body = ms; - - await _next(context); - - if (IsEtagSupported(response)) - { - var checksum = CalculateChecksum(ms); - - response.Headers[HeaderNames.ETag] = checksum; - - if (context.Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var etag) && checksum == etag) - { - response.StatusCode = StatusCodes.Status304NotModified; - return; - } - } - - ms.Position = 0; - await ms.CopyToAsync(originalStream); - } - } - - private static bool IsEtagSupported(HttpResponse response) - { - if (response.StatusCode != StatusCodes.Status200OK) - return false; - - // The 100kb length limit is not based in science. Feel free to change - if (response.Body.Length > 100 * 1024) - return false; - - if (response.Headers.ContainsKey(HeaderNames.ETag)) - return false; - - return true; - } - - private static string CalculateChecksum(MemoryStream ms) - { - string checksum = ""; - - using (var algo = SHA1.Create()) - { - ms.Position = 0; - byte[] bytes = algo.ComputeHash(ms); - checksum = $"\"{WebEncoders.Base64UrlEncode(bytes)}\""; - } - - return checksum; - } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Middlewares/ErrorHandle.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Middlewares/ErrorHandle.cs deleted file mode 100644 index baa03412..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Middlewares/ErrorHandle.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Threading.Tasks; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; - -namespace $safeprojectname$.Middlewares -{ - /// - /// Custom error handler. It allows to view error messages on UI - /// - public class ErrorHandlingMiddleware - { - private readonly RequestDelegate _next; - - /// - public ErrorHandlingMiddleware(RequestDelegate next) - { - _next = next; - } - - /// - /// Invoke middle ware. Entry point - /// - /// - /// - public async Task Invoke(HttpContext context) - { - try - { - await _next(context); - } - catch (Exception ex) - { - await HandleExceptionAsync(context, ex); - } - } - - private static Task HandleExceptionAsync(HttpContext context, Exception exception) - { - try - { - var result = JsonConvert.SerializeObject(ExceptionHelper.GetMessages(exception), Formatting.Indented); - if (result?.Length > 4000) - { - return context.Response.WriteAsync("Error message to long. Please use DEBUG in method HandleExceptionAsync to handle a whole of text of the exception"); - } - return context.Response.WriteAsync(result); - } - catch - { - return context.Response.WriteAsync($"{exception.Message} For more information please use DEBUG in method HandleExceptionAsync to handle a whole of text of the exception"); - } - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/MyTemplate.vstemplate b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/MyTemplate.vstemplate deleted file mode 100644 index 13aa849d..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/MyTemplate.vstemplate +++ /dev/null @@ -1,146 +0,0 @@ - - - Calabonga.Microservice.Module.Web - API for microservice - CSharp - - - 1000 - true - Calabonga.Microservice.Module.Web - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - launchSettings.json - - - - ConfigureCommon.cs - ConfigureEndpoints.cs - - - ConfigureServicesAuthentication.cs - ConfigureServicesBase.cs - ConfigureServicesControllers.cs - ConfigureServicesCors.cs - ConfigureServicesMediator.cs - ConfigureServicesSwagger.cs - ConfigureServicesValidators.cs - - - ApplySummariesOperationFilter.cs - - - - LogsReadonly2Controller.cs - LogsReadonlyController.cs - LogsWritable2Controller.cs - LogsWritableController.cs - - - ApplicationBuilderExtensions.cs - AssemblyExtensions.cs - DateTimeExtensions.cs - EntityValidatorExtensions.cs - - - - SwaggerFormAttribute.cs - SwaggerGroupAttribute.cs - ValidateModelStateAttribute.cs - - - CommonRegistrations.cs - - - - LogManager.cs - - - LogValidator.cs - - - LogViewModelFactory.cs - - - - - IViewModel.cs - IViewModelFactory.cs - ViewModelFactory.cs - - - - AsyncHelper.cs - EmailHelper.cs - EnumHelper.cs - Utilites.cs - ValidationContextHelper.cs - - - - IAutoMapper.cs - MapperConfigurationBase.cs - PagedListConverter.cs - - LogMapperConfiguration.cs - - - CacheService.cs - ICacheService.cs - ILogService.cs - LogService.cs - - - - ServiceBase.cs - - CurrentAppSettings.cs - - - LogValidator.cs - - - - - ValidationBehavior.cs - - - GetRoles.cs - LogGetById.cs - LogGetPaged.cs - - - LogCreateViewModel.cs - LogDeleteItem.cs - LogPostItem.cs - LogPutItem.cs - LogUpdateViewModel.cs - - - - ErrorHandle.cs - ETagMiddleware.cs - - - - LogCreateViewModel.cs - LogUpdateViewModel.cs - LogViewModel.cs - - - appsettings.json - appsettings.Development.json - appsettings.Production.json - Program.cs - Startup.cs - - - \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Program.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Program.cs deleted file mode 100644 index b9f0737a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Program.cs +++ /dev/null @@ -1,36 +0,0 @@ -// --------------------------------------- -// Name: Microservice Template -// Author: Calabonga (calabonga.net) -// Version: 2.2.0 -// Based on: ASP.NET Core 3.1 -// Created Date: 2019-10-06 -// Updated Date 2020-09-27 -// --------------------------------------- - -using System; -using $ext_projectname$.Core; -using $ext_projectname$.Data.DatabaseInitialization; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; - -namespace $safeprojectname$ -{ - public class Program - { - public static void Main(string[] args) - { - var webHost = CreateHostBuilder(args).Build(); - using (var scope = webHost.Services.CreateScope()) - { - DatabaseInitializer.Seed(scope.ServiceProvider); - } - Console.Title = $"{AppData.ServiceName} v.{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - webHost.Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()); - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Startup.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Startup.cs deleted file mode 100644 index d95562f4..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/Startup.cs +++ /dev/null @@ -1,57 +0,0 @@ -using $safeprojectname$.AppStart.Configures; -using $safeprojectname$.AppStart.ConfigureServices; -using $safeprojectname$.Infrastructure.DependencyInjection; -using Calabonga.UnitOfWork.Controllers.DependencyContainer; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$ -{ - /// - /// Startup entry - /// - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - /// - /// Configuration - /// - public IConfiguration Configuration { get; } - - /// - /// This method gets called by the runtime. Use this method to add services to the container. - /// - /// - public void ConfigureServices(IServiceCollection services) - { - ConfigureServicesBase.ConfigureServices(services, Configuration); - ConfigureServicesAuthentication.ConfigureServices(services, Configuration); - ConfigureServicesSwagger.ConfigureServices(services, Configuration); - ConfigureServicesCors.ConfigureServices(services, Configuration); - ConfigureServicesControllers.ConfigureServices(services); - ConfigureServicesMediator.ConfigureServices(services); - ConfigureServicesValidators.ConfigureServices(services); - - DependencyContainer.Common(services); - NimbleDependencyContainer.ConfigureServices(services); - } - - /// - /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - /// - /// - /// - /// - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, AutoMapper.IConfigurationProvider mapper) - { - ConfigureCommon.Configure(app, env, mapper); - ConfigureEndpoints.Configure(app); - } - } -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogCreateViewModel.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogCreateViewModel.cs deleted file mode 100644 index ef1c0f1c..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogCreateViewModel.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.ComponentModel.DataAnnotations; -using Calabonga.EntityFrameworkCore.Entities.Base; -using Microsoft.Extensions.Logging; - -namespace $safeprojectname$.ViewModels.LogViewModels -{ - /// - /// Data Transfer Object for Log entity - /// - public class LogCreateViewModel : IViewModel - { - /// - /// Log Created At - /// - [Required] - public DateTime CreatedAt { get; set; } - - /// - /// Service name or provider - /// - [Required] - [StringLength(255)] - public string Logger { get; set; } - - /// - /// Log level for logging. See - /// - [Required] - [StringLength(50)] - public string Level { get; set; } - - /// - /// Log Message - /// - [Required] - [StringLength(4000)] - public string Message { get; set; } - - /// - /// Thread identifier - /// - public string ThreadId { get; set; } - - /// - /// Exception message - /// - public string ExceptionMessage { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogUpdateViewModel.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogUpdateViewModel.cs deleted file mode 100644 index f10d6efb..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogUpdateViewModel.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace $safeprojectname$.ViewModels.LogViewModels -{ - /// - /// Log View model for Update operations - /// - public class LogUpdateViewModel : ViewModelBase - { - public string Logger { get; set; } - - public string Level { get; set; } - - public string Message { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogViewModel.cs b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogViewModel.cs deleted file mode 100644 index 7f07e20a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/ViewModels/LogViewModels/LogViewModel.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using Calabonga.EntityFrameworkCore.Entities.Base; - -namespace $safeprojectname$.ViewModels.LogViewModels -{ - /// - /// Log ViewModel - /// - public class LogViewModel: ViewModelBase - { - /// - /// Created at - /// - public DateTime CreatedAt { get; set; } - - /// - /// Logger name - /// - public string Logger { get; set; } - - /// - /// Level - /// - public string Level { get; set; } - - /// - /// Message text - /// - public string Message { get; set; } - - /// - /// Thread ID - /// - public string ThreadId { get; set; } - - /// - /// - /// - public string ExceptionMessage { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/__PreviewImage.png b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/__PreviewImage.png deleted file mode 100644 index f34977d9..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/__TemplateIcon.png b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/appsettings.Development.json b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/appsettings.Development.json deleted file mode 100644 index 1a1bae9d..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/appsettings.Development.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=;User ID=;Password=" - }, - "Logging": { - "IncludeScopes": false, - "Debug": { - "LogLevel": { - "Default": "Warning", - "System": "Information", - "Microsoft": "Information" - } - }, - "Console": { - "LogLevel": { - "Default": "Warning", - "System": "Information", - "Microsoft": "Information" - } - } - }, - "Cors": { - "Origins": "*" - }, - "IdentityServer": { - "Url": "http://localhost:10001" - }, - "CurrentAppSettings": { - "PageSize": 50 - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/appsettings.Production.json b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/appsettings.Production.json deleted file mode 100644 index 9aa86891..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/appsettings.Production.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=MicroserviceDb;Trusted_Connection=True;" - }, - "Logging": { - "IncludeScopes": false, - "Debug": { - "LogLevel": { - "Default": "Warning", - "System": "Information", - "Microsoft": "Information" - } - }, - "Console": { - "LogLevel": { - "Default": "Warning", - "System": "Information", - "Microsoft": "Information" - } - } - }, - "Cors": { - "Origins": "*" - }, - "IdentityServer": { - "Url": "http://localhost:10001" - }, - "CurrentAppSettings": { - "PageSize": 50 - } -} \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/appsettings.json b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/appsettings.json deleted file mode 100644 index def9159a..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Calabonga.Microservice.Module.Web/appsettings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Root.vstemplate b/AspNetCore v3.1/TemplateMicroserviceModuleV3/Root.vstemplate deleted file mode 100644 index 43475b43..00000000 --- a/AspNetCore v3.1/TemplateMicroserviceModuleV3/Root.vstemplate +++ /dev/null @@ -1,27 +0,0 @@ - - - Microservice Template - This template gives you a possibility to start developing a microservices system with UI (Swagger). Template developed on ASP.NET Core 3.1 - CSharp - - 1000 - true - Calabonga.Microservice.Module - true - Enabled - true - __TemplateIcon.png - __PreviewImage.png - - - - - - - Calabonga.Microservice.Module.Web\MyTemplate.vstemplate - Calabonga.Microservice.Module.Data\MyTemplate.vstemplate - Calabonga.Microservice.Module.Entities\MyTemplate.vstemplate - Calabonga.Microservice.Module.Core\MyTemplate.vstemplate - - - \ No newline at end of file diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/__PreviewImage.png b/AspNetCore v3.1/TemplateMicroserviceModuleV3/__PreviewImage.png deleted file mode 100644 index f34977d9..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceModuleV3/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v3.1/TemplateMicroserviceModuleV3/__TemplateIcon.png b/AspNetCore v3.1/TemplateMicroserviceModuleV3/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v3.1/TemplateMicroserviceModuleV3/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/.editorconfig b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/.editorconfig deleted file mode 100644 index ad6bdfaf..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/.editorconfig +++ /dev/null @@ -1,228 +0,0 @@ -root = true -# Remove the line below if you want to inherit .editorconfig settings from higher directories - -# C# files -[*.cs] - -#### Core EditorConfig Options #### -charset = utf-8-bom - -# Indentation and spacing -indent_size = 4 -indent_style = space -tab_width = 4 - -# New line preferences -end_of_line = crlf -insert_final_newline = false - -#### .NET Coding Conventions #### - -# Organize usings -dotnet_separate_import_directive_groups = false -dotnet_sort_system_directives_first = false - -# this. and Me. preferences -dotnet_style_qualification_for_event = false:suggestion -dotnet_style_qualification_for_field = false -dotnet_style_qualification_for_method = false:suggestion -dotnet_style_qualification_for_property = false:suggestion - -# Language keywords vs BCL types preferences -dotnet_style_predefined_type_for_locals_parameters_members = true -dotnet_style_predefined_type_for_member_access = true - -# Parentheses preferences -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_operators = never_if_unnecessary -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity - -# Modifier preferences -dotnet_style_require_accessibility_modifiers = for_non_interface_members - -# Expression-level preferences -dotnet_style_coalesce_expression = true -dotnet_style_collection_initializer = true -dotnet_style_explicit_tuple_names = true -dotnet_style_null_propagation = true -dotnet_style_object_initializer = true -dotnet_style_operator_placement_when_wrapping = beginning_of_line -dotnet_style_prefer_auto_properties = true:error -dotnet_style_prefer_compound_assignment = true -dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion -dotnet_style_prefer_conditional_expression_over_return = true:suggestion -dotnet_style_prefer_inferred_anonymous_type_member_names = true:error -dotnet_style_prefer_inferred_tuple_names = true -dotnet_style_prefer_is_null_check_over_reference_equality_method = true -dotnet_style_prefer_simplified_boolean_expressions = true -dotnet_style_prefer_simplified_interpolation = true - -# Field preferences -dotnet_style_readonly_field = true:error - -# Parameter preferences -dotnet_code_quality_unused_parameters = all - -# Suppression preferences -dotnet_remove_unnecessary_suppression_exclusions = none - -#### C# Coding Conventions #### - -# var preferences -csharp_style_var_elsewhere = true:suggestion -csharp_style_var_for_built_in_types = true:suggestion -csharp_style_var_when_type_is_apparent = true:suggestion - -# Expression-bodied members -csharp_style_expression_bodied_accessors = true:suggestion -csharp_style_expression_bodied_constructors = true:suggestion -csharp_style_expression_bodied_indexers = true:suggestion -csharp_style_expression_bodied_lambdas = true -csharp_style_expression_bodied_local_functions = false -csharp_style_expression_bodied_methods = true:suggestion -csharp_style_expression_bodied_operators = true:suggestion -csharp_style_expression_bodied_properties = true:suggestion - -# Pattern matching preferences -csharp_style_pattern_matching_over_as_with_null_check = true -csharp_style_pattern_matching_over_is_with_cast_check = true -csharp_style_prefer_not_pattern = true -csharp_style_prefer_pattern_matching = true -csharp_style_prefer_switch_expression = true - -# Null-checking preferences -csharp_style_conditional_delegate_call = true - -# Modifier preferences -csharp_prefer_static_local_function = true -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async - -# Code-block preferences -csharp_prefer_braces = true:error -csharp_prefer_simple_using_statement = true - -# Expression-level preferences -csharp_prefer_simple_default_expression = true -csharp_style_deconstructed_variable_declaration = true -csharp_style_implicit_object_creation_when_type_is_apparent = true -csharp_style_inlined_variable_declaration = true -csharp_style_pattern_local_over_anonymous_function = true -csharp_style_prefer_index_operator = true -csharp_style_prefer_range_operator = true -csharp_style_throw_expression = true -csharp_style_unused_value_assignment_preference = discard_variable -csharp_style_unused_value_expression_statement_preference = discard_variable - -# 'using' directive preferences -csharp_using_directive_placement = outside_namespace - -#### C# Formatting Rules #### - -# New line preferences -csharp_new_line_before_catch = true -csharp_new_line_before_else = true -csharp_new_line_before_finally = true -csharp_new_line_before_members_in_anonymous_types = true -csharp_new_line_before_members_in_object_initializers = true -csharp_new_line_before_open_brace = all -csharp_new_line_between_query_expression_clauses = true - -# Indentation preferences -csharp_indent_block_contents = true -csharp_indent_braces = false -csharp_indent_case_contents = true -csharp_indent_case_contents_when_block = true -csharp_indent_labels = no_change -csharp_indent_switch_labels = true - -# Space preferences -csharp_space_after_cast = false -csharp_space_after_colon_in_inheritance_clause = true -csharp_space_after_comma = true -csharp_space_after_dot = false -csharp_space_after_keywords_in_control_flow_statements = true -csharp_space_after_semicolon_in_for_statement = true -csharp_space_around_binary_operators = before_and_after -csharp_space_around_declaration_statements = false -csharp_space_before_colon_in_inheritance_clause = true -csharp_space_before_comma = false -csharp_space_before_dot = false -csharp_space_before_open_square_brackets = false -csharp_space_before_semicolon_in_for_statement = false -csharp_space_between_empty_square_brackets = false -csharp_space_between_method_call_empty_parameter_list_parentheses = false -csharp_space_between_method_call_name_and_opening_parenthesis = false -csharp_space_between_method_call_parameter_list_parentheses = false -csharp_space_between_method_declaration_empty_parameter_list_parentheses = false -csharp_space_between_method_declaration_name_and_open_parenthesis = false -csharp_space_between_method_declaration_parameter_list_parentheses = false -csharp_space_between_parentheses = false -csharp_space_between_square_brackets = false - -# Wrapping preferences -csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true - -#### Naming styles #### - -# Naming rules - -dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion -dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface -dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i - -dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.types_should_be_pascal_case.symbols = types -dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case - -dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members -dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case - -# Symbol specifications - -dotnet_naming_symbols.interface.applicable_kinds = interface -dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interface.required_modifiers = - -dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum -dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types.required_modifiers = - -dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method -dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.non_field_members.required_modifiers = - -# Naming styles - -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = -dotnet_naming_style.pascal_case.capitalization = pascal_case - -dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = -dotnet_naming_style.begins_with_i.capitalization = pascal_case - -# Instance fields are camelCase and start with _ -dotnet_naming_rule.instance_fields_should_be_camel_case.severity = hint -dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields -dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style - -dotnet_naming_symbols.instance_fields.applicable_kinds = field - -dotnet_naming_style.instance_field_style.capitalization = camel_case -dotnet_naming_style.instance_field_style.required_prefix = _ - -# ReSharper properties -max_line_length = 200 -resharper_csharp_max_line_length = 200 -resharper_csharp_wrap_after_declaration_lpar = true -resharper_csharp_wrap_extends_list_style = chop_if_long -resharper_csharp_wrap_lines = false -resharper_max_attribute_length_for_same_line = 300 -resharper_place_type_constraints_on_same_line = true -resharper_wrap_before_arrow_with_expressions = true -resharper_wrap_before_extends_colon = false \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/.template.config/template.json b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/.template.config/template.json deleted file mode 100644 index fc63ab16..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/.template.config/template.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/template", - "author": "Calabonga SOFT", - "classifications": [ - "Web", - "WebAPI" - ], - "name": "Calabonga.Microservice.IdentityModule v6.1.0", - "description": "Nimble Microservice Framework. This template gives you a possibility to start developing a microservice architecture with integrated UI (Swagger), Mediatr, Automapper and Authorization Server (OpenIddict OAuth 2.0). Template developed for .NET 6.0.x.", - "identity": "Calabonga.Microservice.IdentityModule", - "shortName": "nimbleminim", - "tags": { - "language": "C#", - "type": "project" - }, - "sourceName": "Calabonga.Microservice.IdentityModule", - "preferNameDirectory": true, - "symbols": { - "Framework": { - "type": "parameter", - "description": "The target framework for the project.", - "datatype": "choice", - "choices": [ - { - "choice": "net6.0" - } - ], - "defaultValue": "net6.0" - } - }, - "sources": [ - { - "modifiers": [ - { - "exclude": [ - ".vs/**", - ".idea/**", - "_ReSharper.Caches/**", - ".template_config/**" - ] - } - ] - } - ] -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/Auditable.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/Auditable.cs deleted file mode 100644 index d73ca209..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/Auditable.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Domain.Base; - -/// -/// Represents 'Audit-able' table from the Property Database -/// -public abstract class Auditable : Identity, IAuditable -{ - /// - /// DateTime when entity created. - /// It's never changed - /// - public DateTime CreatedAt { get; set; } - - /// - /// User name who created entity. - /// It's never changed - /// - public string CreatedBy { get; set; } - - /// - /// Last date entity updated - /// - public DateTime? UpdatedAt { get; set; } - - /// - /// Author of last updated - /// - public string UpdatedBy { get; set; } - -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/IAuditable.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/IAuditable.cs deleted file mode 100644 index 42b73b07..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/IAuditable.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Domain.Base; - -/// -/// Represent information about creation and last update -/// -public interface IAuditable -{ - /// - /// DateTime of creation. This value will never changed - /// - DateTime CreatedAt { get; set; } - - /// - /// Author name. This value never changed - /// - string CreatedBy { get; set; } - - /// - /// DateTime of last value update. Should be updated when entity data updated - /// - DateTime? UpdatedAt { get; set; } - - /// - /// Author of last value update. Should be updated when entity data updated - /// - string UpdatedBy { get; set; } - -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/NamedAuditable.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/NamedAuditable.cs deleted file mode 100644 index 66cdc7c6..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/NamedAuditable.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Domain.Base; - -/// -/// Audit-able with name -/// -public abstract class NamedAuditable : Auditable -{ - public string Name { get; set; } - - public string Description { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/NamedIdentity.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/NamedIdentity.cs deleted file mode 100644 index 9bbf2997..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/NamedIdentity.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Domain.Base; - -/// -/// NamedIdentity dictionary for selector -/// -public abstract class NamedIdentity : Identity -{ - /// - /// Entity name - /// - public string Name { get; set; } - - /// - /// Entity brief name - /// - public string BriefName { get; set; } - - /// - /// Brief descriptions - /// - public string Description { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj deleted file mode 100644 index 27ac3865..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - - net6.0 - enable - enable - - - diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRoleStore.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRoleStore.cs deleted file mode 100644 index 938b2c60..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRoleStore.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -namespace Calabonga.Microservice.IdentityModule.Infrastructure; - -/// -/// Application store for user -/// -public class ApplicationRoleStore : RoleStore -{ - public ApplicationRoleStore(ApplicationDbContext context, IdentityErrorDescriber describer = null) : base(context, describer) - { - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserStore.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserStore.cs deleted file mode 100644 index 4e314700..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserStore.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; - -namespace Calabonga.Microservice.IdentityModule.Infrastructure; - -/// -/// Application store for user -/// -public class ApplicationUserStore : UserStore -{ - public ApplicationUserStore(ApplicationDbContext context, IdentityErrorDescriber describer) - : base(context, describer) - { - - } - - /// - /// Finds and returns a user, if any, who has the specified . - /// - /// The user ID to search for. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The that represents the asynchronous operation, containing the user matching the specified if it exists. - /// - public override Task FindByIdAsync(string userId, CancellationToken cancellationToken = default) - => Users - .Include(x => x.ApplicationUserProfile).ThenInclude(x => x.Permissions) - .FirstOrDefaultAsync(u => u.Id.ToString() == userId, cancellationToken: cancellationToken)!; - - public override Task FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default) - => Users - .Include(x => x.ApplicationUserProfile).ThenInclude(x => x.Permissions) - .FirstOrDefaultAsync(u => u.NormalizedUserName == normalizedUserName, cancellationToken: cancellationToken)!; -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/Base/DbContextBase.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/Base/DbContextBase.cs deleted file mode 100644 index 4e119559..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/Base/DbContextBase.cs +++ /dev/null @@ -1,257 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Domain.Base; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; -using System.Reflection; - -namespace Calabonga.Microservice.IdentityModule.Infrastructure.Base; - -/// -/// Base DbContext with predefined configuration -/// -public abstract class DbContextBase : IdentityDbContext -{ - private const string DefaultUserName = "Anonymous"; - - protected DbContextBase(DbContextOptions options) : base(options) - { - LastSaveChangesResult = new SaveChangesResult(); - } - - public SaveChangesResult LastSaveChangesResult { get; } - - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - /// - /// Saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// The number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override int SaveChanges(bool acceptAllChangesOnSuccess) - { - try - { - DbSaveChanges(); - return base.SaveChanges(acceptAllChangesOnSuccess); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - public override int SaveChanges() - { - try - { - DbSaveChanges(); - return base.SaveChanges(); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - private void DbSaveChanges() - { - var createdEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added); - foreach (var entry in createdEntries) - { - if (!(entry.Entity is IAuditable)) - { - continue; - } - - var creationDate = DateTime.Now.ToUniversalTime(); - var userName = entry.Property("CreatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("CreatedBy").CurrentValue; - var updatedAt = entry.Property("UpdatedAt").CurrentValue; - var createdAt = entry.Property("CreatedAt").CurrentValue; - if (createdAt != null) - { - if (DateTime.Parse(createdAt.ToString()).Year > 1970) - { - entry.Property("CreatedAt").CurrentValue = ((DateTime)createdAt).ToUniversalTime(); - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - - if (updatedAt != null) - { - if (DateTime.Parse(updatedAt.ToString()).Year > 1970) - { - entry.Property("UpdatedAt").CurrentValue = ((DateTime)updatedAt).ToUniversalTime(); - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - - entry.Property("CreatedBy").CurrentValue = userName; - entry.Property("UpdatedBy").CurrentValue = userName; - - LastSaveChangesResult.AddMessage($"ChangeTracker has new entities: {entry.Entity.GetType()}"); - } - - var updatedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified); - foreach (var entry in updatedEntries) - { - if (entry.Entity is IAuditable) - { - var userName = entry.Property("UpdatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("UpdatedBy").CurrentValue; - entry.Property("UpdatedAt").CurrentValue = DateTime.Now.ToUniversalTime(); - entry.Property("UpdatedBy").CurrentValue = userName; - } - - LastSaveChangesResult.AddMessage($"ChangeTracker has modified entities: {entry.Entity.GetType()}"); - } - } - - /// - /// Configures the schema needed for the identity framework. - /// - /// - /// The builder being used to construct the model for this context. - /// - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - var applyGenericMethod = typeof(ModelBuilder).GetMethods(BindingFlags.Instance | BindingFlags.Public).First(x => x.Name == "ApplyConfiguration"); - foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters)) - { - foreach (var item in type.GetInterfaces()) - { - if (!item.IsConstructedGenericType || item.GetGenericTypeDefinition() != typeof(IEntityTypeConfiguration<>)) - { - continue; - } - - var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(item.GenericTypeArguments[0]); - applyConcreteMethod.Invoke(builder, new[] { Activator.CreateInstance(type) }); - break; - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj deleted file mode 100644 index ee993581..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj +++ /dev/null @@ -1,29 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs deleted file mode 100644 index 8b8ba54f..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs +++ /dev/null @@ -1,146 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Domain.Base; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - -namespace Calabonga.Microservice.IdentityModule.Infrastructure.DatabaseInitialization; - -/// -/// Database Initializer -/// -public static class DatabaseInitializer -{ - /// - /// Seeds one default users to database for demo purposes only - /// - /// - /// - public static async void SeedUsers(IServiceProvider serviceProvider) - { - using var scope = serviceProvider.CreateScope(); - await using var context = scope.ServiceProvider.GetService(); - - // ATTENTION! - // ----------------------------------------------------------------------------- - // This is should not be used when UseInMemoryDatabase() - // It should be uncomment when using UseSqlServer() settings or any other providers. - // ----------------------------------------------------------------------------- - //await context!.Database.EnsureCreatedAsync(); - //var pending = await context.Database.GetPendingMigrationsAsync(); - //if (pending.Any()) - //{ - // await context!.Database.MigrateAsync(); - //} - - if (context.Users.Any()) - { - return; - } - - var roles = AppData.Roles.ToArray(); - - foreach (var role in roles) - { - var roleManager = scope.ServiceProvider.GetRequiredService>(); - if (!context!.Roles.Any(r => r.Name == role)) - { - await roleManager.CreateAsync(new ApplicationRole { Name = role, NormalizedName = role.ToUpper() }); - } - } - - #region developer - - var developer1 = new ApplicationUser - { - Email = "microservice@yopmail.com", - NormalizedEmail = "MICROSERVICE@YOPMAIL.COM", - UserName = "microservice@yopmail.com", - FirstName = "Microservice", - LastName = "Administrator", - NormalizedUserName = "MICROSERVICE@YOPMAIL.COM", - PhoneNumber = "+79000000000", - EmailConfirmed = true, - PhoneNumberConfirmed = true, - SecurityStamp = Guid.NewGuid().ToString("D"), - ApplicationUserProfile = new ApplicationUserProfile - { - CreatedAt = DateTime.Now, - CreatedBy = "SEED", - Permissions = new List - { - new() - { - CreatedAt = DateTime.Now, - CreatedBy = "SEED", - PolicyName = "EventItems:UserRoles:View", - Description = "Access policy for EventItems controller user view" - } - } - } - }; - - if (!context!.Users.Any(u => u.UserName == developer1.UserName)) - { - var password = new PasswordHasher(); - var hashed = password.HashPassword(developer1, "123qwe!@#"); - developer1.PasswordHash = hashed; - var userStore = scope.ServiceProvider.GetRequiredService(); - var result = await userStore.CreateAsync(developer1); - if (!result.Succeeded) - { - throw new InvalidOperationException("Cannot create account"); - } - - var userManager = scope.ServiceProvider.GetService>(); - foreach (var role in roles) - { - var roleAdded = await userManager!.AddToRoleAsync(developer1, role); - if (roleAdded.Succeeded) - { - await context.SaveChangesAsync(); - } - } - } - - #endregion - - await context.SaveChangesAsync(); - } - - /// - /// Seeds one event to database for demo purposes only - /// - /// - public static async void SeedEvents(IServiceProvider serviceProvider) - { - using var scope = serviceProvider.CreateScope(); - await using var context = scope.ServiceProvider.GetService(); - - // ATTENTION! - // ----------------------------------------------------------------------------- - // This is should not be used when UseInMemoryDatabase() - // It should be uncomment when using UseSqlServer() settings or any other providers. - // ----------------------------------------------------------------------------- - //await context!.Database.EnsureCreatedAsync(); - //var pending = await context.Database.GetPendingMigrationsAsync(); - //if (pending.Any()) - //{ - // await context!.Database.MigrateAsync(); - //} - - if (context.EventItems.Any()) - { - return; - } - - await context.EventItems.AddAsync(new EventItem - { - CreatedAt = DateTime.UtcNow, - Id = Guid.Parse("1467a5b9-e61f-82b0-425b-7ec75f5c5029"), - Level = "Information", - Logger = "SEED", - Message = "Seed method some entities successfully save to ApplicationDbContext" - }); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/FeatureGroupNameAttribute.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/FeatureGroupNameAttribute.cs deleted file mode 100644 index 186beeaa..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/FeatureGroupNameAttribute.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Web.Application; - -/// -/// Swagger controller group attribute -/// -/// -[AttributeUsage(AttributeTargets.Method)] -public class FeatureGroupNameAttribute : Attribute -{ - /// - public FeatureGroupNameAttribute(string groupName) => GroupName = groupName; - - /// - /// Group name - /// - public string GroupName { get; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/LoggerExtensions.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/LoggerExtensions.cs deleted file mode 100644 index 152ae7d6..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/LoggerExtensions.cs +++ /dev/null @@ -1,74 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Web.Application; - -/// -/// The number identifiers for events in the microservices -/// -internal static class EventNumbers -{ - internal static readonly EventId UserRegistrationId = new EventId(9001, nameof(UserRegistrationId)); - internal static readonly EventId PostItemId = new EventId(9002, nameof(PostItemId)); -} - -/// -/// Event logging as ILogger extension. -/// Please see the video as the manual https://youtu.be/09EVKgHgwnM -/// -internal static class LoggerExtensions -{ - #region UserRegistration - - /// - /// EventItem register action event - /// - /// - /// - /// - internal static void MicroserviceUserRegistration(this ILogger source, string userName, Exception? exception = null) - { - switch (exception) - { - case null: - UserRegistrationExecute(source, userName, exception); - break; - default: - UserRegistrationFailedExecute(source, userName, exception); - break; - } - } - - private static readonly Action UserRegistrationExecute = - LoggerMessage.Define(LogLevel.Information, EventNumbers.UserRegistrationId, - "User {userName} successfully registred"); - - private static readonly Action UserRegistrationFailedExecute = - LoggerMessage.Define(LogLevel.Error, EventNumbers.UserRegistrationId, - "User {userName} registred failed"); - - #endregion - - #region PostItem - - internal static void MicroservicePostItem(this ILogger source, string entityName, Exception? exception = null) - { - switch (exception) - { - case null: - PostItemExecute(source, entityName, null); - break; - - default: - PostItemFailedExecute(source, entityName, exception); - break; - } - } - - private static readonly Action PostItemExecute = - LoggerMessage.Define(LogLevel.Information, EventNumbers.PostItemId, - "The {entityName} successfully saved"); - - private static readonly Action PostItemFailedExecute = - LoggerMessage.Define(LogLevel.Error, EventNumbers.PostItemId, - "The {entityName} saving failed"); - - #endregion -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/Services/AccountService.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/Services/AccountService.cs deleted file mode 100644 index 3d043ff3..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/Services/AccountService.cs +++ /dev/null @@ -1,278 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Domain.Base; -using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.Microservice.IdentityModule.Web.Definitions.Identity; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.Microservices.Core.Extensions; -using Calabonga.Microservices.Core.Validators; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using OpenIddict.Abstractions; -using System.Security.Claims; - -namespace Calabonga.Microservice.IdentityModule.Web.Application.Services; - -/// -/// Account service -/// -public class AccountService : IAccountService -{ - private readonly IUnitOfWork _unitOfWork; - private readonly ILogger _logger; - private readonly ApplicationUserClaimsPrincipalFactory _claimsFactory; - private readonly IHttpContextAccessor _httpContext; - private readonly IMapper _mapper; - private readonly UserManager _userManager; - private readonly RoleManager _roleManager; - - public AccountService( - IUserStore userStore, - IOptions optionsAccessor, - IPasswordHasher passwordHasher, - IEnumerable> userValidators, - IEnumerable> passwordValidators, - ILookupNormalizer keyNormalizer, - IdentityErrorDescriber errors, - IServiceProvider services, - ILogger> loggerRole, - IEnumerable> roleValidators, - IUnitOfWork unitOfWork, - ILogger logger, - ILogger> loggerUser, - ApplicationUserClaimsPrincipalFactory claimsFactory, - IHttpContextAccessor httpContext, - IMapper mapper) - { - _unitOfWork = unitOfWork; - _logger = logger; - _claimsFactory = claimsFactory; - _httpContext = httpContext; - _mapper = mapper; - - // We need to created a custom instance for current service - // It'll help to use Transaction in the Unit Of Work - _userManager = new UserManager(userStore, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, loggerUser); - var roleStore = new RoleStore(_unitOfWork.DbContext); - _roleManager = new RoleManager(roleStore, roleValidators, keyNormalizer, errors, loggerRole); - } - - /// - public Guid GetCurrentUserId() - { - var identity = _httpContext.HttpContext?.User.Identity; - var identitySub = identity?.GetSubjectId(); - return identitySub?.ToGuid() ?? Guid.Empty; - } - - /// - /// Returns instance after successful registration - /// - /// - /// - /// - public async Task> RegisterAsync(RegisterViewModel model, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var user = _mapper.Map(model); - await using var transaction = await _unitOfWork.BeginTransactionAsync(); - var result = await _userManager.CreateAsync(user, model.Password); - const string role = AppData.ManagerRoleName; - - if (result.Succeeded) - { - if (await _roleManager.FindByNameAsync(role) == null) - { - operation.Exception = new MicroserviceUserNotFoundException(); - operation.AddError(AppData.Exceptions.UserNotFoundException); - return await Task.FromResult(operation); - } - - await _userManager.AddToRoleAsync(user, role); - - var profile = _mapper.Map(model); - var profileRepository = _unitOfWork.GetRepository(); - - await profileRepository.InsertAsync(profile, cancellationToken); - await _unitOfWork.SaveChangesAsync(); - if (_unitOfWork.LastSaveChangesResult.IsOk) - { - var principal = await _claimsFactory.CreateAsync(user); - operation.Result = _mapper.Map(principal.Identity); - operation.AddSuccess(AppData.Messages.UserSuccessfullyRegistered); - _logger.LogInformation(operation.GetMetadataMessages()); - await transaction.CommitAsync(cancellationToken); - _logger.MicroserviceUserRegistration(model.Email); - return await Task.FromResult(operation); - } - } - var errors = result.Errors.Select(x => $"{x.Code}: {x.Description}"); - operation.AddError(string.Join(", ", errors)); - operation.Exception = _unitOfWork.LastSaveChangesResult.Exception; - await transaction.RollbackAsync(cancellationToken); - _logger.MicroserviceUserRegistration(model.Email, operation.Exception); - return await Task.FromResult(operation); - } - - /// - /// Returns user profile - /// - /// - /// - public async Task> GetProfileByIdAsync(string identifier) - { - var operation = OperationResult.CreateResult(); - var claimsPrincipal = await GetPrincipalByIdAsync(identifier); - operation.Result = _mapper.Map(claimsPrincipal.Identity); - return await Task.FromResult(operation); - } - - /// - /// Returns user profile - /// - /// - /// - public async Task> GetProfileByEmailAsync(string email) - { - var operation = OperationResult.CreateResult(); - var claimsPrincipal = await GetPrincipalByEmailAsync(email); - operation.Result = _mapper.Map(claimsPrincipal.Identity); - return await Task.FromResult(operation); - } - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - /// - public async Task GetPrincipalByIdAsync(string identifier) - { - if (string.IsNullOrEmpty(identifier)) - { - throw new MicroserviceException(); - } - var userManager = _userManager; - var user = await userManager.FindByIdAsync(identifier); - if (user == null) - { - throw new MicroserviceUserNotFoundException(); - } - - var defaultClaims = await _claimsFactory.CreateAsync(user); - return defaultClaims; - } - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - /// - public async Task GetPrincipalByEmailAsync(string email) - { - if (string.IsNullOrEmpty(email)) - { - throw new MicroserviceException(); - } - var userManager = _userManager; - var user = await userManager.FindByEmailAsync(email); - if (user == null) - { - throw new MicroserviceUserNotFoundException(); - } - - var defaultClaims = await _claimsFactory.CreateAsync(user); - return defaultClaims; - } - - /// - /// Returns user by his identifier - /// - /// - /// - public Task GetByIdAsync(Guid id) - { - var userManager = _userManager; - return userManager.FindByIdAsync(id.ToString()); - } - - /// - /// Returns current user account information or null when user does not logged in - /// - /// - public async Task GetCurrentUserAsync() - { - var userManager = _userManager; - var userId = GetCurrentUserId().ToString(); - var user = await userManager.FindByIdAsync(userId); - return user; - } - - /// - public async Task> GetUsersByEmailsAsync(IEnumerable emails) - { - var userManager = _userManager; - var result = new List(); - foreach (var email in emails) - { - var user = await userManager.FindByEmailAsync(email); - if (user != null && !result.Contains(user)) - { - result.Add(user); - } - } - return await Task.FromResult(result); - } - - /// - /// Check roles for current user - /// - /// - /// - public async Task IsInRolesAsync(string[] roleNames) - { - var userManager = _userManager; - var userId = GetCurrentUserId().ToString(); - var user = await userManager.FindByIdAsync(userId); - if (user == null) - { - var resultUserNotFound = new PermissionValidationResult(); - resultUserNotFound.AddError(AppData.Exceptions.UnauthorizedException); - return await Task.FromResult(resultUserNotFound); - } - foreach (var roleName in roleNames) - { - var ok = await userManager.IsInRoleAsync(user, roleName); - if (ok) - { - return new PermissionValidationResult(); - } - } - - var result = new PermissionValidationResult(); - result.AddError(AppData.Exceptions.UnauthorizedException); - return result; - } - - /// - public async Task> GetUsersInRoleAsync(string roleName) - { - var userManager = _userManager; - return await userManager.GetUsersInRoleAsync(roleName); - } - - #region privates - - private async Task AddClaimsToUser(UserManager userManager, ApplicationUser user, string role) - { - await userManager.AddClaimAsync(user, new Claim(OpenIddictConstants.Claims.Name, user.UserName)); - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.GivenName, user.FirstName ?? "John")); - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.Surname, user.LastName?? "Doe")); - await userManager.AddClaimAsync(user, new Claim(OpenIddictConstants.Claims.Email, user.Email)); - await userManager.AddClaimAsync(user, new Claim(OpenIddictConstants.Claims.Role, role)); - } - - #endregion -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/Services/IAccountService.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/Services/IAccountService.cs deleted file mode 100644 index 3ec1e87e..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/Services/IAccountService.cs +++ /dev/null @@ -1,89 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.Microservices.Core.Validators; -using Calabonga.OperationResults; -using System.Security.Claims; - -namespace Calabonga.Microservice.IdentityModule.Web.Application.Services; - -/// -/// Represent interface for account management -/// -public interface IAccountService -{ - /// - /// Returns a collection of the by emails - /// - /// - /// - Task> GetUsersByEmailsAsync(IEnumerable emails); - - /// - /// Get User Id from HttpContext - /// - /// - Guid GetCurrentUserId(); - - /// - /// Returns instance after successful registration - /// - /// - /// - /// - Task> RegisterAsync(RegisterViewModel model, CancellationToken cancellationToken); - - /// - /// Returns user profile - /// - /// - /// - Task> GetProfileByIdAsync(string identifier); - - /// - /// Returns user profile - /// - /// - /// - Task> GetProfileByEmailAsync(string email); - - /// - /// Returns User by user identifier - /// - /// - /// - Task GetByIdAsync(Guid id); - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - /// - Task GetPrincipalByIdAsync(string identifier); - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - /// - Task GetPrincipalByEmailAsync(string email); - - /// - /// Returns current user account information or null when user does not logged in - /// - /// - Task GetCurrentUserAsync(); - - /// - /// Check roles for current user - /// - /// - /// - Task IsInRolesAsync(string[] roleNames); - - /// - /// Returns all system administrators registered in the system - /// - /// - /// - Task> GetUsersInRoleAsync(string roleName); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/ValidatorBehavior.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/ValidatorBehavior.cs deleted file mode 100644 index 9364ac84..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Application/ValidatorBehavior.cs +++ /dev/null @@ -1,41 +0,0 @@ -using FluentValidation; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Application; - -/// -/// Base validator for requests -/// -/// -/// -public class ValidatorBehavior : IPipelineBehavior - where TRequest : IRequest -{ - private readonly IEnumerable> _validators; - - public ValidatorBehavior(IEnumerable> validators) => _validators = validators; - - /// - /// Pipeline handler. Perform any additional behavior and await the delegate as necessary - /// - /// Incoming request - /// Cancellation token - /// Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler. - /// Awaitable task returning the - public Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) - { - var failures = _validators - .Select(x => x.Validate(new ValidationContext(request))) - .SelectMany(x => x.Errors) - .Where(x => x != null) - .ToList(); - - if (!failures.Any()) - { - return next(); - } - - // return new ProblemDetails(); - throw new ValidationException(failures); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj deleted file mode 100644 index f40aa8c2..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj +++ /dev/null @@ -1,37 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Common/CommonDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Common/CommonDefinition.cs deleted file mode 100644 index e8c67205..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Common/CommonDefinition.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Common; - -/// -/// AspNetCore common configuration -/// -public class CommonDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddLocalization(); - services.AddHttpContextAccessor(); - services.AddResponseCaching(); - services.AddMemoryCache(); - - services.AddMvc(); - services.AddRazorPages(); - } - - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) - { - app.UseHttpsRedirection(); - app.MapRazorPages(); - app.MapDefaultControllerRoute(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Cors/CorsDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Cors/CorsDefinition.cs deleted file mode 100644 index 717792c7..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Cors/CorsDefinition.cs +++ /dev/null @@ -1,47 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Domain.Base; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Cors; - -/// -/// Cors configurations -/// -public class CorsDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - var origins = builder.Configuration.GetSection("Cors")?.GetSection("Origins")?.Value?.Split(','); - services.AddCors(options => - { - options.AddPolicy(AppData.PolicyName, policyBuilder => - { - policyBuilder.AllowAnyHeader(); - policyBuilder.AllowAnyMethod(); - if (origins is not {Length: > 0}) - { - return; - } - - if (origins.Contains("*")) - { - policyBuilder.AllowAnyHeader(); - policyBuilder.AllowAnyMethod(); - policyBuilder.SetIsOriginAllowed(host => true); - policyBuilder.AllowCredentials(); - } - else - { - foreach (var origin in origins) - { - policyBuilder.WithOrigins(origin); - } - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/DbContext/DbContextDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/DbContext/DbContextDefinition.cs deleted file mode 100644 index 2b0ab353..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/DbContext/DbContextDefinition.cs +++ /dev/null @@ -1,65 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.Microservice.IdentityModule.Web.Definitions.Identity; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using OpenIddict.Abstractions; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.DbContext; - -/// -/// ASP.NET Core services registration and configurations -/// -public class DbContextDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddDbContext(config => - { - // UseInMemoryDatabase - This for demo purposes only! - // Should uninstall package "Microsoft.EntityFrameworkCore.InMemory" and install what you need. - // For example: "Microsoft.EntityFrameworkCore.SqlServer" - config.UseInMemoryDatabase("DEMO-PURPOSES-ONLY"); - - // uncomment line below to use UseSqlServer(). Don't forget setup connection string in appSettings.json - //config.UseSqlServer(configuration.GetConnectionString(nameof(ApplicationDbContext))); - - // Register the entity sets needed by OpenIddict. - // Note: use the generic overload if you need to replace the default OpenIddict entities. - config.UseOpenIddict(); - }); - - - services.Configure(options => - { - options.ClaimsIdentity.UserNameClaimType = OpenIddictConstants.Claims.Name; - options.ClaimsIdentity.UserIdClaimType = OpenIddictConstants.Claims.Subject; - options.ClaimsIdentity.RoleClaimType = OpenIddictConstants.Claims.Role; - options.ClaimsIdentity.EmailClaimType = OpenIddictConstants.Claims.Email; - // configure more options if you need - }); - - services.AddIdentity(options => - { - options.Password.RequireDigit = false; - options.Password.RequireLowercase = false; - options.Password.RequireNonAlphanumeric = false; - options.Password.RequiredLength = 8; - options.Password.RequireUppercase = false; - }) - .AddSignInManager() - .AddEntityFrameworkStores() - .AddUserStore() - .AddRoleStore() - .AddUserManager>() - .AddClaimsPrincipalFactory() - .AddDefaultTokenProviders(); - - services.AddTransient(); - } -} diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/DependencyContainer/ContainerDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/DependencyContainer/ContainerDefinition.cs deleted file mode 100644 index c56bcfa1..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/DependencyContainer/ContainerDefinition.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Web.Application.Services; -using Calabonga.Microservice.IdentityModule.Web.Definitions.Identity; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.DependencyContainer; - -/// -/// Dependency container definition -/// -public class ContainerDefinition: AppDefinition -{ - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddTransient(); - services.AddTransient(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs deleted file mode 100644 index b58cb5fb..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs +++ /dev/null @@ -1,71 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Net.Http.Headers; -using System.Diagnostics; -using System.Security.Cryptography; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.ETagGenerator; - -/// -/// ETag Generator -/// -[DebuggerStepThrough] -public class ETagGeneratorDefinition : AppDefinition -{ - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) => - app.Use(async (context, next) => - { - var response = context.Response; - var originalStream = response.Body; - - await using var ms = new MemoryStream(); - response.Body = ms; - - await next(context); - - if (IsEtagSupported(response)) - { - var checksum = CalculateChecksum(ms); - - response.Headers[HeaderNames.ETag] = checksum; - - if (context.Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var etag) && checksum == etag) - { - response.StatusCode = StatusCodes.Status304NotModified; - return; - } - } - - ms.Position = 0; - await ms.CopyToAsync(originalStream); - }); - - - private static bool IsEtagSupported(HttpResponse response) - { - if (response.StatusCode != StatusCodes.Status200OK) - { - return false; - } - - // The 100kb length limit is not based in science. Feel free to change - if (response.Body.Length > 100 * 1024) - { - return false; - } - - return !response.Headers.ContainsKey(HeaderNames.ETag); - } - - private static string CalculateChecksum(MemoryStream ms) - { - using var algorithm = SHA1.Create(); - ms.Position = 0; - var bytes = algorithm.ComputeHash(ms); - return $"\"{WebEncoders.Base64UrlEncode(bytes)}\""; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs deleted file mode 100644 index d423b63a..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using FluentValidation; -using Microsoft.AspNetCore.Diagnostics; -using Serilog; -using System.Text.Json; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.ErrorHandling; - -/// -/// Custom Error handling -/// -public class ErrorHandlingDefinition : AppDefinition -{ - /// - /// Configure application for current application - /// - /// - /// - public override void ConfigureApplication(WebApplication app) => - app.UseExceptionHandler(error => error.Run(async context => - { - - context.Response.ContentType = "application/json"; - var contextFeature = context.Features.Get(); - if (contextFeature is not null) - { - // handling validation errors - if (contextFeature.Error is ValidationException failures) - { - await context.Response.WriteAsync(JsonSerializer.Serialize(failures.Errors)); - context.Response.StatusCode = StatusCodes.Status400BadRequest; - return; - } - - // handling all another errors - Log.Error($"Something went wrong in the {contextFeature.Error}"); - context.Response.StatusCode = StatusCodes.Status500InternalServerError; - - if (app.Environment.IsDevelopment()) - { - await context.Response.WriteAsync($"INTERNAL SERVER ERROR: {contextFeature.Error}"); - } - else - { - await context.Response.WriteAsync("INTERNAL SERVER ERROR. PLEASE TRY AGAIN LATER"); - } - } - })); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/FluentValidating/FluentValidationDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/FluentValidating/FluentValidationDefinition.cs deleted file mode 100644 index d3602ffe..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/FluentValidating/FluentValidationDefinition.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using FluentValidation; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.FluentValidating; - -/// -/// FluentValidation registration as Application definition -/// -public class FluentValidationDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.Configure(options => - { - options.SuppressModelStateInvalidFilter = true; - }); - - services.AddValidatorsFromAssembly(typeof(Program).Assembly); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/ApplicationUserClaimsPrincipalFactory.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/ApplicationUserClaimsPrincipalFactory.cs deleted file mode 100644 index 1de65c13..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/ApplicationUserClaimsPrincipalFactory.cs +++ /dev/null @@ -1,69 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Infrastructure; -using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.Options; -using OpenIddict.Abstractions; -using System.Security.Claims; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Identity; - -/// -/// User Claims Principal Factory override from Microsoft Identity framework -/// -public class ApplicationUserClaimsPrincipalFactory : UserClaimsPrincipalFactory -{ - /// - public ApplicationUserClaimsPrincipalFactory( - UserManager userManager, - RoleManager roleManager, - IOptions optionsAccessor) - : base(userManager, roleManager, optionsAccessor) { } - - /// - /// Creates a from an user asynchronously. - /// - /// The user to create a from. - /// The that represents the asynchronous creation operation, containing the created . - public override async Task CreateAsync(ApplicationUser user) - { - var principal = await base.CreateAsync(user); - - - - if (user.ApplicationUserProfile?.Permissions != null) - { - var permissions = user.ApplicationUserProfile.Permissions.ToList(); - if (permissions.Any()) - { - permissions.ForEach(x => ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim(x.PolicyName, nameof(x.PolicyName).ToLower()))); - } - } - - ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim("framework", "nimble")); - - if (!string.IsNullOrWhiteSpace(user.UserName)) - { - ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim(ClaimTypes.Name, user.UserName)); - } - - if (!string.IsNullOrWhiteSpace(user.FirstName)) - { - ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName)); - } - - if (!string.IsNullOrWhiteSpace(user.LastName)) - { - ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim(ClaimTypes.Surname, user.LastName)); - } - - //// For this sample, just include all claims in all token types. - //// In reality, claims' destinations would probably differ by token type and depending on the scopes requested. - //// In our case (demo) we're using OpenIddictConstants.Destinations.AccessToken and OpenIddictConstants.Destinations.IdentityToken - foreach (var principalClaim in principal.Claims) - { - principalClaim.SetDestinations(OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken); - } - - return principal; - } - -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/AuthorizationDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/AuthorizationDefinition.cs deleted file mode 100644 index e09adb3f..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/AuthorizationDefinition.cs +++ /dev/null @@ -1,55 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Authorization; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Identity; - -/// -/// Authorization Policy registration -/// -public class AuthorizationDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - - services - .AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; - }) - .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => - { - options.LoginPath = "/connect/login"; - }); - - services.AddAuthorization(); - services.AddSingleton(); - services.AddSingleton(); - } - - /// - /// Configure application for current application - /// - /// - /// - public override void ConfigureApplication(WebApplication app) - { - app.UseHttpsRedirection(); - app.UseRouting(); - app.UseCors("CorsPolicy"); - app.UseAuthentication(); - app.UseAuthorization(); - - // registering UserIdentity helper as singleton - UserIdentity.Instance.Configure(app.Services.GetService()!); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/AutomapperDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/AutomapperDefinition.cs deleted file mode 100644 index 85844f55..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/AutomapperDefinition.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Mapping; - -/// -/// Register Automapper as application definition -/// -public class AutomapperDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - => services.AddAutoMapper(typeof(Program)); - - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) - { - var mapper = app.Services.GetRequiredService(); - if (app.Environment.IsDevelopment()) - { - // validate Mapper Configuration - mapper.AssertConfigurationIsValid(); - } - else - { - mapper.CompileMappings(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/PagedListConverter.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/PagedListConverter.cs deleted file mode 100644 index 2414e948..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/PagedListConverter.cs +++ /dev/null @@ -1,23 +0,0 @@ -using AutoMapper; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Mapping; - -/// -/// Generic converter for IPagedList collections -/// -/// -/// -public class PagedListConverter : ITypeConverter, IPagedList> -{ - /// Performs conversion from source to destination type - /// Source object - /// Destination object - /// Resolution context - /// Destination object - public IPagedList Convert(IPagedList source, IPagedList destination, ResolutionContext context) => - // ReSharper disable once ConditionIsAlwaysTrueOrFalse - source == null - ? PagedList.Empty() - : PagedList.From(source, items => context.Mapper.Map>(items)); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs deleted file mode 100644 index 7fcb03d5..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Mediator.Base; - -/// -/// Transaction Behavior -/// -/// -/// -public class TransactionBehavior : IPipelineBehavior - where TRequest : IRequest -{ - private readonly IUnitOfWork _unitOfWork; - - public TransactionBehavior(IUnitOfWork unitOfWork) => _unitOfWork = unitOfWork; - - - public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) - { - await using var transaction = await _unitOfWork.BeginTransactionAsync(); - try - { - var response = await next(); - await transaction.CommitAsync(cancellationToken); - return response; - } - catch (Exception) - { - await transaction.RollbackAsync(cancellationToken); - throw; - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/EventItemPostTransactionBehavior.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/EventItemPostTransactionBehavior.cs deleted file mode 100644 index 338d1921..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/EventItemPostTransactionBehavior.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Web.Definitions.Mediator.Base; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Mediator; - -public class EventItemPostTransactionBehavior : TransactionBehavior>, OperationResult> -{ - public EventItemPostTransactionBehavior(IUnitOfWork unitOfWork) : base(unitOfWork) { } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/MediatorDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/MediatorDefinition.cs deleted file mode 100644 index 8ff6b8dd..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/MediatorDefinition.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Web.Application; -using MediatR; -using System.Reflection; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Mediator; - -/// -/// Register Mediator as application definition -/// -public class MediatorDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>)); - services.AddMediatR(Assembly.GetExecutingAssembly()); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AppPermissionHandler.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AppPermissionHandler.cs deleted file mode 100644 index 327ed020..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AppPermissionHandler.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Calabonga.Microservices.Core; -using Microsoft.AspNetCore.Authorization; -using System.Security.Claims; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; - -/// -/// Permission handler for custom authorization implementations -/// -public class AppPermissionHandler : AuthorizationHandler -{ - /// - protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) - { - if (context.User.Identity is null) - { - return Task.CompletedTask; - } - - var identity = (ClaimsIdentity)context.User.Identity; - var claim = ClaimsHelper.GetValue(identity, requirement.PermissionName); - if (claim == null) - { - return Task.CompletedTask; - } - - context.Succeed(requirement); - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AuthData.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AuthData.cs deleted file mode 100644 index d1f7a410..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AuthData.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Microsoft.AspNetCore.Authentication.Cookies; -using OpenIddict.Validation.AspNetCore; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; - -public static class AuthData -{ - public const string AuthSchemes = CookieAuthenticationDefaults.AuthenticationScheme + "," + OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme; -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/OpenIddictDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/OpenIddictDefinition.cs deleted file mode 100644 index 85ff965c..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/OpenIddictDefinition.cs +++ /dev/null @@ -1,123 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.Microservice.IdentityModule.Web.HostedServices; -using OpenIddict.Abstractions; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; - -public class OpenIddictDefinition : AppDefinition -{ - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddOpenIddict() - // Register the OpenIddict core components. - .AddCore(options => - { - // Configure OpenIddict to use the Entity Framework Core stores and models. - // Note: call ReplaceDefaultEntities() to replace the default entities. - options.UseEntityFrameworkCore() - .UseDbContext() - .ReplaceDefaultEntities(); - }) - - // Register the OpenIddict server components. - .AddServer(options => - { - // Note: the sample uses the code and refresh token flows but you can enable - // the other flows if you need to support implicit, password or client credentials. - // Supported flows are: - // => Authorization code flow - // => Client credentials flow - // => Device code flow - // => Implicit flow - // => Password flow - // => Refresh token flow - options - .AllowAuthorizationCodeFlow()//.RequireProofKeyForCodeExchange() - .AllowPasswordFlow() - .AllowClientCredentialsFlow() - .AllowRefreshTokenFlow(); - - // Using reference tokens means the actual access and refresh tokens - // are stored in the database and different tokens, referencing the actual - // tokens (in the db), are used in request headers. The actual tokens are not - // made public. - // => options.UseReferenceAccessTokens(); - // => options.UseReferenceRefreshTokens(); - - // Set the lifetime of your tokens - // => options.SetAccessTokenLifetime(TimeSpan.FromMinutes(30)); - // => options.SetRefreshTokenLifetime(TimeSpan.FromDays(7)); - - // Enable the token endpoint. - options - .SetAuthorizationEndpointUris("/connect/authorize") - .SetLogoutEndpointUris("/connect/logout") - .SetTokenEndpointUris("/connect/token") - .SetUserinfoEndpointUris("/connect/userinfo"); - - // Encryption and signing of tokens - options - .AddEphemeralEncryptionKey() // only for Developing mode - .AddEphemeralSigningKey() // only for Developing mode - .DisableAccessTokenEncryption(); // only for Developing mode - - // Mark the "email", "profile" and "roles" scopes as supported scopes. - options.RegisterScopes( - OpenIddictConstants.Scopes.Email, - OpenIddictConstants.Scopes.Profile, - OpenIddictConstants.Scopes.Roles, - "api", - "custom"); - - // Register the signing and encryption credentials. - options - .AddDevelopmentEncryptionCertificate() - .AddDevelopmentSigningCertificate(); - - // Register the ASP.NET Core host and configure the ASP.NET Core options. - options - .UseAspNetCore() - .EnableTokenEndpointPassthrough() - .EnableAuthorizationEndpointPassthrough(); - - //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); - //JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear(); - - //options.AddEventHandler(builder => - //{ - // builder.SetOrder(OpenIddictServerHandlers.GenerateIdentityModelRefreshToken.Descriptor.Order - 1) - // .AddFilter() - // .SetType(OpenIddictServerHandlerType.Custom) - // .UseInlineHandler(context => - // { - // context.RefreshTokenPrincipal = context.RefreshTokenPrincipal.Clone( - // claim => claim.Type is ( - // OpenIddictConstants.Claims.Private.AuthorizationId or - // OpenIddictConstants.Claims.Private.Presenter or - // OpenIddictConstants.Claims.Private.TokenId or - // OpenIddictConstants.Claims.Private.Scope or - // OpenIddictConstants.Claims.Subject or - // OpenIddictConstants.Claims.ExpiresAt - // ) - // ); - // return default; - // }); - //}); - }) - - // Register the OpenIddict validation components. - .AddValidation(options => - { - // Import the configuration from the local OpenIddict server instance. - options.UseLocalServer(); - - // Register the ASP.NET Core host. - options.UseAspNetCore(); - }); - - // Register the worker responsible for seeding the database. - // Note: in a real world application, this step should be part of a setup script. - services.AddHostedService(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Swagger/SwaggerDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Swagger/SwaggerDefinition.cs deleted file mode 100644 index 592fdc70..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Swagger/SwaggerDefinition.cs +++ /dev/null @@ -1,121 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Domain.Base; -using Calabonga.Microservice.IdentityModule.Web.Application; -using Microsoft.AspNetCore.Mvc; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerUI; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Swagger; - -/// -/// Swagger definition for application -/// -public class SwaggerDefinition : AppDefinition -{ - - private const string _appVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - private const string _swaggerConfig = "/swagger/v1/swagger.json"; - - public override void ConfigureApplication(WebApplication app) - { - if (!app.Environment.IsDevelopment()) - { - return; - } - - var url = app.Services.GetRequiredService().GetValue("AuthServer:Url"); - - app.UseSwagger(); - app.UseSwaggerUI(settings => - { - settings.SwaggerEndpoint(_swaggerConfig, $"{AppData.ServiceName} v.{_appVersion}"); - settings.HeadContent = $"{ThisAssembly.Git.Branch.ToUpper()} {ThisAssembly.Git.Commit.ToUpper()}"; - settings.DocumentTitle = $"{AppData.ServiceName}"; - settings.DefaultModelExpandDepth(0); - settings.DefaultModelRendering(ModelRendering.Model); - settings.DefaultModelsExpandDepth(0); - settings.DocExpansion(DocExpansion.None); - settings.OAuthScopeSeparator(" "); - settings.OAuthClientId("client-id-code"); - settings.OAuthClientSecret("client-secret-code"); - settings.DisplayRequestDuration(); - settings.OAuthAppName(AppData.ServiceName); - settings.OAuth2RedirectUrl($"{url}/swagger/oauth2-redirect.html"); - }); - } - - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); - services.AddEndpointsApiExplorer(); - services.AddSwaggerGen(options => - { - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = AppData.ServiceName, - Version = _appVersion, - Description = AppData.ServiceDescription - }); - - options.ResolveConflictingActions(x => x.First()); - - options.TagActionsBy(api => - { - string tag; - if (api.ActionDescriptor is { } descriptor) - { - var attribute = descriptor.EndpointMetadata.OfType().FirstOrDefault(); - tag = attribute?.GroupName ?? descriptor.RouteValues["controller"] ?? "Untitled"; - } - else - { - tag = api.RelativePath!; - } - - var tags = new List(); - if (!string.IsNullOrEmpty(tag)) - { - tags.Add(tag); - } - return tags; - }); - - var url = builder.Configuration.GetSection("AuthServer").GetValue("Url"); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - AuthorizationCode = new OpenApiOAuthFlow - { - TokenUrl = new Uri($"{url}/connect/token", UriKind.Absolute), - AuthorizationUrl = new Uri($"{url}/connect/authorize", UriKind.Absolute), - Scopes = new Dictionary - { - { "api", "Default scope" } - }, - - } - } - }); - options.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "oauth2" - }, - In = ParameterLocation.Cookie, - Type = SecuritySchemeType.OAuth2 - - }, - new List() - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/UoW/UnitOfWorkDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/UoW/UnitOfWorkDefinition.cs deleted file mode 100644 index 89bc05e7..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/UoW/UnitOfWorkDefinition.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.UoW; - -/// -/// Unit of Work registration as application definition -/// -public class UnitOfWorkDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - => services.AddUnitOfWork(); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/EventItemEndpoints.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/EventItemEndpoints.cs deleted file mode 100644 index 362ed75f..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/EventItemEndpoints.cs +++ /dev/null @@ -1,59 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Web.Application; -using Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.Queries; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints; - -public class EventItemEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("/api/event-items/{id:guid}", LogGetById); - app.MapGet("/api/event-items/paged", LogGetPaged); - app.MapPost("/api/event-items/", PostLog); - app.MapPut("/api/event-items/{id:guid}", PutLog); - app.MapDelete("/api/event-items/{id:guid}", LogDelete); - } - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogGetById([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new GetEventItemByIdRequest(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogDelete([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new DeleteEventItemRequest(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task>> LogGetPaged([FromServices] IMediator mediator, int pageIndex, int pageSize, string? search, HttpContext context) - => await mediator.Send(new GetEventItemPagedRequest(pageIndex, pageSize, search), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PostLog([FromServices] IMediator mediator, EventItemCreateViewModel model, HttpContext context) - => await mediator.Send(new PostEventItemRequest(model), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PutLog([FromServices] IMediator mediator, Guid id, EventItemUpdateViewModel model, HttpContext context) - => await mediator.Send(new PutEventItemRequest(id, model), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/EventItemMapperConfiguration.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/EventItemMapperConfiguration.cs deleted file mode 100644 index 2d0078de..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/EventItemMapperConfiguration.cs +++ /dev/null @@ -1,32 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Web.Definitions.Mapping; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints; - -/// -/// Mapper Configuration for entity EventItem -/// -public class EventItemMapperConfiguration : Profile -{ - /// - public EventItemMapperConfiguration() - { - CreateMap() - .ForMember(x => x.Id, o => o.Ignore()); - - CreateMap(); - - CreateMap(); - - CreateMap() - .ForMember(x => x.CreatedAt, o => o.Ignore()) - .ForMember(x => x.ThreadId, o => o.Ignore()) - .ForMember(x => x.ExceptionMessage, o => o.Ignore()); - - CreateMap, IPagedList>() - .ConvertUsing>(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/EventItemValidator.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/EventItemValidator.cs deleted file mode 100644 index fa73201a..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/EventItemValidator.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.ViewModels; -using FluentValidation; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints; - -/// -/// RegisterViewModel Validator -/// -public class EventItemCreateRequestValidator : AbstractValidator -{ - public EventItemCreateRequestValidator() => RuleSet("default", () => - { - RuleFor(x => x.CreatedAt).NotNull(); - RuleFor(x => x.Message).NotEmpty().NotNull().MaximumLength(4000); - RuleFor(x => x.Level).NotEmpty().NotNull().MaximumLength(50); - RuleFor(x => x.Logger).NotNull().NotEmpty().MaximumLength(255); - - RuleFor(x => x.ThreadId).MaximumLength(50); - RuleFor(x => x.ExceptionMessage).MaximumLength(4000); - }); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/DeleteEventItem.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/DeleteEventItem.cs deleted file mode 100644 index 74057116..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/DeleteEventItem.cs +++ /dev/null @@ -1,55 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem delete -/// -public record DeleteEventItemRequest(Guid Id) : IRequest>; - -/// -/// Request: EventItem delete -/// -public class DeleteEventItemRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - - private readonly IMapper _mapper; - - public DeleteEventItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(DeleteEventItemRequest request, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.FindAsync(request.Id); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException("Entity not found")); - return operation; - } - repository.Delete(entity); - await _unitOfWork.SaveChangesAsync(); - if (_unitOfWork.LastSaveChangesResult.IsOk) - { - operation.Result = _mapper.Map(entity); - return operation; - } - operation.AddError(_unitOfWork.LastSaveChangesResult.Exception); - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/GetEventItemById.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/GetEventItemById.cs deleted file mode 100644 index 17e5a0d4..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/GetEventItemById.cs +++ /dev/null @@ -1,48 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request for EventItem by Identifier -/// -public record GetEventItemByIdRequest(Guid Id) : IRequest>; - -/// -/// Response for Request for EventItem by Identifier -/// -public class GetEventItemByIdRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public GetEventItemByIdRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request getting log by identifier - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(GetEventItemByIdRequest request, CancellationToken cancellationToken) - { - var id = request.Id; - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entityWithoutIncludes = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == id); - if (entityWithoutIncludes == null) - { - operation.AddError(new MicroserviceNotFoundException($"Entity with identifier {id} not found")); - return operation; - } - operation.Result = _mapper.Map(entityWithoutIncludes); - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/GetEventItemPaged.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/GetEventItemPaged.cs deleted file mode 100644 index f46ccdd2..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/GetEventItemPaged.cs +++ /dev/null @@ -1,75 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.PredicatesBuilder; -using Calabonga.UnitOfWork; -using MediatR; -using System.Linq.Expressions; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request for paged list of EventItems -/// -public record GetEventItemPagedRequest(int PageIndex, int PageSize, string? Search) : IRequest>>; - -/// -/// Request for paged list of EventItems -/// -public class GetEventItemPagedRequestHandler : IRequestHandler>> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public GetEventItemPagedRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task>> Handle(GetEventItemPagedRequest request, - CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult>(); - var predicate = GetPredicate(request.Search); - var pagedList = await _unitOfWork.GetRepository() - .GetPagedListAsync( - predicate: predicate, - pageIndex: request.PageIndex, - pageSize: request.PageSize, - cancellationToken: cancellationToken); - - if (pagedList == null) - { - operation.Result = PagedList.Empty(); - operation.AddWarning("Response does not return the result for pagination."); - return operation; - } - - if (pagedList.PageIndex > pagedList.TotalPages) - { - pagedList = await _unitOfWork.GetRepository() - .GetPagedListAsync( - pageIndex: 0, - pageSize: request.PageSize, cancellationToken: cancellationToken); - } - - operation.Result = _mapper.Map>(pagedList); - return operation; - } - - private Expression> GetPredicate(string? search) - { - var predicate = PredicateBuilder.True(); - if (search is null) - { - return predicate; - } - - predicate = predicate.And(x => x.Message.Contains(search)); - predicate = predicate.Or(x => x.Logger.Contains(search)); - predicate = predicate.Or(x => x.Level.Contains(search)); - return predicate; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/PostEventItem.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/PostEventItem.cs deleted file mode 100644 index 7e033479..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/PostEventItem.cs +++ /dev/null @@ -1,63 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem creation -/// -public record PostEventItemRequest(EventItemCreateViewModel Model) : IRequest>; - -/// -/// Request: EventItem creation -/// -public class PostEventItemRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - private readonly ILogger _logger; - - - public PostEventItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper, ILogger logger) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - _logger = logger; - } - - public async Task> Handle(PostEventItemRequest eventItemRequest, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - - var entity = _mapper.Map(eventItemRequest.Model); - if (entity == null) - { - operation.AddError(new MicroserviceUnauthorizedException(AppContracts.Exceptions.MappingException)); - return operation; - } - - await _unitOfWork.GetRepository().InsertAsync(entity, cancellationToken); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - - var mapped = _mapper.Map(entity); - - operation.Result = mapped; - operation.AddSuccess("Successfully created"); - return operation; - } - - operation.AddError(lastResult.Exception ?? new ApplicationException("Something went wrong")); - - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/UpdateEventItem.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/UpdateEventItem.cs deleted file mode 100644 index c7c6c156..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/Queries/UpdateEventItem.cs +++ /dev/null @@ -1,59 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem edit -/// -public record PutEventItemRequest(Guid Id, EventItemUpdateViewModel Model) : IRequest>; - -/// -/// Request: EventItem creation -/// -public class PutEventItemRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public PutEventItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task> Handle(PutEventItemRequest eventItemRequest, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == eventItemRequest.Id, disableTracking: false); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException(AppContracts.Exceptions.NotFoundException)); - return operation; - } - - _mapper.Map(eventItemRequest.Model, entity); - - repository.Update(entity); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("Successfully updated"); - return operation; - } - - operation.AddError(lastResult.Exception ?? new ApplicationException("Something went wrong")); - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemCreateViewModel.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemCreateViewModel.cs deleted file mode 100644 index 807a1ddd..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemCreateViewModel.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Domain.Base; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemCreateViewModel : IViewModel -{ - /// - /// EventItem Created At - /// - public DateTime CreatedAt { get; set; } - - /// - /// Service name or provider - /// - public string Logger { get; set; } = null!; - - /// - /// EventItem level for logging. See - /// - public string Level { get; set; } = null!; - - /// - /// EventItem Message - /// - public string Message { get; set; } = null!; - - /// - /// Thread identifier - /// - public string? ThreadId { get; set; } - - /// - /// Exception message - /// - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemUpdateViewModel.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemUpdateViewModel.cs deleted file mode 100644 index 51e65f59..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemUpdateViewModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Domain.Base; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemUpdateViewModel : ViewModelBase -{ - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemViewModel.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemViewModel.cs deleted file mode 100644 index c336f745..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemViewModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemViewModel -{ - public Guid Id { get; set; } - - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; - - public string? ThreadId { get; set; } - - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/ProfilesDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/ProfilesDefinition.cs deleted file mode 100644 index 9bbb907e..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/ProfilesDefinition.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Web.Application; -using Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.ProfileEndpoints.Queries; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.OperationResults; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.ProfileEndpoints; - -public class ProfilesDefinition : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("/api/profiles/get-roles", GetRoles); - app.MapPost("/api/profiles/register", RegisterAccount); - } - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("Profiles")] - private async Task GetRoles([FromServices] IMediator mediator, HttpContext context) - => await mediator.Send(new GetRolesRequest(), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [FeatureGroupName("Profiles")] - private async Task> RegisterAccount([FromServices] IMediator mediator, RegisterViewModel model, HttpContext context) - => await mediator.Send(new RegisterAccountRequest(model), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/ProfilesMapperConfiguration.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/ProfilesMapperConfiguration.cs deleted file mode 100644 index 02f90979..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/ProfilesMapperConfiguration.cs +++ /dev/null @@ -1,56 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using System.Security.Claims; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.ProfileEndpoints; - -/// -/// Mapper Configuration for entity ApplicationUser -/// -public class ProfilesMapperConfiguration : Profile -{ - /// - public ProfilesMapperConfiguration() - { - CreateMap() - .ForMember(x => x.UserName, o => o.MapFrom(p => p.Email)) - .ForMember(x => x.Email, o => o.MapFrom(p => p.Email)) - .ForMember(x => x.EmailConfirmed, o => o.MapFrom(src => true)) - .ForMember(x => x.FirstName, o => o.MapFrom(p => p.FirstName)) - .ForMember(x => x.LastName, o => o.MapFrom(p => p.LastName)) - .ForMember(x => x.PhoneNumberConfirmed, o => o.MapFrom(src => true)) - .ForMember(x => x.ApplicationUserProfileId, o => o.Ignore()) - .ForMember(x => x.ApplicationUserProfile, o => o.Ignore()) - .ForMember(x => x.Id, o => o.Ignore()) - .ForMember(x => x.NormalizedUserName, o => o.Ignore()) - .ForMember(x => x.NormalizedEmail, o => o.Ignore()) - .ForMember(x => x.PasswordHash, o => o.Ignore()) - .ForMember(x => x.SecurityStamp, o => o.Ignore()) - .ForMember(x => x.ConcurrencyStamp, o => o.Ignore()) - .ForMember(x => x.PhoneNumber, o => o.Ignore()) - .ForMember(x => x.TwoFactorEnabled, o => o.Ignore()) - .ForMember(x => x.LockoutEnd, o => o.Ignore()) - .ForMember(x => x.LockoutEnabled, o => o.Ignore()) - .ForMember(x => x.AccessFailedCount, o => o.Ignore()); - - CreateMap() - .ForMember(x => x.Id, o => o.Ignore()) - .ForMember(x => x.Permissions, o => o.Ignore()) - .ForMember(x => x.ApplicationUser, o => o.Ignore()) - .ForMember(x => x.CreatedAt, o => o.Ignore()) - .ForMember(x => x.CreatedBy, o => o.Ignore()) - .ForMember(x => x.UpdatedAt, o => o.Ignore()) - .ForMember(x => x.UpdatedBy, o => o.Ignore()); - - CreateMap() - .ForMember(x => x.Id, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.NameIdentifier))) - .ForMember(x => x.PositionName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Actor))) - .ForMember(x => x.FirstName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.GivenName))) - .ForMember(x => x.LastName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Surname))) - .ForMember(x => x.Roles, o => o.MapFrom(claims => ClaimsHelper.GetValues(claims, ClaimTypes.Role))) - .ForMember(x => x.Email, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Name))) - .ForMember(x => x.PhoneNumber, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.MobilePhone))); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/Queries/GetRoles.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/Queries/GetRoles.cs deleted file mode 100644 index 924af3fa..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/Queries/GetRoles.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Calabonga.Microservices.Core; -using MediatR; -using System.Security.Claims; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.ProfileEndpoints.Queries; - -/// -/// Request: Returns user roles -/// -public record GetRolesRequest : IRequest; - -public class GetRolesRequestHandler : RequestHandler -{ - private readonly IHttpContextAccessor _httpContextAccessor; - - public GetRolesRequestHandler(IHttpContextAccessor httpContextAccessor) => _httpContextAccessor = httpContextAccessor; - - protected override string Handle(GetRolesRequest request) - { - var user = _httpContextAccessor.HttpContext!.User; - var roles = ClaimsHelper.GetValues((ClaimsIdentity)user.Identity!, "role"); - return $"Current user ({user.Identity!.Name}) have following roles: {string.Join("|", roles)}"; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/Queries/RegisterAccount.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/Queries/RegisterAccount.cs deleted file mode 100644 index 2e9798e1..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/Queries/RegisterAccount.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Web.Application.Services; -using Calabonga.Microservice.IdentityModule.Web.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.OperationResults; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.ProfileEndpoints.Queries; - -/// -/// Request: Register new account -/// -public class RegisterAccountRequest : IRequest> -{ - public RegisterAccountRequest(RegisterViewModel model) => Model = model; - - public RegisterViewModel Model { get; } -} - -/// -/// Response: Register new account -/// -public class RegisterAccountRequestHandler : IRequestHandler> -{ - private readonly IAccountService _accountService; - - public RegisterAccountRequestHandler(IAccountService accountService) - => _accountService = accountService; - - public Task> Handle(RegisterAccountRequest request, CancellationToken cancellationToken) - => _accountService.RegisterAsync(request.Model, cancellationToken); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/ViewModels/RegisterViewModel.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/ViewModels/RegisterViewModel.cs deleted file mode 100644 index 6ec18ec9..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/ViewModels/RegisterViewModel.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.ProfileEndpoints.ViewModels; - -/// -/// Data transfer object for user registration -/// -public class RegisterViewModel -{ - /// - /// FirstName - /// - [Required] - [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)] - [Display(Name = "First Name")] - public string FirstName { get; set; } = null!; - - /// - /// LastName - /// - [Required] - [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)] - [Display(Name = "Last Name")] - public string LastName { get; set; } = null!; - - /// - /// Email - /// - [Required] - [EmailAddress] - [Display(Name = "Email")] - public string Email { get; set; } = null!; - - /// - /// Password - /// - [Required] - [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] - [DataType(DataType.Password)] - [Display(Name = "Password")] - public string Password { get; set; } = null!; - - /// - /// Password confirmation - /// - [DataType(DataType.Password)] - [Display(Name = "Confirm password")] - [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] - public string ConfirmPassword { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/ViewModels/UserProfileViewModel.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/ViewModels/UserProfileViewModel.cs deleted file mode 100644 index d3032a80..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfileEndpoints/ViewModels/UserProfileViewModel.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.ProfileEndpoints.ViewModels; - -/// -/// Application User Profile -/// -public class UserProfileViewModel -{ - /// - /// Identifier - /// - public Guid Id { get; set; } - - /// - /// FirstName - /// - public string FirstName { get; set; } = null!; - - /// - /// LastName - /// - public string LastName { get; set; } = null!; - - /// - /// Email - /// - public string Email { get; set; } = null!; - - /// - /// User Roles - /// - public List? Roles { get; set; } - - /// - /// User PhoneNumber - /// - public string? PhoneNumber { get; set; } - - /// - /// Position Name - /// - public string? PositionName { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/SecurityEndpoints/AuthorizeEndpoints.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/SecurityEndpoints/AuthorizeEndpoints.cs deleted file mode 100644 index 553a08a5..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/SecurityEndpoints/AuthorizeEndpoints.cs +++ /dev/null @@ -1,158 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Infrastructure; -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Identity; -using OpenIddict.Abstractions; -using OpenIddict.Server.AspNetCore; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.SecurityEndpoints; - -/// -/// Authorize Endpoint for OpenIddict -/// You can test your authorization server with https://oidcdebugger.com/ -/// You can mock your authorization flow with https://oauth.mocklab.io/ -/// -public class AuthorizeEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("~/connect/authorize", AuthorizeAsync).ExcludeFromDescription(); - app.MapPost("~/connect/authorize", AuthorizeAsync).ExcludeFromDescription(); - } - - private async Task AuthorizeAsync( - HttpContext httpContext, - IOpenIddictScopeManager scopeManager, - UserManager userManager, - SignInManager signInManager, - IOpenIddictApplicationManager applicationManager, - IOpenIddictAuthorizationManager authorizationManager) - { - - var request = httpContext.Request; - var iRequest = httpContext.GetOpenIddictServerRequest() ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); - - // Retrieve the user principal stored in the authentication cookie. - var result = await httpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); - - if (!result.Succeeded) - { - return Results.Challenge(new AuthenticationProperties - { - RedirectUri = request.PathBase + request.Path + QueryString.Create(request.HasFormContentType - ? request.Form.ToList() - : request.Query.ToList()) - }, - new List { CookieAuthenticationDefaults.AuthenticationScheme }); - } - - // ATTENTION: If you use are "IN-Memory" mode, then system cannot track user that recreated every time on start. You should clear cookies (site data) in browser. - var user = await userManager.GetUserAsync(result.Principal) ?? throw new InvalidOperationException("The user details cannot be retrieved."); - - var application = await applicationManager.FindByClientIdAsync(iRequest.ClientId!) ?? throw new InvalidOperationException("Details concerning the calling client application cannot be found."); - var applicationId = await applicationManager.GetIdAsync(application); - var userId = await userManager.GetUserIdAsync(user); - - var authorizations = await authorizationManager.FindAsync( - subject: userId, - client: applicationId!, - status: OpenIddictConstants.Statuses.Valid, - type: OpenIddictConstants.AuthorizationTypes.Permanent, - scopes: iRequest.GetScopes()).ToListAsync(); - - switch (await applicationManager.GetConsentTypeAsync(application)) - { - // If the consent is external (e.g when authorizations are granted by a sysadmin), - // immediately return an error if no authorization can be found in the database. - case OpenIddictConstants.ConsentTypes.External when !authorizations.Any(): - return Results.Forbid( - authenticationSchemes: new[] { OpenIddictServerAspNetCoreDefaults.AuthenticationScheme }, - properties: new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = OpenIddictConstants.Errors.ConsentRequired, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "The logged in user is not allowed to access this client application." - }!)); - - // If the consent is implicit or if an authorization was found, - // return an authorization response without displaying the consent form. - case OpenIddictConstants.ConsentTypes.Implicit: - case OpenIddictConstants.ConsentTypes.External when authorizations.Any(): - case OpenIddictConstants.ConsentTypes.Explicit when authorizations.Any() && !iRequest.HasPrompt(OpenIddictConstants.Prompts.Consent): - - var principal = await signInManager.CreateUserPrincipalAsync(user); - - // Note: in this sample, the granted scopes match the requested scope - // but you may want to allow the user to uncheck specific scopes. - // For that, simply restrict the list of scopes before calling SetScopes. - - var sc = iRequest.GetScopes(); - principal.SetScopes(sc); - // principal.SetScopes(iRequest.GetScopes()); - principal.SetResources(await scopeManager.ListResourcesAsync(principal.GetScopes()).ToListAsync()); - - // Automatically create a permanent authorization to avoid requiring explicit consent - // for future authorization or token requests containing the same scopes. - var authorization = authorizations.LastOrDefault(); - if (authorization is null) - { - authorization = await authorizationManager.CreateAsync( - principal: principal, - subject: await userManager.GetUserIdAsync(user), - client: applicationId!, - type: OpenIddictConstants.AuthorizationTypes.Permanent, - scopes: principal.GetScopes()); - } - - principal.SetAuthorizationId(await authorizationManager.GetIdAsync(authorization)); - - foreach (var claim in principal.Claims) - { - claim.SetDestinations(claim.Type switch - { - // If the "profile" scope was granted, allow the "name" claim to be - // added to the access and identity tokens derived from the principal. - OpenIddictConstants.Claims.Name when principal.HasScope(OpenIddictConstants.Scopes.Profile) => new[] - { - OpenIddictConstants.Destinations.AccessToken, - OpenIddictConstants.Destinations.IdentityToken - }, - - // Never add the "secret_value" claim to access or identity tokens. - // In this case, it will only be added to authorization codes, - // refresh tokens and user/device codes, that are always encrypted. - "secret_value" => Array.Empty(), - - // Otherwise, add the claim to the access tokens only. - _ => new[] - { - OpenIddictConstants.Destinations.AccessToken - } - }); - } - - return Results.SignIn(principal, null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - - // At this point, no authorization was found in the database and an error must be returned - // if the client application specified prompt=none in the authorization request. - case OpenIddictConstants.ConsentTypes.Explicit when iRequest.HasPrompt(OpenIddictConstants.Prompts.None): - case OpenIddictConstants.ConsentTypes.Systematic when iRequest.HasPrompt(OpenIddictConstants.Prompts.None): - return Results.Forbid( - authenticationSchemes: new[] { OpenIddictServerAspNetCoreDefaults.AuthenticationScheme }, - properties: new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = OpenIddictConstants.Errors.ConsentRequired, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "Interactive user consent is required." - }!)); - - // In every other case, render the consent form. - default: - return Results.Challenge( - authenticationSchemes: new[] { OpenIddictServerAspNetCoreDefaults.AuthenticationScheme }, - properties: new AuthenticationProperties { RedirectUri = "/" }); - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/SecurityEndpoints/TokenEndpoints.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/SecurityEndpoints/TokenEndpoints.cs deleted file mode 100644 index 64bcab69..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Endpoints/SecurityEndpoints/TokenEndpoints.cs +++ /dev/null @@ -1,101 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.Microservice.IdentityModule.Web.Application.Services; -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Identity; -using OpenIddict.Abstractions; -using OpenIddict.Server.AspNetCore; -using System.Security.Claims; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints.SecurityEndpoints; - -/// -/// Token Endpoint for OpenIddict -/// -public class TokenEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) => - app.MapPost("~/connect/token", TokenAsync).ExcludeFromDescription(); - - private async Task TokenAsync( - HttpContext httpContext, - IOpenIddictScopeManager manager, - UserManager userManager, - SignInManager signInManager, - IAccountService accountService) - { - var request = httpContext.GetOpenIddictServerRequest() ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); - - if (request.IsClientCredentialsGrantType()) - { - var identity = new ClaimsIdentity(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - - // Subject or sub is a required field, we use the client id as the subject identifier here. - identity.AddClaim(OpenIddictConstants.Claims.Subject, request.ClientId!); - identity.AddClaim(OpenIddictConstants.Claims.ClientId, request.ClientId!); - - - // Don't forget to add destination otherwise it won't be added to the access token. - identity.AddClaim(OpenIddictConstants.Claims.Scope, request.Scope!, OpenIddictConstants.Destinations.AccessToken); - identity.AddClaim("nimble", "framework", OpenIddictConstants.Destinations.AccessToken); - - var claimsPrincipal = new ClaimsPrincipal(identity); - - claimsPrincipal.SetScopes(request.GetScopes()); - return Results.SignIn(claimsPrincipal, new AuthenticationProperties(), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - } - - if (request.IsPasswordGrantType()) - { - var user = await userManager.FindByNameAsync(request.Username); - if (user == null) - { - return Results.Problem("Invalid operation"); - } - - // Ensure the user is allowed to sign in - if (!await signInManager.CanSignInAsync(user)) - { - return Results.Problem("Invalid operation"); - } - - - // Ensure the user is not already locked out - if (userManager.SupportsUserLockout && await userManager.IsLockedOutAsync(user)) - { - return Results.Problem("Invalid operation"); - } - - // Ensure the password is valid - if (!await userManager.CheckPasswordAsync(user, request.Password)) - { - if (userManager.SupportsUserLockout) - { - await userManager.AccessFailedAsync(user); - } - - return Results.Problem("Invalid operation"); - } - - // Reset the lockout count - if (userManager.SupportsUserLockout) - { - await userManager.ResetAccessFailedCountAsync(user); - } - - var principal = await accountService.GetPrincipalByEmailAsync(user.Email); - return Results.SignIn(principal, new AuthenticationProperties(), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - } - - if (request.IsAuthorizationCodeGrantType()) - { - var authenticateResult = await httpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - var properties = authenticateResult.Properties; - var claimsPrincipal = authenticateResult.Principal; - return Results.SignIn(claimsPrincipal!, properties ?? new AuthenticationProperties(), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - } - - return Results.Problem("The specified grant type is not supported."); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml.cs deleted file mode 100644 index 98e4bac0..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml.cs +++ /dev/null @@ -1,68 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.Microservice.IdentityModule.Web.Application.Services; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace Calabonga.Microservice.IdentityModule.Web.Pages.Connect; - -public class LoginModel : PageModel -{ - private readonly IAccountService _accountService; - private readonly SignInManager _signInManager; - private readonly UserManager _userManager; - - public LoginModel( - IAccountService accountService, - SignInManager signInManager, - UserManager userManager) - { - _accountService = accountService; - _signInManager = signInManager; - _userManager = userManager; - } - - [BindProperty(SupportsGet = true)] - public string ReturnUrl { get; set; } - - [BindProperty] - public LoginViewModel Input { get; set; } - - public void OnGet() => Input = new LoginViewModel - { - ReturnUrl = ReturnUrl - }; - - public async Task OnPostAsync() - { - if (!ModelState.IsValid) - { - return Page(); - } - - var user = await _userManager.FindByNameAsync(Input.UserName); - if (user == null) - { - ModelState.AddModelError("UserName", "Пользователь не найден"); - return Page(); - } - - var signInResult = await _signInManager.PasswordSignInAsync(user, Input.Password, true, false); - if (signInResult.Succeeded) - { - var principal = await _accountService.GetPrincipalByIdAsync(user.Id.ToString()); - await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); - - if (Url.IsLocalUrl(ReturnUrl)) - { - return Redirect(ReturnUrl); - } - return RedirectToPage("/swagger"); - } - - ModelState.AddModelError("UserName", "Пользователь не найден"); - return Page(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/LoginViewModel.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/LoginViewModel.cs deleted file mode 100644 index da95e730..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/LoginViewModel.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Calabonga.Microservice.IdentityModule.Web.Pages.Connect; - -public class LoginViewModel -{ - - [Required] - [EmailAddress] - [Display(Name = "Имя для входа")] - public string UserName { get; set; } = null!; - - [Required] - [Display(Name = "Пароль")] - public string Password { get; set; } = null!; - - [Required] - public string ReturnUrl { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/Shared/_Layout.cshtml b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/Shared/_Layout.cshtml deleted file mode 100644 index 476c0e72..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/Shared/_Layout.cshtml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - Authorization Server Nimble Framework - - - - -
-
-
- -

- Сервер авторизации -

-

- Version: 6.1.3 -

-
-
-
- @RenderBody() - -
-
-
-

- - Calabonga SOFT 2022 © Nimble Framework -

-
-
-
- - - - \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Program.cs b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Program.cs deleted file mode 100644 index fac47e8b..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Program.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -------------------------------------------------------------------- -// Name: Template for Micro service on ASP.NET Core API with -// OpenIddict (OAuth2.0) -// Author: Calabonga © 2005-2022 Calabonga SOFT -// Version: 6.1.4 -// Based on: .NET 6.0.x -// Created Date: 2019-04-13 3:28:39 PM -// Updated Date: 2022-10-02 11:33:14 AM -// -------------------------------------------------------------------- -// Contacts -// -------------------------------------------------------------------- -// Blog: https://www.calabonga.net -// GitHub: https://github.com/Calabonga -// YouTube: https://youtube.com/sergeicalabonga -// Zen: https://zen.yandex.ru/calabonga -// -------------------------------------------------------------------- -// Description: -// -------------------------------------------------------------------- -// Minimal API for NET6 used. -// This template implements Web API and OpenIddict (OAuth2.0) -// functionality. Also, support two type of Authentication: -// Cookie and Bearer -// -------------------------------------------------------------------- - -using Calabonga.AspNetCore.AppDefinitions; -using Serilog; -using Serilog.Events; - -try -{ - // configure logger (Serilog) - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .Enrich.FromLogContext() - .WriteTo.Console() - .CreateLogger(); - - // created builder - var builder = WebApplication.CreateBuilder(args); - builder.Host.UseSerilog(); - - // adding definitions for application - builder.Services.AddDefinitions(builder, typeof(Program)); - - // create application - var app = builder.Build(); - - // using definition for application - app.UseDefinitions(); - - // start application - app.Run(); - - return 0; -} -catch (Exception ex) -{ - var type = ex.GetType().Name; - if (type.Equals("StopTheHostException", StringComparison.Ordinal)) - { - throw; - } - - Log.Fatal(ex, "Unhandled exception"); - return 1; -} -finally -{ - Log.CloseAndFlush(); -} - - diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json deleted file mode 100644 index 94858a1a..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "Cors": { - "Origins": "*" - }, - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.json b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.json deleted file mode 100644 index 78158c32..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=;User ID=;Password=" - }, - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AuthServer": { - "Url": "https://localhost:10001" - }, - "AllowedHosts": "*" -} diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/readme.md b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/readme.md deleted file mode 100644 index 1086aa6b..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/readme.md +++ /dev/null @@ -1,25 +0,0 @@ -# About - -| Name | Description | -| ------------ | ------------------------------------------ | -| Name | Microservice Template for ASP.NET Core API | -| Author | Calabonga SOFT © 2005-2022 Calabonga SOFT | -| Created Date | 2019-04-13 3:28:39 PM | - -# Versions - -Nimble Framework Templates build on .NET 6.0. That`s why it have the same major version. But the all improvements will increment minor versions. -Current version: 6.1.4 - -# Contacts - -You can contact me by using the next opportunities: - -* Blog: https://www.calabonga.net -* GitHub: https://github.com/Calabonga -* Zen: https://dzen.ru/calabonga -* YouTube: https://youtube.com/sergeicalabonga - -# Description: - -This template implements Web API functionality using minmal API feature from NET 6.0 \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Whatnot/adrs.txt b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Whatnot/adrs.txt deleted file mode 100644 index 7774af4b..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Whatnot/adrs.txt +++ /dev/null @@ -1,7 +0,0 @@ -Architectural Decision Records - -2021-04-08 -Проект .Core переименован в .Domain потому что при построении шаблона были проблемы со сборкой Calabonga.Microservices.Core. - -2022-05-08 -Решение вместе про проектами переименовано Calabonga.Microservice.IdentityModule.* теперь называется Calabonga.AuthService.* по причине того, что слишком длинное название влияет на длину пути в файловой системе. А это налагает некоторые ограничения при сборке и формировании шаблонов. \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Whatnot/thunder-collection_Microservice.json b/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Whatnot/thunder-collection_Microservice.json deleted file mode 100644 index 37a17d21..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Whatnot/thunder-collection_Microservice.json +++ /dev/null @@ -1 +0,0 @@ -{"client":"Thunder Client","collectionName":"Microservice","dateExported":"2021-11-19T03:10:33.651Z","version":"1.1","folders":[{"containerId":"","sortNum":10000,"name":"Logs","_id":"61fd6bb1-5fa1-4b7a-bccf-c54a156f5c93","created":"2021-11-17T03:49:20.622Z"},{"containerId":"","sortNum":20000,"name":"Profiles","_id":"35c9a3f6-742d-4f50-9996-5b77f908a49f","created":"2021-11-18T15:33:27.172Z"}],"requests":[{"containerId":"61fd6bb1-5fa1-4b7a-bccf-c54a156f5c93","sortNum":10000,"headers":[{"name":"Accept","value":"*/*"},{"name":"User-Agent","value":"Thunder Client (https://www.thunderclient.io)"}],"colId":"72b5f27d-1d7c-45e0-9d10-64715fe29249","name":"LogsPost","url":"http://localhost:10001/api/logs","method":"POST","modified":"2021-11-19T02:13:46.413Z","created":"2021-11-17T09:43:34.339Z","_id":"0cb85d14-91a7-40bc-b0a8-54b0e1292dd8","params":[],"body":{"type":"json","raw":"{\n \"createdAt\": \"2021-11-17T09:44:11.479Z\",\n \"logger\": \"Visual Studio Code\",\n \"level\": \"Information\",\n \"message\": \"string\",\n \"threadId\": \"string\",\n \"exceptionMessage\": \"string\"\n}","form":[]},"auth":{"type":"inherit"},"tests":[{"type":"res-code","custom":"","action":"equal","value":"200"},{"type":"res-body","custom":"","action":"contains","value":"Successfully created"},{"type":"Content-Type","custom":"","action":"equal","value":"application/json; charset=utf-8"}]},{"containerId":"61fd6bb1-5fa1-4b7a-bccf-c54a156f5c93","sortNum":20000,"headers":[{"name":"Accept","value":"*/*"},{"name":"User-Agent","value":"Thunder Client (https://www.thunderclient.io)"}],"colId":"72b5f27d-1d7c-45e0-9d10-64715fe29249","name":"LogsPaged","url":"http://localhost:10001/api/logs/paged?pageIndex=0&pageSize=10","method":"GET","modified":"2021-11-19T02:13:37.136Z","created":"2021-11-17T03:49:46.694Z","_id":"2f72ce84-1fe0-4d35-888f-4a413523deb9","params":[{"name":"pageIndex","value":"0","isPath":false},{"name":"pageSize","value":"10","isPath":false}],"auth":{"type":"inherit"},"tests":[{"type":"res-code","custom":"","action":"equal","value":"200"},{"type":"res-body","custom":"","action":"contains","value":"items"}]},{"containerId":"61fd6bb1-5fa1-4b7a-bccf-c54a156f5c93","sortNum":40000,"headers":[{"name":"Accept","value":"*/*"},{"name":"User-Agent","value":"Thunder Client (https://www.thunderclient.io)"}],"colId":"72b5f27d-1d7c-45e0-9d10-64715fe29249","name":"LogsGetById","url":"http://localhost:10001/api/logs/1467a5b9-e61f-82b0-425b-7ec75f5c5029","method":"GET","modified":"2021-11-19T02:13:55.799Z","created":"2021-11-17T06:43:34.773Z","_id":"ffe9773e-bf25-4d3f-8b28-86b258b64552","params":[],"auth":{"type":"inherit"},"tests":[{"type":"res-code","custom":"","action":"equal","value":"200"},{"type":"res-body","custom":"","action":"contains","value":"1467a5b9-e61f-82b0-425b-7ec75f5c5029"}]},{"containerId":"61fd6bb1-5fa1-4b7a-bccf-c54a156f5c93","sortNum":47500,"headers":[{"name":"Accept","value":"*/*"},{"name":"User-Agent","value":"Thunder Client (https://www.thunderclient.io)"}],"colId":"72b5f27d-1d7c-45e0-9d10-64715fe29249","name":"LogsUpdateById","url":"http://localhost:10001/api/logs/1467a5b9-e61f-82b0-425b-7ec75f5c5029","method":"PUT","modified":"2021-11-19T02:14:07.389Z","created":"2021-11-18T14:37:37.031Z","_id":"4bbf399f-dbfb-4fe8-aef0-4e0b8a310148","params":[],"body":{"type":"json","raw":"{\n \"id\": \"1467a5b9-e61f-82b0-425b-7ec75f5c5029\",\n \"logger\": \"Update\",\n \"level\": \"Updated\",\n \"message\": \"string\"\n}","form":[]},"auth":{"type":"inherit"},"tests":[{"type":"res-code","custom":"","action":"equal","value":"200"},{"type":"res-body","custom":"","action":"contains","value":"Successfully updated"}]},{"containerId":"35c9a3f6-742d-4f50-9996-5b77f908a49f","sortNum":60000,"headers":[{"name":"Accept","value":"*/*"},{"name":"User-Agent","value":"Thunder Client (https://www.thunderclient.io)"}],"colId":"72b5f27d-1d7c-45e0-9d10-64715fe29249","name":"RegisterProfile (400 email wrong)","url":"http://localhost:10001/api/profiles/register","method":"POST","modified":"2021-11-19T03:05:00.567Z","created":"2021-11-18T15:33:39.871Z","_id":"42715a0d-e086-4ec0-a763-2dc69037d919","params":[],"body":{"type":"json","raw":"{\n \"firstName\": \"Евлампий\",\n \"lastName\": \"Суходрищев\",\n \"email\": \"userexample.com\",\n \"password\": \"123qwe!@#\",\n \"confirmPassword\": \"123qwe!@#\"\n}","form":[]},"tests":[{"type":"res-code","custom":"","action":"equal","value":"400"},{"type":"res-body","custom":"","action":"contains","value":"Model.Email"}]},{"containerId":"61fd6bb1-5fa1-4b7a-bccf-c54a156f5c93","sortNum":60000,"headers":[{"name":"Accept","value":"*/*"},{"name":"User-Agent","value":"Thunder Client (https://www.thunderclient.io)"}],"colId":"72b5f27d-1d7c-45e0-9d10-64715fe29249","name":"LogsDeleteById","url":"http://localhost:10001/api/logs/1467a5b9-e61f-82b0-425b-7ec75f5c5029","method":"DELETE","modified":"2021-11-19T02:16:11.807Z","created":"2021-11-18T14:35:20.115Z","_id":"774ec485-0406-4332-8e51-d49c9a2c31ab","params":[],"auth":{"type":"inherit"},"tests":[{"type":"res-code","custom":"","action":"equal","value":"200"}]},{"containerId":"35c9a3f6-742d-4f50-9996-5b77f908a49f","sortNum":65000,"headers":[{"name":"Accept","value":"*/*"},{"name":"User-Agent","value":"Thunder Client (https://www.thunderclient.io)"}],"colId":"72b5f27d-1d7c-45e0-9d10-64715fe29249","name":"RegisterProfile (400 email null)","url":"http://localhost:10001/api/profiles/register","method":"POST","modified":"2021-11-19T03:09:43.695Z","created":"2021-11-19T03:05:16.489Z","_id":"cdb6ed6b-a690-4ea3-ae80-607b81dcdb77","params":[],"body":{"type":"json","raw":"{\n \"firstName\": \"Евлампий\",\n \"lastName\": \"Суходрищев\",\n \"email\": \"email@example.com\",\n \"password\": \"123qwe!@#\",\n \"confirmPassword\": \"123qwe!@#\"\n}","form":[]},"tests":[{"type":"res-code","custom":"","action":"equal","value":"200"},{"type":"res-body","custom":"","action":"contains","value":"User successfully registered"}]},{"containerId":"35c9a3f6-742d-4f50-9996-5b77f908a49f","sortNum":67500,"headers":[{"name":"Accept","value":"*/*"},{"name":"User-Agent","value":"Thunder Client (https://www.thunderclient.io)"}],"colId":"72b5f27d-1d7c-45e0-9d10-64715fe29249","name":"RegisterProfile","url":"http://localhost:10001/api/profiles/register","method":"POST","modified":"2021-11-19T03:06:59.962Z","created":"2021-11-19T03:06:59.962Z","_id":"a6a5d20e-75c8-42ec-bfa5-57c07d96407a","params":[],"body":{"type":"json","raw":"{\n \"firstName\": \"Евлампий\",\n \"lastName\": \"Суходрищев\",\n \"password\": \"123qwe!@#\",\n \"confirmPassword\": \"123qwe!@#\"\n}","form":[]},"tests":[{"type":"res-code","custom":"","action":"equal","value":"400"},{"type":"res-body","custom":"","action":"contains","value":"Model.Email"}]},{"containerId":"35c9a3f6-742d-4f50-9996-5b77f908a49f","sortNum":70000,"headers":[{"name":"Accept","value":"*/*"},{"name":"User-Agent","value":"Thunder Client (https://www.thunderclient.io)"}],"colId":"72b5f27d-1d7c-45e0-9d10-64715fe29249","name":"ProfilesGetRoles","url":"http://localhost:10001/api/profiles/get-roles","method":"GET","modified":"2021-11-19T02:16:37.301Z","created":"2021-11-18T15:43:10.579Z","_id":"cc3d9676-dfb9-45e6-b1c2-2e264b64d489","params":[],"auth":{"type":"inherit"},"tests":[{"type":"res-code","custom":"","action":"equal","value":"200"},{"type":"res-body","custom":"","action":"contains","value":"Administrator|Manager"}]}],"settings":{"headers":[],"auth":{"type":"oauth2","oauth2":{"accessToken":"eyJhbGciOiJSUzI1NiIsImtpZCI6IjcyRjRFN0Y4RDE5RjE3QzBGQzQ3RDdDRjFGQkY2MURGIiwidHlwIjoiYXQrand0In0.eyJuYmYiOjE2MzcyODc5MTQsImV4cCI6MTYzNzMwOTUxNCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDoxMDAwMSIsImNsaWVudF9pZCI6Im1pY3Jvc2VydmljZTEiLCJzdWIiOiJiMDY2NDVmMC0xYTAxLTQ2NjctYjk2Yy1mZTcyN2E2ZjA1YjgiLCJhdXRoX3RpbWUiOjE2MzcyODc5MTMsImlkcCI6ImxvY2FsIiwibmFtZSI6Im1pY3Jvc2VydmljZUB5b3BtYWlsLmNvbSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL2VtYWlsYWRkcmVzcyI6Im1pY3Jvc2VydmljZUB5b3BtYWlsLmNvbSIsIkFzcE5ldC5JZGVudGl0eS5TZWN1cml0eVN0YW1wIjoiZTljMDNhZWMtMGU3Yy00OGM5LThjNmItZmNlYmYxZDljYjg4Iiwicm9sZSI6WyJBZG1pbmlzdHJhdG9yIiwiTWFuYWdlciJdLCJMb2dzOlVzZXJSb2xlczpWaWV3Ijoicm9sZSIsImdpdmVuX25hbWUiOiJNaWNyb3NlcnZpY2UiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zdXJuYW1lIjoiQWRtaW5pc3RyYXRvciIsImp0aSI6IjhFNEE4RTA4MUIwQjMxODNFMkJDRDkwOUNBMDI5M0FBIiwiaWF0IjoxNjM3Mjg3OTE0LCJzY29wZSI6WyJhcGkxIl0sImFtciI6WyJwd2QiXX0.k_iICPJE9cLP-7jegmP6uqh-2_9-iD3g3pPYvdBK-GE_dUHQyBEkYOJ1UDDtjCkYciw9jCGly_e2MK5J4V7X2xSkU5lIlj012QjDXU_8PIu4z36Z_axPtUwu-LMtjmx4YG98W_zi-SiLe4I5XMhnM7Cod9qZjdfmUMsXkVCKhXkeYA7Bj4SKhIyGRgF06XNHRSQHzWex4_XYJznoYV64mqw7MvUhDcrrHcrOcB8MEWdDhYb52kyzthK7boYfxRkgkEnKEqU25xomz_IWLZ2u0Ifko-7gNAv3Kszi12YGjlhDnBDNN1fFEcTvQUMndR8NoXp5WJWK7eDxkyLa60w0Bg","grantType":"password","callbackUrl":"https://www.thunderclient.io/oauth/callback","authUrl":"","tokenUrl":"{{AuthorizeUrl}}","clientId":"{{client_id}}","clientSecret":"{{client_secret}}","scope":"{{scope}}","state":"","username":"{{username}}","password":"{{password}}","clientAuth":"in-header"}},"tests":[],"envId":"12966272-8e1b-44c6-8c72-9afbe857b69d"}} diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/.editorconfig b/AspNetCore v6.0/Calabonga.Microservice.Module/.editorconfig deleted file mode 100644 index ad6bdfaf..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/.editorconfig +++ /dev/null @@ -1,228 +0,0 @@ -root = true -# Remove the line below if you want to inherit .editorconfig settings from higher directories - -# C# files -[*.cs] - -#### Core EditorConfig Options #### -charset = utf-8-bom - -# Indentation and spacing -indent_size = 4 -indent_style = space -tab_width = 4 - -# New line preferences -end_of_line = crlf -insert_final_newline = false - -#### .NET Coding Conventions #### - -# Organize usings -dotnet_separate_import_directive_groups = false -dotnet_sort_system_directives_first = false - -# this. and Me. preferences -dotnet_style_qualification_for_event = false:suggestion -dotnet_style_qualification_for_field = false -dotnet_style_qualification_for_method = false:suggestion -dotnet_style_qualification_for_property = false:suggestion - -# Language keywords vs BCL types preferences -dotnet_style_predefined_type_for_locals_parameters_members = true -dotnet_style_predefined_type_for_member_access = true - -# Parentheses preferences -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_operators = never_if_unnecessary -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity - -# Modifier preferences -dotnet_style_require_accessibility_modifiers = for_non_interface_members - -# Expression-level preferences -dotnet_style_coalesce_expression = true -dotnet_style_collection_initializer = true -dotnet_style_explicit_tuple_names = true -dotnet_style_null_propagation = true -dotnet_style_object_initializer = true -dotnet_style_operator_placement_when_wrapping = beginning_of_line -dotnet_style_prefer_auto_properties = true:error -dotnet_style_prefer_compound_assignment = true -dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion -dotnet_style_prefer_conditional_expression_over_return = true:suggestion -dotnet_style_prefer_inferred_anonymous_type_member_names = true:error -dotnet_style_prefer_inferred_tuple_names = true -dotnet_style_prefer_is_null_check_over_reference_equality_method = true -dotnet_style_prefer_simplified_boolean_expressions = true -dotnet_style_prefer_simplified_interpolation = true - -# Field preferences -dotnet_style_readonly_field = true:error - -# Parameter preferences -dotnet_code_quality_unused_parameters = all - -# Suppression preferences -dotnet_remove_unnecessary_suppression_exclusions = none - -#### C# Coding Conventions #### - -# var preferences -csharp_style_var_elsewhere = true:suggestion -csharp_style_var_for_built_in_types = true:suggestion -csharp_style_var_when_type_is_apparent = true:suggestion - -# Expression-bodied members -csharp_style_expression_bodied_accessors = true:suggestion -csharp_style_expression_bodied_constructors = true:suggestion -csharp_style_expression_bodied_indexers = true:suggestion -csharp_style_expression_bodied_lambdas = true -csharp_style_expression_bodied_local_functions = false -csharp_style_expression_bodied_methods = true:suggestion -csharp_style_expression_bodied_operators = true:suggestion -csharp_style_expression_bodied_properties = true:suggestion - -# Pattern matching preferences -csharp_style_pattern_matching_over_as_with_null_check = true -csharp_style_pattern_matching_over_is_with_cast_check = true -csharp_style_prefer_not_pattern = true -csharp_style_prefer_pattern_matching = true -csharp_style_prefer_switch_expression = true - -# Null-checking preferences -csharp_style_conditional_delegate_call = true - -# Modifier preferences -csharp_prefer_static_local_function = true -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async - -# Code-block preferences -csharp_prefer_braces = true:error -csharp_prefer_simple_using_statement = true - -# Expression-level preferences -csharp_prefer_simple_default_expression = true -csharp_style_deconstructed_variable_declaration = true -csharp_style_implicit_object_creation_when_type_is_apparent = true -csharp_style_inlined_variable_declaration = true -csharp_style_pattern_local_over_anonymous_function = true -csharp_style_prefer_index_operator = true -csharp_style_prefer_range_operator = true -csharp_style_throw_expression = true -csharp_style_unused_value_assignment_preference = discard_variable -csharp_style_unused_value_expression_statement_preference = discard_variable - -# 'using' directive preferences -csharp_using_directive_placement = outside_namespace - -#### C# Formatting Rules #### - -# New line preferences -csharp_new_line_before_catch = true -csharp_new_line_before_else = true -csharp_new_line_before_finally = true -csharp_new_line_before_members_in_anonymous_types = true -csharp_new_line_before_members_in_object_initializers = true -csharp_new_line_before_open_brace = all -csharp_new_line_between_query_expression_clauses = true - -# Indentation preferences -csharp_indent_block_contents = true -csharp_indent_braces = false -csharp_indent_case_contents = true -csharp_indent_case_contents_when_block = true -csharp_indent_labels = no_change -csharp_indent_switch_labels = true - -# Space preferences -csharp_space_after_cast = false -csharp_space_after_colon_in_inheritance_clause = true -csharp_space_after_comma = true -csharp_space_after_dot = false -csharp_space_after_keywords_in_control_flow_statements = true -csharp_space_after_semicolon_in_for_statement = true -csharp_space_around_binary_operators = before_and_after -csharp_space_around_declaration_statements = false -csharp_space_before_colon_in_inheritance_clause = true -csharp_space_before_comma = false -csharp_space_before_dot = false -csharp_space_before_open_square_brackets = false -csharp_space_before_semicolon_in_for_statement = false -csharp_space_between_empty_square_brackets = false -csharp_space_between_method_call_empty_parameter_list_parentheses = false -csharp_space_between_method_call_name_and_opening_parenthesis = false -csharp_space_between_method_call_parameter_list_parentheses = false -csharp_space_between_method_declaration_empty_parameter_list_parentheses = false -csharp_space_between_method_declaration_name_and_open_parenthesis = false -csharp_space_between_method_declaration_parameter_list_parentheses = false -csharp_space_between_parentheses = false -csharp_space_between_square_brackets = false - -# Wrapping preferences -csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true - -#### Naming styles #### - -# Naming rules - -dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion -dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface -dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i - -dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.types_should_be_pascal_case.symbols = types -dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case - -dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members -dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case - -# Symbol specifications - -dotnet_naming_symbols.interface.applicable_kinds = interface -dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interface.required_modifiers = - -dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum -dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types.required_modifiers = - -dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method -dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.non_field_members.required_modifiers = - -# Naming styles - -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = -dotnet_naming_style.pascal_case.capitalization = pascal_case - -dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = -dotnet_naming_style.begins_with_i.capitalization = pascal_case - -# Instance fields are camelCase and start with _ -dotnet_naming_rule.instance_fields_should_be_camel_case.severity = hint -dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields -dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style - -dotnet_naming_symbols.instance_fields.applicable_kinds = field - -dotnet_naming_style.instance_field_style.capitalization = camel_case -dotnet_naming_style.instance_field_style.required_prefix = _ - -# ReSharper properties -max_line_length = 200 -resharper_csharp_max_line_length = 200 -resharper_csharp_wrap_after_declaration_lpar = true -resharper_csharp_wrap_extends_list_style = chop_if_long -resharper_csharp_wrap_lines = false -resharper_max_attribute_length_for_same_line = 300 -resharper_place_type_constraints_on_same_line = true -resharper_wrap_before_arrow_with_expressions = true -resharper_wrap_before_extends_colon = false \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/.template.config/template.json b/AspNetCore v6.0/Calabonga.Microservice.Module/.template.config/template.json deleted file mode 100644 index 8eaaa766..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/.template.config/template.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/template", - "author": "Calabonga SOFT", - "classifications": [ - "Web", - "API", - "Backend", - "Microservice" - ], - "name": "Calabonga.Microservice.Module v6.1.0", - "description": "Nimble Microservice Framework. This template gives you a possibility to start developing a microservice architecture with integrated UI (Swagger), Mediatr, Automapper. Template developed for .NET 6.0.x.", - "identity": "Calabonga.Microservice.Module", - "sourceName": "Calabonga.Microservice.Module", - "shortName": "nimbleminm", - "tags": { - "language": "C#", - "type": "project" - }, - "preferNameDirectory": true, - "symbols": { - "Framework": { - "type": "parameter", - "description": "The target framework for the project.", - "datatype": "choice", - "choices": [ - { - "choice": "net6.0" - } - ], - "defaultValue": "net6.0" - } - }, - "sources": [ - { - "modifiers": [ - { - "exclude": [ - ".vs/**", - ".idea/**", - "_ReSharper.Caches/**", - ".template_config/**" - ] - } - ] - } - ] -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/AppData.Exceptions.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/AppData.Exceptions.cs deleted file mode 100644 index ea15c31f..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/AppData.Exceptions.cs +++ /dev/null @@ -1,61 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain.Base -{ - public static partial class AppData - { - /// - /// Exception messages - /// - public static class Exceptions - { - /// - /// "An exception was thrown" - /// - public static string ThrownException => "An exception was thrown"; - - /// - /// "Invalid cast exception" - /// - public static string TypeConverterException => "Invalid cast exception"; - - /// - /// "User not registered in the system" - /// - public static string UserNotFoundException => "User not registered in the system"; - - /// - /// "Object not found" - /// - public static string NotFoundException => "Object not found"; - - /// - /// "Unauthorized access denied" - /// - public static string UnauthorizedException => "Unauthorized access denied"; - - /// - /// "Argument null exception" - /// - public static string ArgumentNullException => "Argument null exception"; - - /// - /// "File already exists" - /// - public static string FileAlreadyExists => "File already exists"; - - /// - /// "Some errors occurred while checking the entity" - /// - public static string EntityValidationException => "Some errors occurred while checking the entity"; - - /// - /// "Invalid operation exception was thrown" - /// - public static string InvalidOperationException => "Invalid operation exception was thrown"; - - /// - /// "Argument out of range" - /// - public static string ArgumentOutOfRangeException => "Argument out of range"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/Auditable.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/Auditable.cs deleted file mode 100644 index c0142005..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/Auditable.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain.Base -{ - /// - /// Represents 'Audit-able' table from the Property Database - /// - public abstract class Auditable : Identity, IAuditable - { - /// - /// DateTime when entity created. - /// It's never changed - /// - public DateTime CreatedAt { get; set; } - - /// - /// User name who created entity. - /// It's never changed - /// - public string CreatedBy { get; set; } - - /// - /// Last date entity updated - /// - public DateTime? UpdatedAt { get; set; } - - /// - /// Author of last updated - /// - public string UpdatedBy { get; set; } - - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/IAuditable.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/IAuditable.cs deleted file mode 100644 index 57172119..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/IAuditable.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain.Base -{ - /// - /// Represent information about creation and last update - /// - public interface IAuditable - { - /// - /// DateTime of creation. This value will never changed - /// - DateTime CreatedAt { get; set; } - - /// - /// Author name. This value never changed - /// - string CreatedBy { get; set; } - - /// - /// DateTime of last value update. Should be updated when entity data updated - /// - DateTime? UpdatedAt { get; set; } - - /// - /// Author of last value update. Should be updated when entity data updated - /// - string UpdatedBy { get; set; } - - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/NamedAuditable.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/NamedAuditable.cs deleted file mode 100644 index 807c9717..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/NamedAuditable.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain.Base -{ - /// - /// Audit-able with name - /// - public abstract class NamedAuditable : Auditable - { - public string Name { get; set; } - - public string Description { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/NamedIdentity.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/NamedIdentity.cs deleted file mode 100644 index e6f066e4..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/NamedIdentity.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain.Base -{ - /// - /// NamedIdentity dictionary for selector - /// - public abstract class NamedIdentity : Identity - { - /// - /// Entity name - /// - public string Name { get; set; } - - /// - /// Entity brief name - /// - public string BriefName { get; set; } - - /// - /// Brief descriptions - /// - public string Description { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj deleted file mode 100644 index 27ac3865..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - - net6.0 - enable - enable - - - diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationUser.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationUser.cs deleted file mode 100644 index 0c5a52b3..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationUser.cs +++ /dev/null @@ -1,30 +0,0 @@ - -namespace Calabonga.Microservice.Module.Infrastructure -{ - /// - /// Default user for application. - /// Add profile data for application users by adding properties to the ApplicationUser class - /// - public class ApplicationUser : IdentityUser - { - /// - /// FirstName - /// - public string FirstName { get; set; } - - /// - /// LastName - /// - public string LastName { get; set; } - - /// - /// Profile identity - /// - public Guid? ApplicationUserProfileId { get; set; } - - /// - /// User Profile - /// - public virtual ApplicationUserProfile ApplicationUserProfile { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationUserProfile.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationUserProfile.cs deleted file mode 100644 index 70734db5..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationUserProfile.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Calabonga.Microservice.Module.Infrastructure -{ - /// - /// Represent person with login information (ApplicationUser) - /// - public class ApplicationUserProfile : Auditable - { - /// - /// Account - /// - public virtual ApplicationUser ApplicationUser { get; set; } - - /// - /// Microservice permission for policy-based authorization - /// - public ICollection Permissions { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationUserStore.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationUserStore.cs deleted file mode 100644 index 056f7645..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationUserStore.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; - -namespace Calabonga.Microservice.Module.Infrastructure -{ - /// - /// Application store for user - /// - public class ApplicationUserStore : UserStore - { - public ApplicationUserStore(ApplicationDbContext context, IdentityErrorDescriber describer = null) - : base(context, describer) - { - - } - - /// - public override Task FindByIdAsync(string userId, CancellationToken cancellationToken = new CancellationToken()) - { - return Users - .Include(x => x.ApplicationUserProfile) - .ThenInclude(x => x.Permissions) - .FirstOrDefaultAsync(u => u.Id.ToString() == userId, cancellationToken: cancellationToken); - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/Base/DbContextBase.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/Base/DbContextBase.cs deleted file mode 100644 index 59d164f3..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/Base/DbContextBase.cs +++ /dev/null @@ -1,258 +0,0 @@ -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; -using System.Reflection; - -namespace Calabonga.Microservice.Module.Infrastructure.Base -{ - /// - /// Base DbContext with predefined configuration - /// - public abstract class - DbContextBase : IdentityDbContext - { - private const string DefaultUserName = "Anonymous"; - - protected DbContextBase(DbContextOptions options) : base(options) - { - LastSaveChangesResult = new SaveChangesResult(); - } - - public SaveChangesResult LastSaveChangesResult { get; } - - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - /// - /// Saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// The number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override int SaveChanges(bool acceptAllChangesOnSuccess) - { - try - { - DbSaveChanges(); - return base.SaveChanges(acceptAllChangesOnSuccess); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - public override int SaveChanges() - { - try - { - DbSaveChanges(); - return base.SaveChanges(); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - private void DbSaveChanges() - { - var createdEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added); - foreach (var entry in createdEntries) - { - if (!(entry.Entity is IAuditable)) - { - continue; - } - - var creationDate = DateTime.Now.ToUniversalTime(); - var userName = entry.Property("CreatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("CreatedBy").CurrentValue; - var updatedAt = entry.Property("UpdatedAt").CurrentValue; - var createdAt = entry.Property("CreatedAt").CurrentValue; - if (createdAt != null) - { - if (DateTime.Parse(createdAt.ToString()).Year > 1970) - { - entry.Property("CreatedAt").CurrentValue = ((DateTime)createdAt).ToUniversalTime(); - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - - if (updatedAt != null) - { - if (DateTime.Parse(updatedAt.ToString()).Year > 1970) - { - entry.Property("UpdatedAt").CurrentValue = ((DateTime)updatedAt).ToUniversalTime(); - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - - entry.Property("CreatedBy").CurrentValue = userName; - entry.Property("UpdatedBy").CurrentValue = userName; - - LastSaveChangesResult.AddMessage($"ChangeTracker has new entities: {entry.Entity.GetType()}"); - } - - var updatedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified); - foreach (var entry in updatedEntries) - { - if (entry.Entity is IAuditable) - { - var userName = entry.Property("UpdatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("UpdatedBy").CurrentValue; - entry.Property("UpdatedAt").CurrentValue = DateTime.Now.ToUniversalTime(); - entry.Property("UpdatedBy").CurrentValue = userName; - } - - LastSaveChangesResult.AddMessage($"ChangeTracker has modified entities: {entry.Entity.GetType()}"); - } - } - - /// - /// Configures the schema needed for the identity framework. - /// - /// - /// The builder being used to construct the model for this context. - /// - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - var applyGenericMethod = typeof(ModelBuilder).GetMethods(BindingFlags.Instance | BindingFlags.Public).First(x => x.Name == "ApplyConfiguration"); - foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters)) - { - foreach (var item in type.GetInterfaces()) - { - if (!item.IsConstructedGenericType || item.GetGenericTypeDefinition() != typeof(IEntityTypeConfiguration<>)) - { - continue; - } - - var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(item.GenericTypeArguments[0]); - applyConcreteMethod.Invoke(builder, new[] { Activator.CreateInstance(type) }); - break; - } - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj deleted file mode 100644 index f930cd23..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - - - - - - - - - - - - diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs deleted file mode 100644 index 745a2e6e..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace Calabonga.Microservice.Module.Infrastructure.DatabaseInitialization -{ - /// - /// Database Initializer - /// - public static class DatabaseInitializer - { - public static async void Seed(IServiceProvider serviceProvider) - { - using var scope = serviceProvider.CreateScope(); - await using var context = scope.ServiceProvider.GetService(); - - // It should be uncomment when using UseSqlServer() settings or any other providers. - // This is should not be used when UseInMemoryDatabase() - // await context!.Database.MigrateAsync(); - - await context!.EventItems.AddAsync(new EventItem - { - CreatedAt = DateTime.UtcNow, - Id = Guid.Parse("1467a5b9-e61f-82b0-425b-7ec75f5c5029"), - Level = "Information", - Logger = "SEED", - Message = "Seed method some entities successfully save to ApplicationDbContext" - }); - - await context.SaveChangesAsync(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/MicroservicePermission.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/MicroservicePermission.cs deleted file mode 100644 index 494d2deb..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/MicroservicePermission.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace Calabonga.Microservice.Module.Infrastructure -{ - /// - /// User permission for microservice - /// - public class MicroservicePermission : Auditable - { - /// - /// Application User profile identifier - /// - public Guid ApplicationUserProfileId { get; set; } - - /// - /// Application User Profile - /// - public virtual ApplicationUserProfile ApplicationUserProfile { get; set; } - - /// - /// Authorize attribute policy name - /// - public string PolicyName { get; set; } - - /// - /// Description for current permission - /// - public string Description { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/.editorconfig b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/.editorconfig deleted file mode 100644 index ad6bdfaf..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/.editorconfig +++ /dev/null @@ -1,228 +0,0 @@ -root = true -# Remove the line below if you want to inherit .editorconfig settings from higher directories - -# C# files -[*.cs] - -#### Core EditorConfig Options #### -charset = utf-8-bom - -# Indentation and spacing -indent_size = 4 -indent_style = space -tab_width = 4 - -# New line preferences -end_of_line = crlf -insert_final_newline = false - -#### .NET Coding Conventions #### - -# Organize usings -dotnet_separate_import_directive_groups = false -dotnet_sort_system_directives_first = false - -# this. and Me. preferences -dotnet_style_qualification_for_event = false:suggestion -dotnet_style_qualification_for_field = false -dotnet_style_qualification_for_method = false:suggestion -dotnet_style_qualification_for_property = false:suggestion - -# Language keywords vs BCL types preferences -dotnet_style_predefined_type_for_locals_parameters_members = true -dotnet_style_predefined_type_for_member_access = true - -# Parentheses preferences -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_operators = never_if_unnecessary -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity - -# Modifier preferences -dotnet_style_require_accessibility_modifiers = for_non_interface_members - -# Expression-level preferences -dotnet_style_coalesce_expression = true -dotnet_style_collection_initializer = true -dotnet_style_explicit_tuple_names = true -dotnet_style_null_propagation = true -dotnet_style_object_initializer = true -dotnet_style_operator_placement_when_wrapping = beginning_of_line -dotnet_style_prefer_auto_properties = true:error -dotnet_style_prefer_compound_assignment = true -dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion -dotnet_style_prefer_conditional_expression_over_return = true:suggestion -dotnet_style_prefer_inferred_anonymous_type_member_names = true:error -dotnet_style_prefer_inferred_tuple_names = true -dotnet_style_prefer_is_null_check_over_reference_equality_method = true -dotnet_style_prefer_simplified_boolean_expressions = true -dotnet_style_prefer_simplified_interpolation = true - -# Field preferences -dotnet_style_readonly_field = true:error - -# Parameter preferences -dotnet_code_quality_unused_parameters = all - -# Suppression preferences -dotnet_remove_unnecessary_suppression_exclusions = none - -#### C# Coding Conventions #### - -# var preferences -csharp_style_var_elsewhere = true:suggestion -csharp_style_var_for_built_in_types = true:suggestion -csharp_style_var_when_type_is_apparent = true:suggestion - -# Expression-bodied members -csharp_style_expression_bodied_accessors = true:suggestion -csharp_style_expression_bodied_constructors = true:suggestion -csharp_style_expression_bodied_indexers = true:suggestion -csharp_style_expression_bodied_lambdas = true -csharp_style_expression_bodied_local_functions = false -csharp_style_expression_bodied_methods = true:suggestion -csharp_style_expression_bodied_operators = true:suggestion -csharp_style_expression_bodied_properties = true:suggestion - -# Pattern matching preferences -csharp_style_pattern_matching_over_as_with_null_check = true -csharp_style_pattern_matching_over_is_with_cast_check = true -csharp_style_prefer_not_pattern = true -csharp_style_prefer_pattern_matching = true -csharp_style_prefer_switch_expression = true - -# Null-checking preferences -csharp_style_conditional_delegate_call = true - -# Modifier preferences -csharp_prefer_static_local_function = true -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async - -# Code-block preferences -csharp_prefer_braces = true:error -csharp_prefer_simple_using_statement = true - -# Expression-level preferences -csharp_prefer_simple_default_expression = true -csharp_style_deconstructed_variable_declaration = true -csharp_style_implicit_object_creation_when_type_is_apparent = true -csharp_style_inlined_variable_declaration = true -csharp_style_pattern_local_over_anonymous_function = true -csharp_style_prefer_index_operator = true -csharp_style_prefer_range_operator = true -csharp_style_throw_expression = true -csharp_style_unused_value_assignment_preference = discard_variable -csharp_style_unused_value_expression_statement_preference = discard_variable - -# 'using' directive preferences -csharp_using_directive_placement = outside_namespace - -#### C# Formatting Rules #### - -# New line preferences -csharp_new_line_before_catch = true -csharp_new_line_before_else = true -csharp_new_line_before_finally = true -csharp_new_line_before_members_in_anonymous_types = true -csharp_new_line_before_members_in_object_initializers = true -csharp_new_line_before_open_brace = all -csharp_new_line_between_query_expression_clauses = true - -# Indentation preferences -csharp_indent_block_contents = true -csharp_indent_braces = false -csharp_indent_case_contents = true -csharp_indent_case_contents_when_block = true -csharp_indent_labels = no_change -csharp_indent_switch_labels = true - -# Space preferences -csharp_space_after_cast = false -csharp_space_after_colon_in_inheritance_clause = true -csharp_space_after_comma = true -csharp_space_after_dot = false -csharp_space_after_keywords_in_control_flow_statements = true -csharp_space_after_semicolon_in_for_statement = true -csharp_space_around_binary_operators = before_and_after -csharp_space_around_declaration_statements = false -csharp_space_before_colon_in_inheritance_clause = true -csharp_space_before_comma = false -csharp_space_before_dot = false -csharp_space_before_open_square_brackets = false -csharp_space_before_semicolon_in_for_statement = false -csharp_space_between_empty_square_brackets = false -csharp_space_between_method_call_empty_parameter_list_parentheses = false -csharp_space_between_method_call_name_and_opening_parenthesis = false -csharp_space_between_method_call_parameter_list_parentheses = false -csharp_space_between_method_declaration_empty_parameter_list_parentheses = false -csharp_space_between_method_declaration_name_and_open_parenthesis = false -csharp_space_between_method_declaration_parameter_list_parentheses = false -csharp_space_between_parentheses = false -csharp_space_between_square_brackets = false - -# Wrapping preferences -csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true - -#### Naming styles #### - -# Naming rules - -dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion -dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface -dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i - -dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.types_should_be_pascal_case.symbols = types -dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case - -dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members -dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case - -# Symbol specifications - -dotnet_naming_symbols.interface.applicable_kinds = interface -dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interface.required_modifiers = - -dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum -dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types.required_modifiers = - -dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method -dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.non_field_members.required_modifiers = - -# Naming styles - -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = -dotnet_naming_style.pascal_case.capitalization = pascal_case - -dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = -dotnet_naming_style.begins_with_i.capitalization = pascal_case - -# Instance fields are camelCase and start with _ -dotnet_naming_rule.instance_fields_should_be_camel_case.severity = hint -dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields -dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style - -dotnet_naming_symbols.instance_fields.applicable_kinds = field - -dotnet_naming_style.instance_field_style.capitalization = camel_case -dotnet_naming_style.instance_field_style.required_prefix = _ - -# ReSharper properties -max_line_length = 200 -resharper_csharp_max_line_length = 200 -resharper_csharp_wrap_after_declaration_lpar = true -resharper_csharp_wrap_extends_list_style = chop_if_long -resharper_csharp_wrap_lines = false -resharper_max_attribute_length_for_same_line = 300 -resharper_place_type_constraints_on_same_line = true -resharper_wrap_before_arrow_with_expressions = true -resharper_wrap_before_extends_colon = false \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Application/LoggerExtensions.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Application/LoggerExtensions.cs deleted file mode 100644 index 210b3f0f..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Application/LoggerExtensions.cs +++ /dev/null @@ -1,75 +0,0 @@ - -namespace Calabonga.Microservice.Module.Web.Application; - -/// -/// The number identifiers for events in the microservices -/// -internal static class EventNumbers -{ - internal static readonly EventId UserRegistrationId = new EventId(9001, nameof(UserRegistrationId)); - internal static readonly EventId PostItemId = new EventId(9002, nameof(PostItemId)); -} - -/// -/// Event logging as ILogger extension. -/// Please see the video as the manual https://youtu.be/09EVKgHgwnM -/// -internal static class LoggerExtensions -{ - #region UserRegistration - - /// - /// EventItem register action event - /// - /// - /// - /// - internal static void MicroserviceUserRegistration(this ILogger source, string userName, Exception? exception = null) - { - switch (exception) - { - case null: - UserRegistrationExecute(source, userName, exception); - break; - default: - UserRegistrationFailedExecute(source, userName, exception); - break; - } - } - - private static readonly Action UserRegistrationExecute = - LoggerMessage.Define(LogLevel.Information, EventNumbers.UserRegistrationId, - "User {userName} successfully registred"); - - private static readonly Action UserRegistrationFailedExecute = - LoggerMessage.Define(LogLevel.Error, EventNumbers.UserRegistrationId, - "User {userName} registred failed"); - - #endregion - - #region PostItem - - internal static void MicroservicePostItem(this ILogger source, string entityName, Exception? exception = null) - { - switch (exception) - { - case null: - PostItemExecute(source, entityName, null); - break; - - default: - PostItemFailedExecute(source, entityName, exception); - break; - } - } - - private static readonly Action PostItemExecute = - LoggerMessage.Define(LogLevel.Information, EventNumbers.PostItemId, - "The {entityName} successfully saved"); - - private static readonly Action PostItemFailedExecute = - LoggerMessage.Define(LogLevel.Error, EventNumbers.PostItemId, - "The {entityName} saving failed"); - - #endregion -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Application/ValidatorBehavior.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Application/ValidatorBehavior.cs deleted file mode 100644 index cc0db617..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Application/ValidatorBehavior.cs +++ /dev/null @@ -1,41 +0,0 @@ -using FluentValidation; -using MediatR; - -namespace Calabonga.Microservice.Module.Web.Application; - -/// -/// Base validator for requests -/// -/// -/// -public class ValidatorBehavior : IPipelineBehavior - where TRequest : IRequest -{ - private readonly IEnumerable> _validators; - - public ValidatorBehavior(IEnumerable> validators) => _validators = validators; - - /// - /// Pipeline handler. Perform any additional behavior and await the delegate as necessary - /// - /// Incoming request - /// Cancellation token - /// Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler. - /// Awaitable task returning the - public Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) - { - var failures = _validators - .Select(x => x.Validate(new ValidationContext(request))) - .SelectMany(x => x.Errors) - .Where(x => x != null) - .ToList(); - - if (!failures.Any()) - { - return next(); - } - - // return new ProblemDetails(); - throw new ValidationException(failures); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj deleted file mode 100644 index f19f30b6..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj +++ /dev/null @@ -1,31 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Common/CommonDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Common/CommonDefinition.cs deleted file mode 100644 index fd2586c0..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Common/CommonDefinition.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace Calabonga.Microservice.Module.Web.Definitions.Common; - -/// -/// AspNetCore common configuration -/// -public class CommonDefinition : AppDefinition -{ - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) - => app.UseHttpsRedirection(); - - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddLocalization(); - services.AddHttpContextAccessor(); - services.AddResponseCaching(); - services.AddMemoryCache(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Cors/CorsDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Cors/CorsDefinition.cs deleted file mode 100644 index 3c214b91..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Cors/CorsDefinition.cs +++ /dev/null @@ -1,47 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.Module.Domain.Base; - -namespace Calabonga.Microservice.Module.Web.Definitions.Cors; - -/// -/// Cors configurations -/// -public class CorsDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - var origins = builder.Configuration.GetSection("Cors")?.GetSection("Origins")?.Value?.Split(','); - services.AddCors(options => - { - options.AddPolicy(AppData.PolicyName, builder => - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - if (origins is not {Length: > 0}) - { - return; - } - - if (origins.Contains("*")) - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - builder.SetIsOriginAllowed(host => true); - builder.AllowCredentials(); - } - else - { - foreach (var origin in origins) - { - builder.WithOrigins(origin); - } - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/DbContext/DbContextDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/DbContext/DbContextDefinition.cs deleted file mode 100644 index 8901c293..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/DbContext/DbContextDefinition.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.Module.Infrastructure; -using Microsoft.EntityFrameworkCore; - -namespace Calabonga.Microservice.Module.Web.Definitions.DbContext; - -/// -/// ASP.NET Core services registration and configurations -/// -public class DbContextDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - => services.AddDbContext(config => - { - // UseInMemoryDatabase - This for demo purposes only! - // Should uninstall package "Microsoft.EntityFrameworkCore.InMemory" and install what you need. - // For example: "Microsoft.EntityFrameworkCore.SqlServer" - // uncomment line below to use UseSqlServer(). Don't forget setup connection string in appSettings.json - config.UseInMemoryDatabase("DEMO_PURPOSES_ONLY"); - // config.UseSqlServer(configuration.GetConnectionString(nameof(ApplicationDbContext))); - }); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs deleted file mode 100644 index c21b1622..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs +++ /dev/null @@ -1,69 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Net.Http.Headers; -using System.Security.Cryptography; - -namespace Calabonga.Microservice.Module.Web.Definitions.ETagGenerator; - -/// -/// ETag Generator -/// -public class ETagGeneratorDefinition : AppDefinition -{ - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) => - app.Use(async (context, next) => - { - var response = context.Response; - var originalStream = response.Body; - - await using var ms = new MemoryStream(); - response.Body = ms; - - await next(context); - - if (IsEtagSupported(response)) - { - var checksum = CalculateChecksum(ms); - - response.Headers[HeaderNames.ETag] = checksum; - - if (context.Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var etag) && checksum == etag) - { - response.StatusCode = StatusCodes.Status304NotModified; - return; - } - } - - ms.Position = 0; - await ms.CopyToAsync(originalStream); - }); - - - private static bool IsEtagSupported(HttpResponse response) - { - if (response.StatusCode != StatusCodes.Status200OK) - { - return false; - } - - // The 100kb length limit is not based in science. Feel free to change - if (response.Body.Length > 100 * 1024) - { - return false; - } - - return !response.Headers.ContainsKey(HeaderNames.ETag); - } - - private static string CalculateChecksum(MemoryStream ms) - { - using var algorithm = SHA1.Create(); - ms.Position = 0; - var bytes = algorithm.ComputeHash(ms); - return $"\"{WebEncoders.Base64UrlEncode(bytes)}\""; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs deleted file mode 100644 index a06e129a..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using FluentValidation; -using Microsoft.AspNetCore.Diagnostics; -using Serilog; -using System.Text.Json; - -namespace Calabonga.Microservice.Module.Web.Definitions.ErrorHandling; - -/// -/// Custom Error handling -/// -public class ErrorHandlingDefinition : AppDefinition -{ - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) => - app.UseExceptionHandler(error => error.Run(async context => - { - - context.Response.ContentType = "application/json"; - var contextFeature = context.Features.Get(); - if (contextFeature is not null) - { - // handling validation errors - if (contextFeature.Error is ValidationException failures) - { - await context.Response.WriteAsync(JsonSerializer.Serialize(failures.Errors)); - context.Response.StatusCode = StatusCodes.Status400BadRequest; - return; - } - - // handling all another errors - Log.Error($"Something went wrong in the {contextFeature.Error}"); - context.Response.StatusCode = StatusCodes.Status500InternalServerError; - - if (app.Environment.IsDevelopment()) - { - await context.Response.WriteAsync($"INTERNAL SERVER ERROR: {contextFeature.Error}"); - } - else - { - await context.Response.WriteAsync("INTERNAL SERVER ERROR. PLEASE TRY AGAIN LATER"); - } - } - })); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/FluentValidating/FluentValidationDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/FluentValidating/FluentValidationDefinition.cs deleted file mode 100644 index 3760e717..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/FluentValidating/FluentValidationDefinition.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using FluentValidation; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.Module.Web.Definitions.FluentValidating; - -/// -/// FluentValidation registration as MicroserviceDefinition -/// -public class FluentValidationDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.Configure(options => - { - options.SuppressModelStateInvalidFilter = true; - }); - - services.AddValidatorsFromAssembly(typeof(Program).Assembly); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Identity/AuthData.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Identity/AuthData.cs deleted file mode 100644 index e250920a..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Identity/AuthData.cs +++ /dev/null @@ -1,8 +0,0 @@ -using OpenIddict.Server.AspNetCore; - -namespace Calabonga.Microservice.Module.Web.Definitions.Identity; - -public static class AuthData -{ - public const string AuthSchemes = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Identity/AuthorizationDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Identity/AuthorizationDefinition.cs deleted file mode 100644 index bbdbd594..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Identity/AuthorizationDefinition.cs +++ /dev/null @@ -1,108 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.Module.Domain.Base; -using Calabonga.Microservice.Module.Web.Definitions.OpenIddict; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Authorization; -using Microsoft.IdentityModel.Tokens; -using OpenIddict.Server.AspNetCore; -using System.Text.Json; - -namespace Calabonga.Microservice.Module.Web.Definitions.Identity; - -/// -/// Authorization Policy registration -/// -public class AuthorizationDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - var url = builder.Configuration.GetSection("AuthServer").GetValue("Url"); - - services - .AddAuthentication(options => - { - options.DefaultScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; - options.DefaultAuthenticateScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; - }) - .AddJwtBearer(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme, "Bearer", options => - { - options.SaveToken = true; - options.Audience = "client-id-code"; - options.Authority = url; - options.RequireHttpsMetadata = false; - options.TokenValidationParameters = new TokenValidationParameters - { - ValidateAudience = false, // Audience should be defined on the authorization server or disabled as shown - ClockSkew = new TimeSpan(0, 0, 30) - }; - options.Events = new JwtBearerEvents - { - OnChallenge = context => - { - context.HandleResponse(); - context.Response.StatusCode = StatusCodes.Status401Unauthorized; - context.Response.ContentType = "application/json"; - - // Ensure we always have an error and error description. - if (string.IsNullOrEmpty(context.Error)) - { - context.Error = "invalid_token"; - } - - if (string.IsNullOrEmpty(context.ErrorDescription)) - { - context.ErrorDescription = "This request requires a valid JWT access token to be provided"; - } - - // Add some extra context for expired tokens. - if (context.AuthenticateFailure != null && context.AuthenticateFailure.GetType() == typeof(SecurityTokenExpiredException)) - { - var authenticationException = context.AuthenticateFailure as SecurityTokenExpiredException; - context.Response.Headers.Add("x-token-expired", authenticationException?.Expires.ToString("o")); - context.ErrorDescription = $"The token expired on {authenticationException?.Expires:o}"; - } - - return context.Response.WriteAsync(JsonSerializer.Serialize(new - { - error = context.Error, - error_description = context.ErrorDescription - })); - } - }; - }); - - services.AddAuthorization(options => - { - options.AddPolicy(AuthData.AuthSchemes, policy => - { - policy.RequireAuthenticatedUser(); - policy.RequireClaim("scope", "api"); - }); - }); - - services.AddSingleton(); - services.AddSingleton(); - } - - /// - /// Configure application for current microservice - /// - /// - /// - public override void ConfigureApplication(WebApplication app) - { - app.UseRouting(); - app.UseCors(AppData.PolicyName); - app.UseAuthentication(); - app.UseAuthorization(); - - // registering UserIdentity helper as singleton - UserIdentity.Instance.Configure(app.Services.GetService()!); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Identity/UserIdentity.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Identity/UserIdentity.cs deleted file mode 100644 index fc8650d0..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Identity/UserIdentity.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Calabonga.Microservices.Core.Exceptions; -using System.Security.Claims; -using System.Security.Principal; - -namespace Calabonga.Microservice.Module.Web.Definitions.Identity; - -/// -/// Identity helper for Requests operations -/// -public sealed class UserIdentity -{ - private UserIdentity() { } - - public static UserIdentity Instance => _lazy.Value; - - public void Configure(IHttpContextAccessor httpContextAccessor) - { - ContextAccessor = httpContextAccessor ?? throw new MicroserviceArgumentNullException(nameof(IHttpContextAccessor)); - IsInitialized = true; - } - - public IIdentity? User - { - get - { - if (IsInitialized) - { - return ContextAccessor.HttpContext!.User.Identity != null - && ContextAccessor.HttpContext != null - && ContextAccessor.HttpContext.User.Identity.IsAuthenticated - ? ContextAccessor.HttpContext.User.Identity - : null; - } - throw new MicroserviceArgumentNullException($"{nameof(UserIdentity)} has not been initialized. Please use {nameof(UserIdentity)}.Instance.Configure(...) in Configure Application method in Startup.cs"); - } - } - - public IEnumerable Claims - { - get - { - if (User != null) - { - return ContextAccessor.HttpContext!.User.Claims; - } - return Enumerable.Empty(); - } - } - - private static readonly Lazy _lazy = new(() => new UserIdentity()); - - private bool IsInitialized { get; set; } - - private static IHttpContextAccessor ContextAccessor { get; set; } = null!; - -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mapping/AutomapperDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mapping/AutomapperDefinition.cs deleted file mode 100644 index 04c51479..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mapping/AutomapperDefinition.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace Calabonga.Microservice.Module.Web.Definitions.Mapping; - -/// -/// Register Automapper as MicroserviceDefinition -/// -public class AutomapperDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - => services.AddAutoMapper(typeof(Program)); - - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) - { - var mapper = app.Services.GetRequiredService(); - if (app.Environment.IsDevelopment()) - { - // validate Mapper Configuration - mapper.AssertConfigurationIsValid(); - } - else - { - mapper.CompileMappings(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mapping/PagedListConverter.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mapping/PagedListConverter.cs deleted file mode 100644 index 1850b889..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mapping/PagedListConverter.cs +++ /dev/null @@ -1,23 +0,0 @@ -using AutoMapper; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.Module.Web.Definitions.Mapping; - -/// -/// Generic converter for IPagedList collections -/// -/// -/// -public class PagedListConverter : ITypeConverter, IPagedList> -{ - /// Performs conversion from source to destination type - /// Source object - /// Destination object - /// Resolution context - /// Destination object - public IPagedList Convert(IPagedList? source, IPagedList destination, ResolutionContext context) => - // ReSharper disable once ConditionIsAlwaysTrueOrFalse - source == null - ? PagedList.Empty() - : PagedList.From(source, items => context.Mapper.Map>(items)); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mediator/LogPostTransaction.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mediator/LogPostTransaction.cs deleted file mode 100644 index 01201096..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mediator/LogPostTransaction.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Calabonga.Microservice.Module.Web.Definitions.Mediator.Base; -using Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.Module.Web.Definitions.Mediator; - -public class LogPostTransactionBehavior : TransactionBehavior>, OperationResult> -{ - public LogPostTransactionBehavior(IUnitOfWork unitOfWork) : base(unitOfWork) { } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mediator/MediatorDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mediator/MediatorDefinition.cs deleted file mode 100644 index aa81ed69..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mediator/MediatorDefinition.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.Module.Web.Application; -using MediatR; -using System.Reflection; - -namespace Calabonga.Microservice.Module.Web.Definitions.Mediator; - -/// -/// Register Mediator as MicroserviceDefinition -/// -public class MediatorDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>)); - services.AddMediatR(Assembly.GetExecutingAssembly()); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/OpenIddictDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/OpenIddictDefinition.cs deleted file mode 100644 index 6a47103b..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/OpenIddictDefinition.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace Calabonga.Microservice.Module.Web.Definitions.OpenIddict; - -public class OpenIddictDefinition : AppDefinition -{ - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) => - services - .AddOpenIddict() - .AddValidation(options => - { - // Import the configuration from the local OpenIddict server instance. - options.UseLocalServer(); - - // Register the ASP.NET Core host. - options.UseAspNetCore(); - }); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Swagger/SwaggerDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Swagger/SwaggerDefinition.cs deleted file mode 100644 index e226a5aa..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Swagger/SwaggerDefinition.cs +++ /dev/null @@ -1,117 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.Module.Domain.Base; -using Microsoft.AspNetCore.Mvc; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerUI; - -namespace Calabonga.Microservice.Module.Web.Definitions.Swagger; - -/// -/// Swagger definition for application -/// -public class SwaggerDefinition : AppDefinition -{ - - private const string _appVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - private const string _swaggerConfig = "/swagger/v1/swagger.json"; - - public override void ConfigureApplication(WebApplication app) - { - if (!app.Environment.IsDevelopment()) - { - return; - } - - app.UseSwagger(); - app.UseSwaggerUI(settings => - { - settings.SwaggerEndpoint(_swaggerConfig, $"{AppData.ServiceName} v.{_appVersion}"); - settings.HeadContent = $"{ThisAssembly.Git.Branch.ToUpper()} {ThisAssembly.Git.Commit.ToUpper()}"; - settings.DocumentTitle = $"{AppData.ServiceName}"; - settings.DefaultModelExpandDepth(0); - settings.DefaultModelRendering(ModelRendering.Model); - settings.DefaultModelsExpandDepth(0); - settings.DocExpansion(DocExpansion.None); - settings.OAuthScopeSeparator(" "); - settings.OAuthClientId("client-id-code"); - settings.OAuthClientSecret("client-secret-code"); - settings.DisplayRequestDuration(); - settings.OAuthAppName(AppData.ServiceName); - }); - } - - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); - services.AddEndpointsApiExplorer(); - services.AddSwaggerGen(options => - { - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = AppData.ServiceName, - Version = _appVersion, - Description = AppData.ServiceDescription - }); - - options.ResolveConflictingActions(x => x.First()); - - options.TagActionsBy(api => - { - string tag; - if (api.ActionDescriptor is { } descriptor) - { - var attribute = descriptor.EndpointMetadata.OfType().FirstOrDefault(); - tag = attribute?.GroupName ?? descriptor.RouteValues["controller"] ?? "Untitled"; - } - else - { - tag = api.RelativePath!; - } - - var tags = new List(); - if (!string.IsNullOrEmpty(tag)) - { - tags.Add(tag); - } - return tags; - }); - - var url = builder.Configuration.GetSection("AuthServer").GetValue("Url"); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - AuthorizationCode = new OpenApiOAuthFlow - { - AuthorizationUrl = new Uri($"{url}/connect/authorize", UriKind.Absolute), - TokenUrl = new Uri($"{url}/connect/token", UriKind.Absolute), - Scopes = new Dictionary - { - { "api", "Default scope" } - } - } - } - }); - options.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "oauth2" - }, - Scheme = "oauth2", - Name = "Bearer", - In = ParameterLocation.Header, - - }, - new List() - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/UoW/UnitOfWorkDefinition.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/UoW/UnitOfWorkDefinition.cs deleted file mode 100644 index 89eb4ec6..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/UoW/UnitOfWorkDefinition.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.Module.Infrastructure; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.Module.Web.Definitions.UoW; - -/// -/// Unit of Work registration as MicroserviceDefinition -/// -public class UnitOfWorkDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - => services.AddUnitOfWork(); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/EventItemEndpoints.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/EventItemEndpoints.cs deleted file mode 100644 index 8c3aecb7..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/EventItemEndpoints.cs +++ /dev/null @@ -1,58 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.Module.Web.Definitions.Identity; -using Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.Queries; -using Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints; - -public class EventItemEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("/api/logs/{id}", LogGetById); - app.MapGet("/api/logs/paged", LogGetPaged); - app.MapPost("/api/logs/", PostLog); - app.MapPut("/api/logs/{id}", PutLog); - app.MapDelete("/api/logs/{id}", LogDelete); - } - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogGetById([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new GetEventItemByIdRequest(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogDelete([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new DeleteEventItemRequest(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task>> LogGetPaged([FromServices] IMediator mediator, int pageIndex, int pageSize, string? search, HttpContext context) - => await mediator.Send(new GetEventItemPagedRequest(pageIndex, pageSize, search), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PostLog([FromServices] IMediator mediator, EventItemCreateViewModel model, HttpContext context) - => await mediator.Send(new PostEventItemRequest(model), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PutLog([FromServices] IMediator mediator, Guid id, EventItemUpdateViewModel model, HttpContext context) - => await mediator.Send(new PutEventItemRequest(id, model), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/EventItemMapperConfiguration.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/EventItemMapperConfiguration.cs deleted file mode 100644 index ef840689..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/EventItemMapperConfiguration.cs +++ /dev/null @@ -1,32 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.Module.Domain; -using Calabonga.Microservice.Module.Web.Definitions.Mapping; -using Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints; - -/// -/// Mapper Configuration for entity EventItem -/// -public class EventItemMapperConfiguration : Profile -{ - /// - public EventItemMapperConfiguration() - { - CreateMap() - .ForMember(x => x.Id, o => o.Ignore()); - - CreateMap(); - - CreateMap(); - - CreateMap() - .ForMember(x => x.CreatedAt, o => o.Ignore()) - .ForMember(x => x.ThreadId, o => o.Ignore()) - .ForMember(x => x.ExceptionMessage, o => o.Ignore()); - - CreateMap, IPagedList>() - .ConvertUsing>(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/EventItemValidator.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/EventItemValidator.cs deleted file mode 100644 index 93a96e49..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/EventItemValidator.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.ViewModels; -using FluentValidation; - -namespace Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints; - -/// -/// RegisterViewModel Validator -/// -public class EventItemCreateRequestValidator : AbstractValidator -{ - public EventItemCreateRequestValidator() => RuleSet("default", () => - { - RuleFor(x => x.CreatedAt).NotNull(); - RuleFor(x => x.Message).NotEmpty().NotNull().MaximumLength(4000); - RuleFor(x => x.Level).NotEmpty().NotNull().MaximumLength(50); - RuleFor(x => x.Logger).NotNull().NotEmpty().MaximumLength(255); - - RuleFor(x => x.ThreadId).MaximumLength(50); - RuleFor(x => x.ExceptionMessage).MaximumLength(4000); - }); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/DeleteEventItem.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/DeleteEventItem.cs deleted file mode 100644 index f688b5b3..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/DeleteEventItem.cs +++ /dev/null @@ -1,55 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.Module.Domain; -using Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem delete -/// -public record DeleteEventItemRequest(Guid Id) : IRequest>; - -/// -/// Request: EventItem delete -/// -public class DeleteEventItemRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - - private readonly IMapper _mapper; - - public DeleteEventItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(DeleteEventItemRequest request, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.FindAsync(request.Id); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException("Entity not found")); - return operation; - } - repository.Delete(entity); - await _unitOfWork.SaveChangesAsync(); - if (_unitOfWork.LastSaveChangesResult.IsOk) - { - operation.Result = _mapper.Map(entity); - return operation; - } - operation.AddError(_unitOfWork.LastSaveChangesResult.Exception); - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/GetEventItemById.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/GetEventItemById.cs deleted file mode 100644 index b60f52f3..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/GetEventItemById.cs +++ /dev/null @@ -1,48 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.Module.Domain; -using Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request for EventItem by Identifier -/// -public record GetEventItemByIdRequest(Guid Id) : IRequest>; - -/// -/// Response for Request for EventItem by Identifier -/// -public class GetEventItemByIdRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public GetEventItemByIdRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request getting log by identifier - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(GetEventItemByIdRequest request, CancellationToken cancellationToken) - { - var id = request.Id; - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entityWithoutIncludes = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == id); - if (entityWithoutIncludes == null) - { - operation.AddError(new MicroserviceNotFoundException($"Entity with identifier {id} not found")); - return operation; - } - operation.Result = _mapper.Map(entityWithoutIncludes); - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/GetEventItemPaged.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/GetEventItemPaged.cs deleted file mode 100644 index 5a11a049..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/GetEventItemPaged.cs +++ /dev/null @@ -1,75 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.Module.Domain; -using Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.PredicatesBuilder; -using Calabonga.UnitOfWork; -using MediatR; -using System.Linq.Expressions; - -namespace Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request for paged list of EventItems -/// -public record GetEventItemPagedRequest(int PageIndex, int PageSize, string? Search) : IRequest>>; - -/// -/// Request for paged list of EventItems -/// -public class GetEventItemPagedRequestHandler : IRequestHandler>> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public GetEventItemPagedRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task>> Handle(GetEventItemPagedRequest request, - CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult>(); - var predicate = GetPredicate(request.Search); - var pagedList = await _unitOfWork.GetRepository() - .GetPagedListAsync( - predicate: predicate, - pageIndex: request.PageIndex, - pageSize: request.PageSize, - cancellationToken: cancellationToken); - - if (pagedList == null) - { - operation.Result = PagedList.Empty(); - operation.AddWarning("Response does not return the result for pagination."); - return operation; - } - - if (pagedList.PageIndex > pagedList.TotalPages) - { - pagedList = await _unitOfWork.GetRepository() - .GetPagedListAsync( - pageIndex: 0, - pageSize: request.PageSize, cancellationToken: cancellationToken); - } - - operation.Result = _mapper.Map>(pagedList); - return operation; - } - - private Expression> GetPredicate(string? search) - { - var predicate = PredicateBuilder.True(); - if (search is null) - { - return predicate; - } - - predicate = predicate.And(x => x.Message.Contains(search)); - predicate = predicate.Or(x => x.Logger.Contains(search)); - predicate = predicate.Or(x => x.Level.Contains(search)); - return predicate; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/PostEventItem.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/PostEventItem.cs deleted file mode 100644 index c2ffc9ae..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/PostEventItem.cs +++ /dev/null @@ -1,63 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.Module.Domain; -using Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem creation -/// -public record PostEventItemRequest(EventItemCreateViewModel Model) : IRequest>; - -/// -/// Request: EventItem creation -/// -public class PostEventItemRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - private readonly ILogger _logger; - - - public PostEventItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper, ILogger logger) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - _logger = logger; - } - - public async Task> Handle(PostEventItemRequest eventItemRequest, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - - var entity = _mapper.Map(eventItemRequest.Model); - if (entity == null) - { - operation.AddError(new MicroserviceUnauthorizedException(AppContracts.Exceptions.MappingException)); - return operation; - } - - await _unitOfWork.GetRepository().InsertAsync(entity, cancellationToken); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - - var mapped = _mapper.Map(entity); - - operation.Result = mapped; - operation.AddSuccess("Successfully created"); - return operation; - } - - operation.AddError(lastResult.Exception?? new ApplicationException("Something went wrong")); - - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/UpdateEventItem.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/UpdateEventItem.cs deleted file mode 100644 index 590a33a0..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/Queries/UpdateEventItem.cs +++ /dev/null @@ -1,59 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.Module.Domain; -using Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem edit -/// -public record PutEventItemRequest(Guid Id, EventItemUpdateViewModel Model) : IRequest>; - -/// -/// Request: EventItem creation -/// -public class PutEventItemRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public PutEventItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task> Handle(PutEventItemRequest eventItemRequest, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == eventItemRequest.Id, disableTracking: false); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException(AppContracts.Exceptions.NotFoundException)); - return operation; - } - - _mapper.Map(eventItemRequest.Model, entity); - - repository.Update(entity); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("Successfully updated"); - return operation; - } - - operation.AddError(lastResult.Exception ?? new ApplicationException("Something went wrong")); - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemCreateViewModel.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemCreateViewModel.cs deleted file mode 100644 index 186f8ff3..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemCreateViewModel.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Calabonga.Microservice.Module.Domain.Base; - -namespace Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemCreateViewModel : IViewModel -{ - /// - /// EventItem Created At - /// - public DateTime CreatedAt { get; set; } - - /// - /// Service name or provider - /// - public string Logger { get; set; } = null!; - - /// - /// EventItem level for logging. See - /// - public string Level { get; set; } = null!; - - /// - /// EventItem Message - /// - public string Message { get; set; } = null!; - - /// - /// Thread identifier - /// - public string? ThreadId { get; set; } - - /// - /// Exception message - /// - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemUpdateViewModel.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemUpdateViewModel.cs deleted file mode 100644 index e4a6eefa..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemUpdateViewModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Calabonga.Microservice.Module.Domain.Base; - -namespace Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemUpdateViewModel : ViewModelBase -{ - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemViewModel.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemViewModel.cs deleted file mode 100644 index 6689da83..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/EventItemsEndpoints/ViewModels/EventItemViewModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Calabonga.Microservice.Module.Web.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemViewModel -{ - public Guid Id { get; set; } - - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; - - public string? ThreadId { get; set; } - - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/ProfileEndpoints/ProfilesEndpoint.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/ProfileEndpoints/ProfilesEndpoint.cs deleted file mode 100644 index a82ba63c..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/ProfileEndpoints/ProfilesEndpoint.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.Module.Web.Definitions.Identity; -using Calabonga.Microservice.Module.Web.Endpoints.ProfileEndpoints.Queries; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.Module.Web.Endpoints.ProfileEndpoints; - -public class ProfilesEndpointDefinition : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - => app.MapGet("/api/profiles/get-roles", GetRoles); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes, Policy = "EventItems:UserRoles:View")] - [FeatureGroupName("Profiles")] - private async Task GetRoles([FromServices] IMediator mediator, HttpContext context) - => await mediator.Send(new GetRolesRequest(), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/ProfileEndpoints/ProfilesMapperConfiguration.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/ProfileEndpoints/ProfilesMapperConfiguration.cs deleted file mode 100644 index 884444f6..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/ProfileEndpoints/ProfilesMapperConfiguration.cs +++ /dev/null @@ -1,23 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.Module.Web.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using System.Security.Claims; - -namespace Calabonga.Microservice.Module.Web.Endpoints.ProfileEndpoints; - -/// -/// Mapper Configuration for entity ApplicationUser -/// -public class ProfilesMapperConfiguration : Profile -{ - /// - public ProfilesMapperConfiguration() - => CreateMap() - .ForMember(x => x.Id, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Name))) - .ForMember(x => x.PositionName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Actor))) - .ForMember(x => x.FirstName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.GivenName))) - .ForMember(x => x.LastName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Surname))) - .ForMember(x => x.Roles, o => o.MapFrom(claims => ClaimsHelper.GetValues(claims, ClaimTypes.Role))) - .ForMember(x => x.Email, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Name))) - .ForMember(x => x.PhoneNumber, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.MobilePhone))); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/ProfileEndpoints/Queries/GetRoles.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/ProfileEndpoints/Queries/GetRoles.cs deleted file mode 100644 index 683fcc4f..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/ProfileEndpoints/Queries/GetRoles.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Calabonga.Microservices.Core; -using MediatR; -using System.Security.Claims; - -namespace Calabonga.Microservice.Module.Web.Endpoints.ProfileEndpoints.Queries; - -/// -/// Request: Returns user roles -/// -public record GetRolesRequest : IRequest; - -public class GetRolesRequestHandler : RequestHandler -{ - private readonly IHttpContextAccessor _httpContextAccessor; - - public GetRolesRequestHandler(IHttpContextAccessor httpContextAccessor) => _httpContextAccessor = httpContextAccessor; - - protected override string Handle(GetRolesRequest request) - { - var user = _httpContextAccessor.HttpContext!.User; - var roles = ClaimsHelper.GetValues((ClaimsIdentity)user.Identity!, ClaimTypes.Role); - return $"Current user ({user.Identity!.Name}) have following roles: {string.Join("|", roles)}"; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/ProfileEndpoints/ViewModels/UserProfileViewModel.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/ProfileEndpoints/ViewModels/UserProfileViewModel.cs deleted file mode 100644 index 62368f7d..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Endpoints/ProfileEndpoints/ViewModels/UserProfileViewModel.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace Calabonga.Microservice.Module.Web.Endpoints.ProfileEndpoints.ViewModels; - -/// -/// Application User Profile -/// -public class UserProfileViewModel -{ - /// - /// Identifier - /// - public Guid Id { get; set; } - - /// - /// FirstName - /// - public string FirstName { get; set; } = null!; - - /// - /// LastName - /// - public string LastName { get; set; } = null!; - - /// - /// Email - /// - public string Email { get; set; } = null!; - - /// - /// User Roles - /// - public List? Roles { get; set; } - - /// - /// User PhoneNumber - /// - public string? PhoneNumber { get; set; } - - /// - /// Position Name - /// - public string? PositionName { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/FeatureGroupNameAttribute.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/FeatureGroupNameAttribute.cs deleted file mode 100644 index 1637134c..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/FeatureGroupNameAttribute.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Calabonga.Microservice.Module.Web; - -/// -/// Swagger controller group attribute -/// -/// -[AttributeUsage(AttributeTargets.Method)] -public class FeatureGroupNameAttribute : Attribute -{ - /// - public FeatureGroupNameAttribute(string groupName) => GroupName = groupName; - - /// - /// Group name - /// - public string GroupName { get; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Program.cs b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Program.cs deleted file mode 100644 index 098fe1c2..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Program.cs +++ /dev/null @@ -1,61 +0,0 @@ -// -------------------------------------------------------------------- -// Name: Template for Micro service on ASP.NET Core API with -// OpenIddict (OAuth2.0) -// Author: Calabonga © 2005-2022 Calabonga SOFT -// Version: 6.1.1 -// Based on: .NET 6.0.x -// Created Date: 2019-04-13 3:28:39 PM -// Updated Date: 2022-10-02 11:25:41 AM -// -------------------------------------------------------------------- -// Contacts -// -------------------------------------------------------------------- -// Blog: https://www.calabonga.net -// GitHub: https://github.com/Calabonga -// YouTube: https://youtube.com/sergeicalabonga -// -------------------------------------------------------------------- -// Description: -// -------------------------------------------------------------------- -// Minimal API for NET6 used. -// This template implements Web API and OpenIddict (OAuth2.0) -// functionality. Also, support two type of Authentication: -// Cookie and Bearer -// -------------------------------------------------------------------- - -using Calabonga.AspNetCore.AppDefinitions; -using Serilog; -using Serilog.Events; - -try -{ - // configure logger (Serilog) - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .Enrich.FromLogContext() - .WriteTo.Console() - .CreateLogger(); - - // created builder - var builder = WebApplication.CreateBuilder(args); - builder.Host.UseSerilog(); - - builder.Services.AddDefinitions(builder, typeof(Program)); - - // create application - var app = builder.Build(); - app.UseDefinitions(); - - // start application - app.Run(); - - return 0; -} -catch (Exception ex) -{ - Log.Fatal(ex, "Host terminated unexpectedly"); - return 1; -} -finally -{ - Log.CloseAndFlush(); -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.Development.json b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.Development.json deleted file mode 100644 index a6e41b5e..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.Development.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=;User ID=;Password=" - }, - "Cors": { - "Origins": "*" - }, - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.json b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.json deleted file mode 100644 index 387377ec..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/appsettings.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AuthServer": { - "Url": "https://localhost:10001" - }, - "AllowedHosts": "*" -} \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/readme.md b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/readme.md deleted file mode 100644 index ef570a14..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/readme.md +++ /dev/null @@ -1,25 +0,0 @@ -# About - -| Name | Description | -| ------------ | ------------------------------------------ | -| Name | Microservice Template for ASP.NET Core API | -| Author | Calabonga SOFT © 2005-2022 Calabonga SOFT | -| Created Date | 2019-04-19 | - -# Versions - -Nimble Framework Templates build on .NET 6.0. That`s why it have the same major version. But the all improvements will increment minor versions. -Current version: 6.1.1 - -# Contacts - -You can contact me by using the next opportunities: - -* Blog: https://www.calabonga.net -* GitHub: https://github.com/Calabonga -* Zen: https://dzen.ru/calabonga -* YouTube: https://youtube.com/sergeicalabonga - -# Description: - -This template implements Web API functionality using minmal API feature from NET 6.0 \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.sln b/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.sln deleted file mode 100644 index d2d35476..00000000 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.sln +++ /dev/null @@ -1,37 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.31912.275 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Calabonga.Microservice.Module.Domain", "Calabonga.Microservice.Module.Domain\Calabonga.Microservice.Module.Domain.csproj", "{2DA97A11-5594-406B-8216-F46B29B41BF4}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Calabonga.Microservice.Module.Infrastructure", "Calabonga.Microservice.Module.Infrastructure\Calabonga.Microservice.Module.Infrastructure.csproj", "{62AC64BB-F04B-445C-83A6-94C491C8F897}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Calabonga.Microservice.Module.Web", "Calabonga.Microservice.Module.Web\Calabonga.Microservice.Module.Web.csproj", "{9D94187D-B284-4069-8AC4-AEBD4D633A35}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2DA97A11-5594-406B-8216-F46B29B41BF4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2DA97A11-5594-406B-8216-F46B29B41BF4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2DA97A11-5594-406B-8216-F46B29B41BF4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2DA97A11-5594-406B-8216-F46B29B41BF4}.Release|Any CPU.Build.0 = Release|Any CPU - {62AC64BB-F04B-445C-83A6-94C491C8F897}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {62AC64BB-F04B-445C-83A6-94C491C8F897}.Debug|Any CPU.Build.0 = Debug|Any CPU - {62AC64BB-F04B-445C-83A6-94C491C8F897}.Release|Any CPU.ActiveCfg = Release|Any CPU - {62AC64BB-F04B-445C-83A6-94C491C8F897}.Release|Any CPU.Build.0 = Release|Any CPU - {9D94187D-B284-4069-8AC4-AEBD4D633A35}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9D94187D-B284-4069-8AC4-AEBD4D633A35}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9D94187D-B284-4069-8AC4-AEBD4D633A35}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9D94187D-B284-4069-8AC4-AEBD4D633A35}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {C11497F9-ED75-4BD7-B173-4204C1AB173F} - EndGlobalSection -EndGlobal diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Common.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Common.cs deleted file mode 100644 index 387b870e..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Common.cs +++ /dev/null @@ -1,46 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Static data container -/// -public static partial class AppData -{ - /// - /// Current service name - /// - public const string ServiceName = "Microservice Template with OpenIddict"; - - /// - /// Nimble Framework Microservice Template with integrated OpenIddict - /// for OpenID Connect server and Token Validation - /// - public const string ServiceDescription = "Nimble Framework Microservice Template with integrated OpenIddict for OpenID Connect server and Token Validation"; - - /// - /// Default policy name - /// - public const string PolicyName = "CorsPolicy"; - - /// - /// "SystemAdministrator" - /// - public const string SystemAdministratorRoleName = "Administrator"; - - /// - /// "BusinessOwner" - /// - public const string ManagerRoleName = "Manager"; - - - /// - /// Roles - /// - public static IEnumerable Roles - { - get - { - yield return SystemAdministratorRoleName; - yield return ManagerRoleName; - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Exceptions.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Exceptions.cs deleted file mode 100644 index 9ca24ec3..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Exceptions.cs +++ /dev/null @@ -1,60 +0,0 @@ -namespace $safeprojectname$.Base; - -public static partial class AppData -{ - /// - /// Exception messages - /// - public static class Exceptions - { - /// - /// "An exception was thrown" - /// - public static string ThrownException => "An exception was thrown"; - - /// - /// "Invalid cast exception" - /// - public static string TypeConverterException => "Invalid cast exception"; - - /// - /// "User not registered in the system" - /// - public static string UserNotFoundException => "User not registered in the system"; - - /// - /// "Object not found" - /// - public static string NotFoundException => "Object not found"; - - /// - /// "Unauthorized access denied" - /// - public static string UnauthorizedException => "Unauthorized access denied"; - - /// - /// "Argument null exception" - /// - public static string ArgumentNullException => "Argument null exception"; - - /// - /// "File already exists" - /// - public static string FileAlreadyExists => "File already exists"; - - /// - /// "Some errors occurred while checking the entity" - /// - public static string EntityValidationException => "Some errors occurred while checking the entity"; - - /// - /// "Invalid operation exception was thrown" - /// - public static string InvalidOperationException => "Invalid operation exception was thrown"; - - /// - /// "Argument out of range" - /// - public static string ArgumentOutOfRangeException => "Argument out of range"; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Messages.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Messages.cs deleted file mode 100644 index 4e00b9ed..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Messages.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace $safeprojectname$.Base; - -public static partial class AppData -{ - /// - /// Common messages - /// - public static class Messages - { - /// - /// "User successfully registered" - /// - public static string UserSuccessfullyRegistered => "User successfully registered"; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/Auditable.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/Auditable.cs deleted file mode 100644 index 76eb902c..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/Auditable.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Represents 'Audit-able' table from the Property Database -/// -public abstract class Auditable : Identity, IAuditable -{ - /// - /// DateTime when entity created. - /// It's never changed - /// - public DateTime CreatedAt { get; set; } - - /// - /// User name who created entity. - /// It's never changed - /// - public string CreatedBy { get; set; } - - /// - /// Last date entity updated - /// - public DateTime? UpdatedAt { get; set; } - - /// - /// Author of last updated - /// - public string UpdatedBy { get; set; } - -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/IAuditable.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/IAuditable.cs deleted file mode 100644 index c7026a64..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/IAuditable.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Represent information about creation and last update -/// -public interface IAuditable -{ - /// - /// DateTime of creation. This value will never changed - /// - DateTime CreatedAt { get; set; } - - /// - /// Author name. This value never changed - /// - string CreatedBy { get; set; } - - /// - /// DateTime of last value update. Should be updated when entity data updated - /// - DateTime? UpdatedAt { get; set; } - - /// - /// Author of last value update. Should be updated when entity data updated - /// - string UpdatedBy { get; set; } - -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/IHaveId.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/IHaveId.cs deleted file mode 100644 index 829eaed7..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/IHaveId.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Identifier common interface -/// -public interface IHaveId -{ - /// - /// Identifier - /// - Guid Id { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/IViewModel.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/IViewModel.cs deleted file mode 100644 index 4afc0b1f..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/IViewModel.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Represents ViewModel for CRUD controller -/// -public interface IViewModel { } \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/Identity.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/Identity.cs deleted file mode 100644 index 8fd4099e..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/Identity.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Identifier -/// -public abstract class Identity : IHaveId -{ - /// - /// Identifier - /// - public Guid Id { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/NamedAuditable.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/NamedAuditable.cs deleted file mode 100644 index 1aa2d784..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/NamedAuditable.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Audit-able with name -/// -public abstract class NamedAuditable : Auditable -{ - public string Name { get; set; } - - public string Description { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/NamedIdentity.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/NamedIdentity.cs deleted file mode 100644 index 45b5d66f..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/NamedIdentity.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// NamedIdentity dictionary for selector -/// -public abstract class NamedIdentity : Identity -{ - /// - /// Entity name - /// - public string Name { get; set; } - - /// - /// Entity brief name - /// - public string BriefName { get; set; } - - /// - /// Brief descriptions - /// - public string Description { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/Sortable.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/Sortable.cs deleted file mode 100644 index ce0b2ce8..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/Sortable.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Order -/// -public class Sortable : Auditable -{ - /// - /// Sorting index for entity - /// - public int SortIndex { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/TypeHelper.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/TypeHelper.cs deleted file mode 100644 index f5d84f70..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/TypeHelper.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Some helpful methods for Type manipulations -/// -public static class TypeHelper -{ - /// - /// Check type before converting - /// - /// - /// - /// - public static bool CanChangeType(object value, Type conversionType) - { - if (conversionType == null) - { - return false; - } - return value is IConvertible; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/ViewModelBase.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/ViewModelBase.cs deleted file mode 100644 index 218dd783..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/BASE/ViewModelBase.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// ViewModelBase for -/// -public class ViewModelBase : IViewModel, IHaveId -{ - /// - /// Identifier - /// - public Guid Id { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj deleted file mode 100644 index 27ac3865..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - - net6.0 - enable - enable - - - diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/EventItem.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/EventItem.cs deleted file mode 100644 index e3433e39..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/EventItem.cs +++ /dev/null @@ -1,21 +0,0 @@ -using $safeprojectname$.Base; - -namespace $safeprojectname$; - -/// -/// EventItem entity for demo purposes only -/// -public class EventItem : Identity -{ - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; - - public string? ThreadId { get; set; } - - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/MyTemplate.vstemplate b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/MyTemplate.vstemplate deleted file mode 100644 index 82649efb..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/MyTemplate.vstemplate +++ /dev/null @@ -1,38 +0,0 @@ - - - Calabonga.Microservice.IdentityModule.Domain - Calabonga.Microservice.IdentityModule.Domain - CSharp - - - 1000 - true - Calabonga.Microservice.IdentityModule.Domain - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - AppData.Common.cs - AppData.Exceptions.cs - AppData.Messages.cs - Auditable.cs - IAuditable.cs - Identity.cs - IHaveId.cs - IViewModel.cs - NamedAuditable.cs - NamedIdentity.cs - Sortable.cs - TypeHelper.cs - ViewModelBase.cs - - EventItem.cs - - - \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/__PreviewImage.png b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/__PreviewImage.png deleted file mode 100644 index d92b7a06..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/__TemplateIcon.png b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Domain/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/AppPermission.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/AppPermission.cs deleted file mode 100644 index be8cdeb1..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/AppPermission.cs +++ /dev/null @@ -1,29 +0,0 @@ -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$; - -/// -/// User permission for application -/// -public class AppPermission : Auditable -{ - /// - /// Application User profile identifier - /// - public Guid ApplicationUserProfileId { get; set; } - - /// - /// Application User Profile - /// - public virtual ApplicationUserProfile? ApplicationUserProfile { get; set; } - - /// - /// Authorize attribute policy name - /// - public string PolicyName { get; set; } = null!; - - /// - /// Description for current permission - /// - public string Description { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs deleted file mode 100644 index a83ca5c3..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs +++ /dev/null @@ -1,49 +0,0 @@ -using $ext_projectname$.Domain; -using $safeprojectname$.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Design; -using Microsoft.EntityFrameworkCore.Diagnostics; - -namespace $safeprojectname$; - -/// -/// Database context for current application -/// -public class ApplicationDbContext : DbContextBase -{ - public ApplicationDbContext(DbContextOptions options) - : base(options) { } - - public DbSet EventItems { get; set; } - - public DbSet Profiles { get; set; } - - public DbSet Permissions { get; set; } - - protected override void OnModelCreating(ModelBuilder builder) - { - builder.UseOpenIddict(); - base.OnModelCreating(builder); - } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - // It should be removed when using real Database (not in memory mode) - optionsBuilder.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)); - base.OnConfiguring(optionsBuilder); - } -} - -///// -///// ATTENTION! -///// It should uncomment two line below when using real Database (not in memory mode). Don't forget update connection string. -///// -//public class ApplicationDbContextFactory : IDesignTimeDbContextFactory -//{ -// public ApplicationDbContext CreateDbContext(string[] args) -// { -// var optionsBuilder = new DbContextOptionsBuilder(); -// optionsBuilder.UseSqlServer("Server=;Database=;User ID=;Password="); -// return new ApplicationDbContext(optionsBuilder.Options); -// } -//} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRole.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRole.cs deleted file mode 100644 index ebd1b27b..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRole.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Microsoft.AspNetCore.Identity; - -namespace $safeprojectname$; - -/// -/// Application role -/// -public class ApplicationRole : IdentityRole -{ -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRoleStore.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRoleStore.cs deleted file mode 100644 index 92ef4948..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRoleStore.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -namespace $safeprojectname$; - -/// -/// Application store for user -/// -public class ApplicationRoleStore : RoleStore -{ - public ApplicationRoleStore(ApplicationDbContext context, IdentityErrorDescriber describer = null) : base(context, describer) - { - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUser.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUser.cs deleted file mode 100644 index acf4fa79..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUser.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Microsoft.AspNetCore.Identity; - -namespace $safeprojectname$; - -/// -/// Default user for application. -/// Add profile data for application users by adding properties to the ApplicationUser class -/// -public class ApplicationUser : IdentityUser -{ - /// - /// FirstName - /// - public string? FirstName { get; set; } - - /// - /// LastName - /// - public string? LastName { get; set; } - - /// - /// Profile identity - /// - public Guid? ApplicationUserProfileId { get; set; } - - /// - /// User Profile - /// - public virtual ApplicationUserProfile? ApplicationUserProfile { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserProfile.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserProfile.cs deleted file mode 100644 index 6b14bb02..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserProfile.cs +++ /dev/null @@ -1,19 +0,0 @@ -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$; - -/// -/// Represent person with login information (ApplicationUser) -/// -public class ApplicationUserProfile : Auditable -{ - /// - /// Account - /// - public virtual ApplicationUser? ApplicationUser { get; set; } - - /// - /// Application permission for policy-based authorization - /// - public List? Permissions { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserStore.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserStore.cs deleted file mode 100644 index 950fe52e..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserStore.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; - -namespace $safeprojectname$; - -/// -/// Application store for user -/// -public class ApplicationUserStore : UserStore -{ - public ApplicationUserStore(ApplicationDbContext context, IdentityErrorDescriber describer) - : base(context, describer) - { - - } - - /// - /// Finds and returns a user, if any, who has the specified . - /// - /// The user ID to search for. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The that represents the asynchronous operation, containing the user matching the specified if it exists. - /// - public override Task FindByIdAsync(string userId, CancellationToken cancellationToken = default) - => Users - .Include(x => x.ApplicationUserProfile).ThenInclude(x => x.Permissions) - .FirstOrDefaultAsync(u => u.Id.ToString() == userId, cancellationToken: cancellationToken)!; - - public override Task FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default) - => Users - .Include(x => x.ApplicationUserProfile).ThenInclude(x => x.Permissions) - .FirstOrDefaultAsync(u => u.NormalizedUserName == normalizedUserName, cancellationToken: cancellationToken)!; -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/BASE/DbContextBase.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/BASE/DbContextBase.cs deleted file mode 100644 index 5db95c51..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/BASE/DbContextBase.cs +++ /dev/null @@ -1,257 +0,0 @@ -using $ext_projectname$.Domain.Base; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; -using System.Reflection; - -namespace $safeprojectname$.Base; - -/// -/// Base DbContext with predefined configuration -/// -public abstract class DbContextBase : IdentityDbContext -{ - private const string DefaultUserName = "Anonymous"; - - protected DbContextBase(DbContextOptions options) : base(options) - { - LastSaveChangesResult = new SaveChangesResult(); - } - - public SaveChangesResult LastSaveChangesResult { get; } - - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - /// - /// Saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// The number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override int SaveChanges(bool acceptAllChangesOnSuccess) - { - try - { - DbSaveChanges(); - return base.SaveChanges(acceptAllChangesOnSuccess); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - public override int SaveChanges() - { - try - { - DbSaveChanges(); - return base.SaveChanges(); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - private void DbSaveChanges() - { - var createdEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added); - foreach (var entry in createdEntries) - { - if (!(entry.Entity is IAuditable)) - { - continue; - } - - var creationDate = DateTime.Now.ToUniversalTime(); - var userName = entry.Property("CreatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("CreatedBy").CurrentValue; - var updatedAt = entry.Property("UpdatedAt").CurrentValue; - var createdAt = entry.Property("CreatedAt").CurrentValue; - if (createdAt != null) - { - if (DateTime.Parse(createdAt.ToString()).Year > 1970) - { - entry.Property("CreatedAt").CurrentValue = ((DateTime)createdAt).ToUniversalTime(); - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - - if (updatedAt != null) - { - if (DateTime.Parse(updatedAt.ToString()).Year > 1970) - { - entry.Property("UpdatedAt").CurrentValue = ((DateTime)updatedAt).ToUniversalTime(); - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - - entry.Property("CreatedBy").CurrentValue = userName; - entry.Property("UpdatedBy").CurrentValue = userName; - - LastSaveChangesResult.AddMessage($"ChangeTracker has new entities: {entry.Entity.GetType()}"); - } - - var updatedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified); - foreach (var entry in updatedEntries) - { - if (entry.Entity is IAuditable) - { - var userName = entry.Property("UpdatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("UpdatedBy").CurrentValue; - entry.Property("UpdatedAt").CurrentValue = DateTime.Now.ToUniversalTime(); - entry.Property("UpdatedBy").CurrentValue = userName; - } - - LastSaveChangesResult.AddMessage($"ChangeTracker has modified entities: {entry.Entity.GetType()}"); - } - } - - /// - /// Configures the schema needed for the identity framework. - /// - /// - /// The builder being used to construct the model for this context. - /// - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - var applyGenericMethod = typeof(ModelBuilder).GetMethods(BindingFlags.Instance | BindingFlags.Public).First(x => x.Name == "ApplyConfiguration"); - foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters)) - { - foreach (var item in type.GetInterfaces()) - { - if (!item.IsConstructedGenericType || item.GetGenericTypeDefinition() != typeof(IEntityTypeConfiguration<>)) - { - continue; - } - - var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(item.GenericTypeArguments[0]); - applyConcreteMethod.Invoke(builder, new[] { Activator.CreateInstance(type) }); - break; - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj deleted file mode 100644 index 626b3c3e..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj +++ /dev/null @@ -1,29 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/DATABASEINITIALIZATION/DatabaseInitializer.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/DATABASEINITIALIZATION/DatabaseInitializer.cs deleted file mode 100644 index 5706b74b..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/DATABASEINITIALIZATION/DatabaseInitializer.cs +++ /dev/null @@ -1,146 +0,0 @@ -using $ext_projectname$.Domain; -using $ext_projectname$.Domain.Base; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.DatabaseInitialization; - -/// -/// Database Initializer -/// -public static class DatabaseInitializer -{ - /// - /// Seeds one default users to database for demo purposes only - /// - /// - /// - public static async void SeedUsers(IServiceProvider serviceProvider) - { - using var scope = serviceProvider.CreateScope(); - await using var context = scope.ServiceProvider.GetService(); - - // ATTENTION! - // ----------------------------------------------------------------------------- - // This is should not be used when UseInMemoryDatabase() - // It should be uncomment when using UseSqlServer() settings or any other providers. - // ----------------------------------------------------------------------------- - //await context!.Database.EnsureCreatedAsync(); - //var pending = await context.Database.GetPendingMigrationsAsync(); - //if (pending.Any()) - //{ - // await context!.Database.MigrateAsync(); - //} - - if (context.Users.Any()) - { - return; - } - - var roles = AppData.Roles.ToArray(); - - foreach (var role in roles) - { - var roleManager = scope.ServiceProvider.GetRequiredService>(); - if (!context!.Roles.Any(r => r.Name == role)) - { - await roleManager.CreateAsync(new ApplicationRole { Name = role, NormalizedName = role.ToUpper() }); - } - } - - #region developer - - var developer1 = new ApplicationUser - { - Email = "microservice@yopmail.com", - NormalizedEmail = "MICROSERVICE@YOPMAIL.COM", - UserName = "microservice@yopmail.com", - FirstName = "Microservice", - LastName = "Administrator", - NormalizedUserName = "MICROSERVICE@YOPMAIL.COM", - PhoneNumber = "+79000000000", - EmailConfirmed = true, - PhoneNumberConfirmed = true, - SecurityStamp = Guid.NewGuid().ToString("D"), - ApplicationUserProfile = new ApplicationUserProfile - { - CreatedAt = DateTime.Now, - CreatedBy = "SEED", - Permissions = new List - { - new() - { - CreatedAt = DateTime.Now, - CreatedBy = "SEED", - PolicyName = "EventItems:UserRoles:View", - Description = "Access policy for EventItems controller user view" - } - } - } - }; - - if (!context!.Users.Any(u => u.UserName == developer1.UserName)) - { - var password = new PasswordHasher(); - var hashed = password.HashPassword(developer1, "123qwe!@#"); - developer1.PasswordHash = hashed; - var userStore = scope.ServiceProvider.GetRequiredService(); - var result = await userStore.CreateAsync(developer1); - if (!result.Succeeded) - { - throw new InvalidOperationException("Cannot create account"); - } - - var userManager = scope.ServiceProvider.GetService>(); - foreach (var role in roles) - { - var roleAdded = await userManager!.AddToRoleAsync(developer1, role); - if (roleAdded.Succeeded) - { - await context.SaveChangesAsync(); - } - } - } - - #endregion - - await context.SaveChangesAsync(); - } - - /// - /// Seeds one event to database for demo purposes only - /// - /// - public static async void SeedEvents(IServiceProvider serviceProvider) - { - using var scope = serviceProvider.CreateScope(); - await using var context = scope.ServiceProvider.GetService(); - - // ATTENTION! - // ----------------------------------------------------------------------------- - // This is should not be used when UseInMemoryDatabase() - // It should be uncomment when using UseSqlServer() settings or any other providers. - // ----------------------------------------------------------------------------- - //await context!.Database.EnsureCreatedAsync(); - //var pending = await context.Database.GetPendingMigrationsAsync(); - //if (pending.Any()) - //{ - // await context!.Database.MigrateAsync(); - //} - - if (context.EventItems.Any()) - { - return; - } - - await context.EventItems.AddAsync(new EventItem - { - CreatedAt = DateTime.UtcNow, - Id = Guid.Parse("1467a5b9-e61f-82b0-425b-7ec75f5c5029"), - Level = "Information", - Logger = "SEED", - Message = "Seed method some entities successfully save to ApplicationDbContext" - }); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/MyTemplate.vstemplate b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/MyTemplate.vstemplate deleted file mode 100644 index dea56f43..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/MyTemplate.vstemplate +++ /dev/null @@ -1,35 +0,0 @@ - - - Calabonga.Microservice.IdentityModule.Infrastructure - Calabonga.Microservice.IdentityModule.Infrastructure - CSharp - - - 1000 - true - Calabonga.Microservice.IdentityModule.Infrastructure - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - DbContextBase.cs - - - DatabaseInitializer.cs - - ApplicationDbContext.cs - ApplicationRole.cs - ApplicationRoleStore.cs - ApplicationUser.cs - ApplicationUserProfile.cs - ApplicationUserStore.cs - AppPermission.cs - - - \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/__PreviewImage.png b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/__PreviewImage.png deleted file mode 100644 index d92b7a06..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/__TemplateIcon.png b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Infrastructure/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/FeatureGroupNameAttribute.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/FeatureGroupNameAttribute.cs deleted file mode 100644 index 9e4d374b..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/FeatureGroupNameAttribute.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace $safeprojectname$.Application; - -/// -/// Swagger controller group attribute -/// -/// -[AttributeUsage(AttributeTargets.Method)] -public class FeatureGroupNameAttribute : Attribute -{ - /// - public FeatureGroupNameAttribute(string groupName) => GroupName = groupName; - - /// - /// Group name - /// - public string GroupName { get; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/LoggerExtensions.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/LoggerExtensions.cs deleted file mode 100644 index 53220e7b..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/LoggerExtensions.cs +++ /dev/null @@ -1,74 +0,0 @@ -namespace $safeprojectname$.Application; - -/// -/// The number identifiers for events in the microservices -/// -internal static class EventNumbers -{ - internal static readonly EventId UserRegistrationId = new EventId(9001, nameof(UserRegistrationId)); - internal static readonly EventId PostItemId = new EventId(9002, nameof(PostItemId)); -} - -/// -/// Event logging as ILogger extension. -/// Please see the video as the manual https://youtu.be/09EVKgHgwnM -/// -internal static class LoggerExtensions -{ - #region UserRegistration - - /// - /// EventItem register action event - /// - /// - /// - /// - internal static void MicroserviceUserRegistration(this ILogger source, string userName, Exception? exception = null) - { - switch (exception) - { - case null: - UserRegistrationExecute(source, userName, exception); - break; - default: - UserRegistrationFailedExecute(source, userName, exception); - break; - } - } - - private static readonly Action UserRegistrationExecute = - LoggerMessage.Define(LogLevel.Information, EventNumbers.UserRegistrationId, - "User {userName} successfully registred"); - - private static readonly Action UserRegistrationFailedExecute = - LoggerMessage.Define(LogLevel.Error, EventNumbers.UserRegistrationId, - "User {userName} registred failed"); - - #endregion - - #region PostItem - - internal static void MicroservicePostItem(this ILogger source, string entityName, Exception? exception = null) - { - switch (exception) - { - case null: - PostItemExecute(source, entityName, null); - break; - - default: - PostItemFailedExecute(source, entityName, exception); - break; - } - } - - private static readonly Action PostItemExecute = - LoggerMessage.Define(LogLevel.Information, EventNumbers.PostItemId, - "The {entityName} successfully saved"); - - private static readonly Action PostItemFailedExecute = - LoggerMessage.Define(LogLevel.Error, EventNumbers.PostItemId, - "The {entityName} saving failed"); - - #endregion -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/SERVICES/AccountService.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/SERVICES/AccountService.cs deleted file mode 100644 index 45904a6a..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/SERVICES/AccountService.cs +++ /dev/null @@ -1,278 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain.Base; -using $ext_projectname$.Infrastructure; -using $safeprojectname$.Definitions.Identity; -using $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.Microservices.Core.Extensions; -using Calabonga.Microservices.Core.Validators; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using OpenIddict.Abstractions; -using System.Security.Claims; - -namespace $safeprojectname$.Application.Services; - -/// -/// Account service -/// -public class AccountService : IAccountService -{ - private readonly IUnitOfWork _unitOfWork; - private readonly ILogger _logger; - private readonly ApplicationUserClaimsPrincipalFactory _claimsFactory; - private readonly IHttpContextAccessor _httpContext; - private readonly IMapper _mapper; - private readonly UserManager _userManager; - private readonly RoleManager _roleManager; - - public AccountService( - IUserStore userStore, - IOptions optionsAccessor, - IPasswordHasher passwordHasher, - IEnumerable> userValidators, - IEnumerable> passwordValidators, - ILookupNormalizer keyNormalizer, - IdentityErrorDescriber errors, - IServiceProvider services, - ILogger> loggerRole, - IEnumerable> roleValidators, - IUnitOfWork unitOfWork, - ILogger logger, - ILogger> loggerUser, - ApplicationUserClaimsPrincipalFactory claimsFactory, - IHttpContextAccessor httpContext, - IMapper mapper) - { - _unitOfWork = unitOfWork; - _logger = logger; - _claimsFactory = claimsFactory; - _httpContext = httpContext; - _mapper = mapper; - - // We need to created a custom instance for current service - // It'll help to use Transaction in the Unit Of Work - _userManager = new UserManager(userStore, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, loggerUser); - var roleStore = new RoleStore(_unitOfWork.DbContext); - _roleManager = new RoleManager(roleStore, roleValidators, keyNormalizer, errors, loggerRole); - } - - /// - public Guid GetCurrentUserId() - { - var identity = _httpContext.HttpContext?.User.Identity; - var identitySub = identity?.GetSubjectId(); - return identitySub?.ToGuid() ?? Guid.Empty; - } - - /// - /// Returns instance after successful registration - /// - /// - /// - /// - public async Task> RegisterAsync(RegisterViewModel model, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var user = _mapper.Map(model); - await using var transaction = await _unitOfWork.BeginTransactionAsync(); - var result = await _userManager.CreateAsync(user, model.Password); - const string role = AppData.ManagerRoleName; - - if (result.Succeeded) - { - if (await _roleManager.FindByNameAsync(role) == null) - { - operation.Exception = new MicroserviceUserNotFoundException(); - operation.AddError(AppData.Exceptions.UserNotFoundException); - return await Task.FromResult(operation); - } - - await _userManager.AddToRoleAsync(user, role); - - var profile = _mapper.Map(model); - var profileRepository = _unitOfWork.GetRepository(); - - await profileRepository.InsertAsync(profile, cancellationToken); - await _unitOfWork.SaveChangesAsync(); - if (_unitOfWork.LastSaveChangesResult.IsOk) - { - var principal = await _claimsFactory.CreateAsync(user); - operation.Result = _mapper.Map(principal.Identity); - operation.AddSuccess(AppData.Messages.UserSuccessfullyRegistered); - _logger.LogInformation(operation.GetMetadataMessages()); - await transaction.CommitAsync(cancellationToken); - _logger.MicroserviceUserRegistration(model.Email); - return await Task.FromResult(operation); - } - } - var errors = result.Errors.Select(x => $"{x.Code}: {x.Description}"); - operation.AddError(string.Join(", ", errors)); - operation.Exception = _unitOfWork.LastSaveChangesResult.Exception; - await transaction.RollbackAsync(cancellationToken); - _logger.MicroserviceUserRegistration(model.Email, operation.Exception); - return await Task.FromResult(operation); - } - - /// - /// Returns user profile - /// - /// - /// - public async Task> GetProfileByIdAsync(string identifier) - { - var operation = OperationResult.CreateResult(); - var claimsPrincipal = await GetPrincipalByIdAsync(identifier); - operation.Result = _mapper.Map(claimsPrincipal.Identity); - return await Task.FromResult(operation); - } - - /// - /// Returns user profile - /// - /// - /// - public async Task> GetProfileByEmailAsync(string email) - { - var operation = OperationResult.CreateResult(); - var claimsPrincipal = await GetPrincipalByEmailAsync(email); - operation.Result = _mapper.Map(claimsPrincipal.Identity); - return await Task.FromResult(operation); - } - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - /// - public async Task GetPrincipalByIdAsync(string identifier) - { - if (string.IsNullOrEmpty(identifier)) - { - throw new MicroserviceException(); - } - var userManager = _userManager; - var user = await userManager.FindByIdAsync(identifier); - if (user == null) - { - throw new MicroserviceUserNotFoundException(); - } - - var defaultClaims = await _claimsFactory.CreateAsync(user); - return defaultClaims; - } - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - /// - public async Task GetPrincipalByEmailAsync(string email) - { - if (string.IsNullOrEmpty(email)) - { - throw new MicroserviceException(); - } - var userManager = _userManager; - var user = await userManager.FindByEmailAsync(email); - if (user == null) - { - throw new MicroserviceUserNotFoundException(); - } - - var defaultClaims = await _claimsFactory.CreateAsync(user); - return defaultClaims; - } - - /// - /// Returns user by his identifier - /// - /// - /// - public Task GetByIdAsync(Guid id) - { - var userManager = _userManager; - return userManager.FindByIdAsync(id.ToString()); - } - - /// - /// Returns current user account information or null when user does not logged in - /// - /// - public async Task GetCurrentUserAsync() - { - var userManager = _userManager; - var userId = GetCurrentUserId().ToString(); - var user = await userManager.FindByIdAsync(userId); - return user; - } - - /// - public async Task> GetUsersByEmailsAsync(IEnumerable emails) - { - var userManager = _userManager; - var result = new List(); - foreach (var email in emails) - { - var user = await userManager.FindByEmailAsync(email); - if (user != null && !result.Contains(user)) - { - result.Add(user); - } - } - return await Task.FromResult(result); - } - - /// - /// Check roles for current user - /// - /// - /// - public async Task IsInRolesAsync(string[] roleNames) - { - var userManager = _userManager; - var userId = GetCurrentUserId().ToString(); - var user = await userManager.FindByIdAsync(userId); - if (user == null) - { - var resultUserNotFound = new PermissionValidationResult(); - resultUserNotFound.AddError(AppData.Exceptions.UnauthorizedException); - return await Task.FromResult(resultUserNotFound); - } - foreach (var roleName in roleNames) - { - var ok = await userManager.IsInRoleAsync(user, roleName); - if (ok) - { - return new PermissionValidationResult(); - } - } - - var result = new PermissionValidationResult(); - result.AddError(AppData.Exceptions.UnauthorizedException); - return result; - } - - /// - public async Task> GetUsersInRoleAsync(string roleName) - { - var userManager = _userManager; - return await userManager.GetUsersInRoleAsync(roleName); - } - - #region privates - - private async Task AddClaimsToUser(UserManager userManager, ApplicationUser user, string role) - { - await userManager.AddClaimAsync(user, new Claim(OpenIddictConstants.Claims.Name, user.UserName)); - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.GivenName, user.FirstName ?? "John")); - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.Surname, user.LastName?? "Doe")); - await userManager.AddClaimAsync(user, new Claim(OpenIddictConstants.Claims.Email, user.Email)); - await userManager.AddClaimAsync(user, new Claim(OpenIddictConstants.Claims.Role, role)); - } - - #endregion -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/SERVICES/IAccountService.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/SERVICES/IAccountService.cs deleted file mode 100644 index 17b65d05..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/SERVICES/IAccountService.cs +++ /dev/null @@ -1,89 +0,0 @@ -using $ext_projectname$.Infrastructure; -using $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.Microservices.Core.Validators; -using Calabonga.OperationResults; -using System.Security.Claims; - -namespace $safeprojectname$.Application.Services; - -/// -/// Represent interface for account management -/// -public interface IAccountService -{ - /// - /// Returns a collection of the by emails - /// - /// - /// - Task> GetUsersByEmailsAsync(IEnumerable emails); - - /// - /// Get User Id from HttpContext - /// - /// - Guid GetCurrentUserId(); - - /// - /// Returns instance after successful registration - /// - /// - /// - /// - Task> RegisterAsync(RegisterViewModel model, CancellationToken cancellationToken); - - /// - /// Returns user profile - /// - /// - /// - Task> GetProfileByIdAsync(string identifier); - - /// - /// Returns user profile - /// - /// - /// - Task> GetProfileByEmailAsync(string email); - - /// - /// Returns User by user identifier - /// - /// - /// - Task GetByIdAsync(Guid id); - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - /// - Task GetPrincipalByIdAsync(string identifier); - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - /// - Task GetPrincipalByEmailAsync(string email); - - /// - /// Returns current user account information or null when user does not logged in - /// - /// - Task GetCurrentUserAsync(); - - /// - /// Check roles for current user - /// - /// - /// - Task IsInRolesAsync(string[] roleNames); - - /// - /// Returns all system administrators registered in the system - /// - /// - /// - Task> GetUsersInRoleAsync(string roleName); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj deleted file mode 100644 index 481e8b62..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj +++ /dev/null @@ -1,44 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/COMMON/CommonDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/COMMON/CommonDefinition.cs deleted file mode 100644 index 1e4aebab..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/COMMON/CommonDefinition.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace $safeprojectname$.Definitions.Common; - -/// -/// AspNetCore common configuration -/// -public class CommonDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddLocalization(); - services.AddHttpContextAccessor(); - services.AddResponseCaching(); - services.AddMemoryCache(); - - services.AddMvc(); - services.AddRazorPages(); - } - - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) - { - app.UseHttpsRedirection(); - app.MapRazorPages(); - app.MapDefaultControllerRoute(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/CORS/CorsDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/CORS/CorsDefinition.cs deleted file mode 100644 index 96e4d29f..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/CORS/CorsDefinition.cs +++ /dev/null @@ -1,47 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$.Definitions.Cors; - -/// -/// Cors configurations -/// -public class CorsDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - var origins = builder.Configuration.GetSection("Cors")?.GetSection("Origins")?.Value?.Split(','); - services.AddCors(options => - { - options.AddPolicy(AppData.PolicyName, policyBuilder => - { - policyBuilder.AllowAnyHeader(); - policyBuilder.AllowAnyMethod(); - if (origins is not {Length: > 0}) - { - return; - } - - if (origins.Contains("*")) - { - policyBuilder.AllowAnyHeader(); - policyBuilder.AllowAnyMethod(); - policyBuilder.SetIsOriginAllowed(host => true); - policyBuilder.AllowCredentials(); - } - else - { - foreach (var origin in origins) - { - policyBuilder.WithOrigins(origin); - } - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DATASEEDING/DataSeedingDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DATASEEDING/DataSeedingDefinition.cs deleted file mode 100644 index ce8299e6..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DATASEEDING/DataSeedingDefinition.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure.DatabaseInitialization; - -namespace $safeprojectname$.Definitions.DataSeeding; - -/// -/// Seeding DbContext for default data for EntityFrameworkCore -/// -public class DataSeedingDefinition : AppDefinition -{ - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) - { - DatabaseInitializer.SeedUsers(app.Services); - DatabaseInitializer.SeedEvents(app.Services); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DBCONTEXT/DbContextDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DBCONTEXT/DbContextDefinition.cs deleted file mode 100644 index 750a7967..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DBCONTEXT/DbContextDefinition.cs +++ /dev/null @@ -1,65 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using $safeprojectname$.Definitions.Identity; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using OpenIddict.Abstractions; - -namespace $safeprojectname$.Definitions.DbContext; - -/// -/// ASP.NET Core services registration and configurations -/// -public class DbContextDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddDbContext(config => - { - // UseInMemoryDatabase - This for demo purposes only! - // Should uninstall package "Microsoft.EntityFrameworkCore.InMemory" and install what you need. - // For example: "Microsoft.EntityFrameworkCore.SqlServer" - config.UseInMemoryDatabase("DEMO-PURPOSES-ONLY"); - - // uncomment line below to use UseSqlServer(). Don't forget setup connection string in appSettings.json - //config.UseSqlServer(configuration.GetConnectionString(nameof(ApplicationDbContext))); - - // Register the entity sets needed by OpenIddict. - // Note: use the generic overload if you need to replace the default OpenIddict entities. - config.UseOpenIddict(); - }); - - - services.Configure(options => - { - options.ClaimsIdentity.UserNameClaimType = OpenIddictConstants.Claims.Name; - options.ClaimsIdentity.UserIdClaimType = OpenIddictConstants.Claims.Subject; - options.ClaimsIdentity.RoleClaimType = OpenIddictConstants.Claims.Role; - options.ClaimsIdentity.EmailClaimType = OpenIddictConstants.Claims.Email; - // configure more options if you need - }); - - services.AddIdentity(options => - { - options.Password.RequireDigit = false; - options.Password.RequireLowercase = false; - options.Password.RequireNonAlphanumeric = false; - options.Password.RequiredLength = 8; - options.Password.RequireUppercase = false; - }) - .AddSignInManager() - .AddEntityFrameworkStores() - .AddUserStore() - .AddRoleStore() - .AddUserManager>() - .AddClaimsPrincipalFactory() - .AddDefaultTokenProviders(); - - services.AddTransient(); - } -} diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DEPENDENCYCONTAINER/ContainerDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DEPENDENCYCONTAINER/ContainerDefinition.cs deleted file mode 100644 index 83819504..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DEPENDENCYCONTAINER/ContainerDefinition.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Application.Services; -using $safeprojectname$.Definitions.Identity; - -namespace $safeprojectname$.Definitions.DependencyContainer; - -/// -/// Dependency container definition -/// -public class ContainerDefinition: AppDefinition -{ - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddTransient(); - services.AddTransient(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/ERRORHANDLING/ErrorHandlingDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/ERRORHANDLING/ErrorHandlingDefinition.cs deleted file mode 100644 index e94337b5..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/ERRORHANDLING/ErrorHandlingDefinition.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using FluentValidation; -using Microsoft.AspNetCore.Diagnostics; -using Serilog; -using System.Text.Json; - -namespace $safeprojectname$.Definitions.ErrorHandling; - -/// -/// Custom Error handling -/// -public class ErrorHandlingDefinition : AppDefinition -{ - /// - /// Configure application for current application - /// - /// - /// - public override void ConfigureApplication(WebApplication app) => - app.UseExceptionHandler(error => error.Run(async context => - { - - context.Response.ContentType = "application/json"; - var contextFeature = context.Features.Get(); - if (contextFeature is not null) - { - // handling validation errors - if (contextFeature.Error is ValidationException failures) - { - await context.Response.WriteAsync(JsonSerializer.Serialize(failures.Errors)); - context.Response.StatusCode = StatusCodes.Status400BadRequest; - return; - } - - // handling all another errors - Log.Error($"Something went wrong in the {contextFeature.Error}"); - context.Response.StatusCode = StatusCodes.Status500InternalServerError; - - if (app.Environment.IsDevelopment()) - { - await context.Response.WriteAsync($"INTERNAL SERVER ERROR: {contextFeature.Error}"); - } - else - { - await context.Response.WriteAsync("INTERNAL SERVER ERROR. PLEASE TRY AGAIN LATER"); - } - } - })); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/ETAGGENERATOR/ETagGeneratorDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/ETAGGENERATOR/ETagGeneratorDefinition.cs deleted file mode 100644 index f2b997e2..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/ETAGGENERATOR/ETagGeneratorDefinition.cs +++ /dev/null @@ -1,71 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Net.Http.Headers; -using System.Diagnostics; -using System.Security.Cryptography; - -namespace $safeprojectname$.Definitions.ETagGenerator; - -/// -/// ETag Generator -/// -[DebuggerStepThrough] -public class ETagGeneratorDefinition : AppDefinition -{ - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) => - app.Use(async (context, next) => - { - var response = context.Response; - var originalStream = response.Body; - - await using var ms = new MemoryStream(); - response.Body = ms; - - await next(context); - - if (IsEtagSupported(response)) - { - var checksum = CalculateChecksum(ms); - - response.Headers[HeaderNames.ETag] = checksum; - - if (context.Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var etag) && checksum == etag) - { - response.StatusCode = StatusCodes.Status304NotModified; - return; - } - } - - ms.Position = 0; - await ms.CopyToAsync(originalStream); - }); - - - private static bool IsEtagSupported(HttpResponse response) - { - if (response.StatusCode != StatusCodes.Status200OK) - { - return false; - } - - // The 100kb length limit is not based in science. Feel free to change - if (response.Body.Length > 100 * 1024) - { - return false; - } - - return !response.Headers.ContainsKey(HeaderNames.ETag); - } - - private static string CalculateChecksum(MemoryStream ms) - { - using var algorithm = SHA1.Create(); - ms.Position = 0; - var bytes = algorithm.ComputeHash(ms); - return $"\"{WebEncoders.Base64UrlEncode(bytes)}\""; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/FLUENTVALIDATING/FluentValidationDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/FLUENTVALIDATING/FluentValidationDefinition.cs deleted file mode 100644 index da74f663..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/FLUENTVALIDATING/FluentValidationDefinition.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using FluentValidation; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Definitions.FluentValidating; - -/// -/// FluentValidation registration as Application definition -/// -public class FluentValidationDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.Configure(options => - { - options.SuppressModelStateInvalidFilter = true; - }); - - services.AddValidatorsFromAssembly(typeof(Program).Assembly); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/ApplicationUserClaimsPrincipalFactory.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/ApplicationUserClaimsPrincipalFactory.cs deleted file mode 100644 index bd572a2b..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/ApplicationUserClaimsPrincipalFactory.cs +++ /dev/null @@ -1,69 +0,0 @@ -using $ext_projectname$.Infrastructure; -using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.Options; -using OpenIddict.Abstractions; -using System.Security.Claims; - -namespace $safeprojectname$.Definitions.Identity; - -/// -/// User Claims Principal Factory override from Microsoft Identity framework -/// -public class ApplicationUserClaimsPrincipalFactory : UserClaimsPrincipalFactory -{ - /// - public ApplicationUserClaimsPrincipalFactory( - UserManager userManager, - RoleManager roleManager, - IOptions optionsAccessor) - : base(userManager, roleManager, optionsAccessor) { } - - /// - /// Creates a from an user asynchronously. - /// - /// The user to create a from. - /// The that represents the asynchronous creation operation, containing the created . - public override async Task CreateAsync(ApplicationUser user) - { - var principal = await base.CreateAsync(user); - - - - if (user.ApplicationUserProfile?.Permissions != null) - { - var permissions = user.ApplicationUserProfile.Permissions.ToList(); - if (permissions.Any()) - { - permissions.ForEach(x => ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim(x.PolicyName, nameof(x.PolicyName).ToLower()))); - } - } - - ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim("framework", "nimble")); - - if (!string.IsNullOrWhiteSpace(user.UserName)) - { - ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim(ClaimTypes.Name, user.UserName)); - } - - if (!string.IsNullOrWhiteSpace(user.FirstName)) - { - ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName)); - } - - if (!string.IsNullOrWhiteSpace(user.LastName)) - { - ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim(ClaimTypes.Surname, user.LastName)); - } - - //// For this sample, just include all claims in all token types. - //// In reality, claims' destinations would probably differ by token type and depending on the scopes requested. - //// In our case (demo) we're using OpenIddictConstants.Destinations.AccessToken and OpenIddictConstants.Destinations.IdentityToken - foreach (var principalClaim in principal.Claims) - { - principalClaim.SetDestinations(OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken); - } - - return principal; - } - -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/AuthorizationDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/AuthorizationDefinition.cs deleted file mode 100644 index dbb33023..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/AuthorizationDefinition.cs +++ /dev/null @@ -1,55 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Definitions.OpenIddict; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Authorization; - -namespace $safeprojectname$.Definitions.Identity; - -/// -/// Authorization Policy registration -/// -public class AuthorizationDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - - services - .AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; - }) - .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => - { - options.LoginPath = "/connect/login"; - }); - - services.AddAuthorization(); - services.AddSingleton(); - services.AddSingleton(); - } - - /// - /// Configure application for current application - /// - /// - /// - public override void ConfigureApplication(WebApplication app) - { - app.UseHttpsRedirection(); - app.UseRouting(); - app.UseCors("CorsPolicy"); - app.UseAuthentication(); - app.UseAuthorization(); - - // registering UserIdentity helper as singleton - UserIdentity.Instance.Configure(app.Services.GetService()!); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/UserIdentity.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/UserIdentity.cs deleted file mode 100644 index 9b7b2756..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/UserIdentity.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Calabonga.Microservices.Core.Exceptions; -using System.Security.Claims; -using System.Security.Principal; - -namespace $safeprojectname$.Definitions.Identity; - -/// -/// Identity helper for Requests operations -/// -public sealed class UserIdentity -{ - private UserIdentity() { } - - public static UserIdentity Instance => Lazy.Value; - - public void Configure(IHttpContextAccessor httpContextAccessor) - { - ContextAccessor = httpContextAccessor ?? throw new MicroserviceArgumentNullException(nameof(IHttpContextAccessor)); - IsInitialized = true; - } - - public IIdentity? User - { - get - { - if (IsInitialized) - { - return ContextAccessor.HttpContext!.User.Identity != null - && ContextAccessor.HttpContext != null - && ContextAccessor.HttpContext.User.Identity.IsAuthenticated - ? ContextAccessor.HttpContext.User.Identity - : null; - } - throw new MicroserviceArgumentNullException($"{nameof(UserIdentity)} has not been initialized. Please use {nameof(UserIdentity)}.Instance.Configure(...) in Configure Application method in Startup.cs"); - } - } - - public IEnumerable Claims - { - get - { - if (User != null) - { - return ContextAccessor.HttpContext!.User.Claims; - } - return Enumerable.Empty(); - } - } - - private static readonly Lazy Lazy = new Lazy(() => new UserIdentity()); - - private bool IsInitialized { get; set; } - - private static IHttpContextAccessor ContextAccessor { get; set; } = null!; - -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MAPPING/AutomapperDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MAPPING/AutomapperDefinition.cs deleted file mode 100644 index 78be81d0..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MAPPING/AutomapperDefinition.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace $safeprojectname$.Definitions.Mapping; - -/// -/// Register Automapper as application definition -/// -public class AutomapperDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - => services.AddAutoMapper(typeof(Program)); - - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) - { - var mapper = app.Services.GetRequiredService(); - if (app.Environment.IsDevelopment()) - { - // validate Mapper Configuration - mapper.AssertConfigurationIsValid(); - } - else - { - mapper.CompileMappings(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MAPPING/PagedListConverter.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MAPPING/PagedListConverter.cs deleted file mode 100644 index 82b4c28a..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MAPPING/PagedListConverter.cs +++ /dev/null @@ -1,23 +0,0 @@ -using AutoMapper; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Definitions.Mapping; - -/// -/// Generic converter for IPagedList collections -/// -/// -/// -public class PagedListConverter : ITypeConverter, IPagedList> -{ - /// Performs conversion from source to destination type - /// Source object - /// Destination object - /// Resolution context - /// Destination object - public IPagedList Convert(IPagedList source, IPagedList destination, ResolutionContext context) => - // ReSharper disable once ConditionIsAlwaysTrueOrFalse - source == null - ? PagedList.Empty() - : PagedList.From(source, items => context.Mapper.Map>(items)); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/BASE/UnitOfWorkTransactionBehavior.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/BASE/UnitOfWorkTransactionBehavior.cs deleted file mode 100644 index b588a961..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/BASE/UnitOfWorkTransactionBehavior.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Definitions.Mediator.Base; - -/// -/// Transaction Behavior -/// -/// -/// -public class TransactionBehavior : IPipelineBehavior - where TRequest : IRequest -{ - private readonly IUnitOfWork _unitOfWork; - - public TransactionBehavior(IUnitOfWork unitOfWork) => _unitOfWork = unitOfWork; - - - public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) - { - await using var transaction = await _unitOfWork.BeginTransactionAsync(); - try - { - var response = await next(); - await transaction.CommitAsync(cancellationToken); - return response; - } - catch (Exception) - { - await transaction.RollbackAsync(cancellationToken); - throw; - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/EventItemPostTransactionBehavior.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/EventItemPostTransactionBehavior.cs deleted file mode 100644 index 0d7f292e..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/EventItemPostTransactionBehavior.cs +++ /dev/null @@ -1,12 +0,0 @@ -using $safeprojectname$.Definitions.Mediator.Base; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Definitions.Mediator; - -public class EventItemPostTransactionBehavior : TransactionBehavior>, OperationResult> -{ - public EventItemPostTransactionBehavior(IUnitOfWork unitOfWork) : base(unitOfWork) { } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/MediatorDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/MediatorDefinition.cs deleted file mode 100644 index 06ec2863..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/MediatorDefinition.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Application; -using MediatR; -using System.Reflection; - -namespace $safeprojectname$.Definitions.Mediator; - -/// -/// Register Mediator as application definition -/// -public class MediatorDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>)); - services.AddMediatR(Assembly.GetExecutingAssembly()); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AppPermissionHandler.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AppPermissionHandler.cs deleted file mode 100644 index b550bbe8..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AppPermissionHandler.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Calabonga.Microservices.Core; -using Microsoft.AspNetCore.Authorization; -using System.Security.Claims; - -namespace $safeprojectname$.Definitions.OpenIddict; - -/// -/// Permission handler for custom authorization implementations -/// -public class AppPermissionHandler : AuthorizationHandler -{ - /// - protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) - { - if (context.User.Identity is null) - { - return Task.CompletedTask; - } - - var identity = (ClaimsIdentity)context.User.Identity; - var claim = ClaimsHelper.GetValue(identity, requirement.PermissionName); - if (claim == null) - { - return Task.CompletedTask; - } - - context.Succeed(requirement); - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AuthData.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AuthData.cs deleted file mode 100644 index c29501d9..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AuthData.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Microsoft.AspNetCore.Authentication.Cookies; -using OpenIddict.Validation.AspNetCore; - -namespace $safeprojectname$.Definitions.OpenIddict; - -public static class AuthData -{ - public const string AuthSchemes = CookieAuthenticationDefaults.AuthenticationScheme + "," + OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme; -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AuthorizationPolicyProvider.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AuthorizationPolicyProvider.cs deleted file mode 100644 index 47dd81f1..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AuthorizationPolicyProvider.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.Options; - -namespace $safeprojectname$.Definitions.OpenIddict; - -/// -/// Policy provider -/// -public class AuthorizationPolicyProvider : DefaultAuthorizationPolicyProvider -{ - private readonly AuthorizationOptions _options; - - /// - public AuthorizationPolicyProvider(IOptions options) : base(options) => _options = options.Value; - - /// - public override async Task GetPolicyAsync(string policyName) - { - var policyExists = await base.GetPolicyAsync(policyName); - if (policyExists != null) - { - return policyExists; - } - - policyExists = new AuthorizationPolicyBuilder().AddRequirements(new PermissionRequirement(policyName)).Build(); - _options.AddPolicy(policyName, policyExists); - return policyExists; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/OpenIddictDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/OpenIddictDefinition.cs deleted file mode 100644 index e2b035a7..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/OpenIddictDefinition.cs +++ /dev/null @@ -1,123 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using $safeprojectname$.HostedServices; -using OpenIddict.Abstractions; - -namespace $safeprojectname$.Definitions.OpenIddict; - -public class OpenIddictDefinition : AppDefinition -{ - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddOpenIddict() - // Register the OpenIddict core components. - .AddCore(options => - { - // Configure OpenIddict to use the Entity Framework Core stores and models. - // Note: call ReplaceDefaultEntities() to replace the default entities. - options.UseEntityFrameworkCore() - .UseDbContext() - .ReplaceDefaultEntities(); - }) - - // Register the OpenIddict server components. - .AddServer(options => - { - // Note: the sample uses the code and refresh token flows but you can enable - // the other flows if you need to support implicit, password or client credentials. - // Supported flows are: - // => Authorization code flow - // => Client credentials flow - // => Device code flow - // => Implicit flow - // => Password flow - // => Refresh token flow - options - .AllowAuthorizationCodeFlow()//.RequireProofKeyForCodeExchange() - .AllowPasswordFlow() - .AllowClientCredentialsFlow() - .AllowRefreshTokenFlow(); - - // Using reference tokens means the actual access and refresh tokens - // are stored in the database and different tokens, referencing the actual - // tokens (in the db), are used in request headers. The actual tokens are not - // made public. - // => options.UseReferenceAccessTokens(); - // => options.UseReferenceRefreshTokens(); - - // Set the lifetime of your tokens - // => options.SetAccessTokenLifetime(TimeSpan.FromMinutes(30)); - // => options.SetRefreshTokenLifetime(TimeSpan.FromDays(7)); - - // Enable the token endpoint. - options - .SetAuthorizationEndpointUris("/connect/authorize") - .SetLogoutEndpointUris("/connect/logout") - .SetTokenEndpointUris("/connect/token") - .SetUserinfoEndpointUris("/connect/userinfo"); - - // Encryption and signing of tokens - options - .AddEphemeralEncryptionKey() // only for Developing mode - .AddEphemeralSigningKey() // only for Developing mode - .DisableAccessTokenEncryption(); // only for Developing mode - - // Mark the "email", "profile" and "roles" scopes as supported scopes. - options.RegisterScopes( - OpenIddictConstants.Scopes.Email, - OpenIddictConstants.Scopes.Profile, - OpenIddictConstants.Scopes.Roles, - "api", - "custom"); - - // Register the signing and encryption credentials. - options - .AddDevelopmentEncryptionCertificate() - .AddDevelopmentSigningCertificate(); - - // Register the ASP.NET Core host and configure the ASP.NET Core options. - options - .UseAspNetCore() - .EnableTokenEndpointPassthrough() - .EnableAuthorizationEndpointPassthrough(); - - //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); - //JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear(); - - //options.AddEventHandler(builder => - //{ - // builder.SetOrder(OpenIddictServerHandlers.GenerateIdentityModelRefreshToken.Descriptor.Order - 1) - // .AddFilter() - // .SetType(OpenIddictServerHandlerType.Custom) - // .UseInlineHandler(context => - // { - // context.RefreshTokenPrincipal = context.RefreshTokenPrincipal.Clone( - // claim => claim.Type is ( - // OpenIddictConstants.Claims.Private.AuthorizationId or - // OpenIddictConstants.Claims.Private.Presenter or - // OpenIddictConstants.Claims.Private.TokenId or - // OpenIddictConstants.Claims.Private.Scope or - // OpenIddictConstants.Claims.Subject or - // OpenIddictConstants.Claims.ExpiresAt - // ) - // ); - // return default; - // }); - //}); - }) - - // Register the OpenIddict validation components. - .AddValidation(options => - { - // Import the configuration from the local OpenIddict server instance. - options.UseLocalServer(); - - // Register the ASP.NET Core host. - options.UseAspNetCore(); - }); - - // Register the worker responsible for seeding the database. - // Note: in a real world application, this step should be part of a setup script. - services.AddHostedService(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/PermissionRequirement.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/PermissionRequirement.cs deleted file mode 100644 index 5c3d40c2..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/PermissionRequirement.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Microsoft.AspNetCore.Authorization; - -namespace $safeprojectname$.Definitions.OpenIddict; - -/// -/// Permission requirement for user or service authorization -/// -public class PermissionRequirement : IAuthorizationRequirement -{ - public PermissionRequirement(string permissionName) => PermissionName = permissionName; - - /// - /// Permission name - /// - public string PermissionName { get; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/SWAGGER/SwaggerDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/SWAGGER/SwaggerDefinition.cs deleted file mode 100644 index 4c2a310d..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/SWAGGER/SwaggerDefinition.cs +++ /dev/null @@ -1,121 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Domain.Base; -using $safeprojectname$.Application; -using Microsoft.AspNetCore.Mvc; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerUI; - -namespace $safeprojectname$.Definitions.Swagger; - -/// -/// Swagger definition for application -/// -public class SwaggerDefinition : AppDefinition -{ - - private const string _appVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - private const string _swaggerConfig = "/swagger/v1/swagger.json"; - - public override void ConfigureApplication(WebApplication app) - { - if (!app.Environment.IsDevelopment()) - { - return; - } - - var url = app.Services.GetRequiredService().GetValue("AuthServer:Url"); - - app.UseSwagger(); - app.UseSwaggerUI(settings => - { - settings.SwaggerEndpoint(_swaggerConfig, $"{AppData.ServiceName} v.{_appVersion}"); - settings.HeadContent = $"{ThisAssembly.Git.Branch.ToUpper()} {ThisAssembly.Git.Commit.ToUpper()}"; - settings.DocumentTitle = $"{AppData.ServiceName}"; - settings.DefaultModelExpandDepth(0); - settings.DefaultModelRendering(ModelRendering.Model); - settings.DefaultModelsExpandDepth(0); - settings.DocExpansion(DocExpansion.None); - settings.OAuthScopeSeparator(" "); - settings.OAuthClientId("client-id-code"); - settings.OAuthClientSecret("client-secret-code"); - settings.DisplayRequestDuration(); - settings.OAuthAppName(AppData.ServiceName); - settings.OAuth2RedirectUrl($"{url}/swagger/oauth2-redirect.html"); - }); - } - - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); - services.AddEndpointsApiExplorer(); - services.AddSwaggerGen(options => - { - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = AppData.ServiceName, - Version = _appVersion, - Description = AppData.ServiceDescription - }); - - options.ResolveConflictingActions(x => x.First()); - - options.TagActionsBy(api => - { - string tag; - if (api.ActionDescriptor is { } descriptor) - { - var attribute = descriptor.EndpointMetadata.OfType().FirstOrDefault(); - tag = attribute?.GroupName ?? descriptor.RouteValues["controller"] ?? "Untitled"; - } - else - { - tag = api.RelativePath!; - } - - var tags = new List(); - if (!string.IsNullOrEmpty(tag)) - { - tags.Add(tag); - } - return tags; - }); - - var url = builder.Configuration.GetSection("AuthServer").GetValue("Url"); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - AuthorizationCode = new OpenApiOAuthFlow - { - TokenUrl = new Uri($"{url}/connect/token", UriKind.Absolute), - AuthorizationUrl = new Uri($"{url}/connect/authorize", UriKind.Absolute), - Scopes = new Dictionary - { - { "api", "Default scope" } - }, - - } - } - }); - options.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "oauth2" - }, - In = ParameterLocation.Cookie, - Type = SecuritySchemeType.OAuth2 - - }, - new List() - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/UOW/UnitOfWorkDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/UOW/UnitOfWorkDefinition.cs deleted file mode 100644 index c399de03..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/UOW/UnitOfWorkDefinition.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Definitions.UoW; - -/// -/// Unit of Work registration as application definition -/// -public class UnitOfWorkDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - => services.AddUnitOfWork(); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemEndpoints.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemEndpoints.cs deleted file mode 100644 index 834110dd..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemEndpoints.cs +++ /dev/null @@ -1,59 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Application; -using $safeprojectname$.Definitions.OpenIddict; -using $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints; - -public class EventItemEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("/api/event-items/{id:guid}", LogGetById); - app.MapGet("/api/event-items/paged", LogGetPaged); - app.MapPost("/api/event-items/", PostLog); - app.MapPut("/api/event-items/{id:guid}", PutLog); - app.MapDelete("/api/event-items/{id:guid}", LogDelete); - } - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogGetById([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new GetEventItemByIdRequest(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogDelete([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new DeleteEventItemRequest(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task>> LogGetPaged([FromServices] IMediator mediator, int pageIndex, int pageSize, string? search, HttpContext context) - => await mediator.Send(new GetEventItemPagedRequest(pageIndex, pageSize, search), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PostLog([FromServices] IMediator mediator, EventItemCreateViewModel model, HttpContext context) - => await mediator.Send(new PostEventItemRequest(model), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PutLog([FromServices] IMediator mediator, Guid id, EventItemUpdateViewModel model, HttpContext context) - => await mediator.Send(new PutEventItemRequest(id, model), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemMapperConfiguration.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemMapperConfiguration.cs deleted file mode 100644 index 9fa595b9..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemMapperConfiguration.cs +++ /dev/null @@ -1,32 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Definitions.Mapping; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints; - -/// -/// Mapper Configuration for entity EventItem -/// -public class EventItemMapperConfiguration : Profile -{ - /// - public EventItemMapperConfiguration() - { - CreateMap() - .ForMember(x => x.Id, o => o.Ignore()); - - CreateMap(); - - CreateMap(); - - CreateMap() - .ForMember(x => x.CreatedAt, o => o.Ignore()) - .ForMember(x => x.ThreadId, o => o.Ignore()) - .ForMember(x => x.ExceptionMessage, o => o.Ignore()); - - CreateMap, IPagedList>() - .ConvertUsing>(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemValidator.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemValidator.cs deleted file mode 100644 index 46f08298..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemValidator.cs +++ /dev/null @@ -1,21 +0,0 @@ -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using FluentValidation; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints; - -/// -/// RegisterViewModel Validator -/// -public class EventItemCreateRequestValidator : AbstractValidator -{ - public EventItemCreateRequestValidator() => RuleSet("default", () => - { - RuleFor(x => x.CreatedAt).NotNull(); - RuleFor(x => x.Message).NotEmpty().NotNull().MaximumLength(4000); - RuleFor(x => x.Level).NotEmpty().NotNull().MaximumLength(50); - RuleFor(x => x.Logger).NotNull().NotEmpty().MaximumLength(255); - - RuleFor(x => x.ThreadId).MaximumLength(50); - RuleFor(x => x.ExceptionMessage).MaximumLength(4000); - }); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/DeleteEventItem.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/DeleteEventItem.cs deleted file mode 100644 index f1ab914b..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/DeleteEventItem.cs +++ /dev/null @@ -1,55 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem delete -/// -public record DeleteEventItemRequest(Guid Id) : IRequest>; - -/// -/// Request: EventItem delete -/// -public class DeleteEventItemRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - - private readonly IMapper _mapper; - - public DeleteEventItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(DeleteEventItemRequest request, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.FindAsync(request.Id); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException("Entity not found")); - return operation; - } - repository.Delete(entity); - await _unitOfWork.SaveChangesAsync(); - if (_unitOfWork.LastSaveChangesResult.IsOk) - { - operation.Result = _mapper.Map(entity); - return operation; - } - operation.AddError(_unitOfWork.LastSaveChangesResult.Exception); - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemById.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemById.cs deleted file mode 100644 index 1b4bd9a1..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemById.cs +++ /dev/null @@ -1,48 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request for EventItem by Identifier -/// -public record GetEventItemByIdRequest(Guid Id) : IRequest>; - -/// -/// Response for Request for EventItem by Identifier -/// -public class GetEventItemByIdRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public GetEventItemByIdRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request getting log by identifier - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(GetEventItemByIdRequest request, CancellationToken cancellationToken) - { - var id = request.Id; - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entityWithoutIncludes = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == id); - if (entityWithoutIncludes == null) - { - operation.AddError(new MicroserviceNotFoundException($"Entity with identifier {id} not found")); - return operation; - } - operation.Result = _mapper.Map(entityWithoutIncludes); - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemPaged.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemPaged.cs deleted file mode 100644 index 85565bca..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemPaged.cs +++ /dev/null @@ -1,75 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.PredicatesBuilder; -using Calabonga.UnitOfWork; -using MediatR; -using System.Linq.Expressions; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request for paged list of EventItems -/// -public record GetEventItemPagedRequest(int PageIndex, int PageSize, string? Search) : IRequest>>; - -/// -/// Request for paged list of EventItems -/// -public class GetEventItemPagedRequestHandler : IRequestHandler>> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public GetEventItemPagedRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task>> Handle(GetEventItemPagedRequest request, - CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult>(); - var predicate = GetPredicate(request.Search); - var pagedList = await _unitOfWork.GetRepository() - .GetPagedListAsync( - predicate: predicate, - pageIndex: request.PageIndex, - pageSize: request.PageSize, - cancellationToken: cancellationToken); - - if (pagedList == null) - { - operation.Result = PagedList.Empty(); - operation.AddWarning("Response does not return the result for pagination."); - return operation; - } - - if (pagedList.PageIndex > pagedList.TotalPages) - { - pagedList = await _unitOfWork.GetRepository() - .GetPagedListAsync( - pageIndex: 0, - pageSize: request.PageSize, cancellationToken: cancellationToken); - } - - operation.Result = _mapper.Map>(pagedList); - return operation; - } - - private Expression> GetPredicate(string? search) - { - var predicate = PredicateBuilder.True(); - if (search is null) - { - return predicate; - } - - predicate = predicate.And(x => x.Message.Contains(search)); - predicate = predicate.Or(x => x.Logger.Contains(search)); - predicate = predicate.Or(x => x.Level.Contains(search)); - return predicate; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/PostEventItem.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/PostEventItem.cs deleted file mode 100644 index 511190f1..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/PostEventItem.cs +++ /dev/null @@ -1,63 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem creation -/// -public record PostEventItemRequest(EventItemCreateViewModel Model) : IRequest>; - -/// -/// Request: EventItem creation -/// -public class PostEventItemRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - private readonly ILogger _logger; - - - public PostEventItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper, ILogger logger) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - _logger = logger; - } - - public async Task> Handle(PostEventItemRequest eventItemRequest, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - - var entity = _mapper.Map(eventItemRequest.Model); - if (entity == null) - { - operation.AddError(new MicroserviceUnauthorizedException(AppContracts.Exceptions.MappingException)); - return operation; - } - - await _unitOfWork.GetRepository().InsertAsync(entity, cancellationToken); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - - var mapped = _mapper.Map(entity); - - operation.Result = mapped; - operation.AddSuccess("Successfully created"); - return operation; - } - - operation.AddError(lastResult.Exception ?? new ApplicationException("Something went wrong")); - - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/UpdateEventItem.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/UpdateEventItem.cs deleted file mode 100644 index 31c631e1..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/UpdateEventItem.cs +++ /dev/null @@ -1,59 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem edit -/// -public record PutEventItemRequest(Guid Id, EventItemUpdateViewModel Model) : IRequest>; - -/// -/// Request: EventItem creation -/// -public class PutEventItemRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public PutEventItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task> Handle(PutEventItemRequest eventItemRequest, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == eventItemRequest.Id, disableTracking: false); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException(AppContracts.Exceptions.NotFoundException)); - return operation; - } - - _mapper.Map(eventItemRequest.Model, entity); - - repository.Update(entity); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("Successfully updated"); - return operation; - } - - operation.AddError(lastResult.Exception ?? new ApplicationException("Something went wrong")); - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemCreateViewModel.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemCreateViewModel.cs deleted file mode 100644 index 054466de..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemCreateViewModel.cs +++ /dev/null @@ -1,36 +0,0 @@ -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemCreateViewModel : IViewModel -{ - /// - /// EventItem Created At - /// - public DateTime CreatedAt { get; set; } - - /// - /// Service name or provider - /// - public string Logger { get; set; } = null!; - - /// - /// EventItem level for logging. See - /// - public string Level { get; set; } = null!; - - /// - /// EventItem Message - /// - public string Message { get; set; } = null!; - - /// - /// Thread identifier - /// - public string? ThreadId { get; set; } - - /// - /// Exception message - /// - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemUpdateViewModel.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemUpdateViewModel.cs deleted file mode 100644 index 6dc45417..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemUpdateViewModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemUpdateViewModel : ViewModelBase -{ - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemViewModel.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemViewModel.cs deleted file mode 100644 index 39211dbc..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemViewModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemViewModel -{ - public Guid Id { get; set; } - - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; - - public string? ThreadId { get; set; } - - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesDefinition.cs deleted file mode 100644 index 1c8f3b0d..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesDefinition.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Application; -using $safeprojectname$.Definitions.OpenIddict; -using $safeprojectname$.Endpoints.ProfileEndpoints.Queries; -using $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.OperationResults; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints; - -public class ProfilesDefinition : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("/api/profiles/get-roles", GetRoles); - app.MapPost("/api/profiles/register", RegisterAccount); - } - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("Profiles")] - private async Task GetRoles([FromServices] IMediator mediator, HttpContext context) - => await mediator.Send(new GetRolesRequest(), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [FeatureGroupName("Profiles")] - private async Task> RegisterAccount([FromServices] IMediator mediator, RegisterViewModel model, HttpContext context) - => await mediator.Send(new RegisterAccountRequest(model), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesMapperConfiguration.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesMapperConfiguration.cs deleted file mode 100644 index 2a7ee133..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesMapperConfiguration.cs +++ /dev/null @@ -1,56 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Infrastructure; -using $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using System.Security.Claims; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints; - -/// -/// Mapper Configuration for entity ApplicationUser -/// -public class ProfilesMapperConfiguration : Profile -{ - /// - public ProfilesMapperConfiguration() - { - CreateMap() - .ForMember(x => x.UserName, o => o.MapFrom(p => p.Email)) - .ForMember(x => x.Email, o => o.MapFrom(p => p.Email)) - .ForMember(x => x.EmailConfirmed, o => o.MapFrom(src => true)) - .ForMember(x => x.FirstName, o => o.MapFrom(p => p.FirstName)) - .ForMember(x => x.LastName, o => o.MapFrom(p => p.LastName)) - .ForMember(x => x.PhoneNumberConfirmed, o => o.MapFrom(src => true)) - .ForMember(x => x.ApplicationUserProfileId, o => o.Ignore()) - .ForMember(x => x.ApplicationUserProfile, o => o.Ignore()) - .ForMember(x => x.Id, o => o.Ignore()) - .ForMember(x => x.NormalizedUserName, o => o.Ignore()) - .ForMember(x => x.NormalizedEmail, o => o.Ignore()) - .ForMember(x => x.PasswordHash, o => o.Ignore()) - .ForMember(x => x.SecurityStamp, o => o.Ignore()) - .ForMember(x => x.ConcurrencyStamp, o => o.Ignore()) - .ForMember(x => x.PhoneNumber, o => o.Ignore()) - .ForMember(x => x.TwoFactorEnabled, o => o.Ignore()) - .ForMember(x => x.LockoutEnd, o => o.Ignore()) - .ForMember(x => x.LockoutEnabled, o => o.Ignore()) - .ForMember(x => x.AccessFailedCount, o => o.Ignore()); - - CreateMap() - .ForMember(x => x.Id, o => o.Ignore()) - .ForMember(x => x.Permissions, o => o.Ignore()) - .ForMember(x => x.ApplicationUser, o => o.Ignore()) - .ForMember(x => x.CreatedAt, o => o.Ignore()) - .ForMember(x => x.CreatedBy, o => o.Ignore()) - .ForMember(x => x.UpdatedAt, o => o.Ignore()) - .ForMember(x => x.UpdatedBy, o => o.Ignore()); - - CreateMap() - .ForMember(x => x.Id, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.NameIdentifier))) - .ForMember(x => x.PositionName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Actor))) - .ForMember(x => x.FirstName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.GivenName))) - .ForMember(x => x.LastName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Surname))) - .ForMember(x => x.Roles, o => o.MapFrom(claims => ClaimsHelper.GetValues(claims, ClaimTypes.Role))) - .ForMember(x => x.Email, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Name))) - .ForMember(x => x.PhoneNumber, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.MobilePhone))); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/GetRoles.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/GetRoles.cs deleted file mode 100644 index 9258993c..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/GetRoles.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Calabonga.Microservices.Core; -using MediatR; -using System.Security.Claims; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints.Queries; - -/// -/// Request: Returns user roles -/// -public record GetRolesRequest : IRequest; - -public class GetRolesRequestHandler : RequestHandler -{ - private readonly IHttpContextAccessor _httpContextAccessor; - - public GetRolesRequestHandler(IHttpContextAccessor httpContextAccessor) => _httpContextAccessor = httpContextAccessor; - - protected override string Handle(GetRolesRequest request) - { - var user = _httpContextAccessor.HttpContext!.User; - var roles = ClaimsHelper.GetValues((ClaimsIdentity)user.Identity!, "role"); - return $"Current user ({user.Identity!.Name}) have following roles: {string.Join("|", roles)}"; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/RegisterAccount.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/RegisterAccount.cs deleted file mode 100644 index dbfe0668..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/RegisterAccount.cs +++ /dev/null @@ -1,30 +0,0 @@ -using $safeprojectname$.Application.Services; -using $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.OperationResults; -using MediatR; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints.Queries; - -/// -/// Request: Register new account -/// -public class RegisterAccountRequest : IRequest> -{ - public RegisterAccountRequest(RegisterViewModel model) => Model = model; - - public RegisterViewModel Model { get; } -} - -/// -/// Response: Register new account -/// -public class RegisterAccountRequestHandler : IRequestHandler> -{ - private readonly IAccountService _accountService; - - public RegisterAccountRequestHandler(IAccountService accountService) - => _accountService = accountService; - - public Task> Handle(RegisterAccountRequest request, CancellationToken cancellationToken) - => _accountService.RegisterAsync(request.Model, cancellationToken); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/RegisterViewModel.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/RegisterViewModel.cs deleted file mode 100644 index eccd056f..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/RegisterViewModel.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; - -/// -/// Data transfer object for user registration -/// -public class RegisterViewModel -{ - /// - /// FirstName - /// - [Required] - [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)] - [Display(Name = "First Name")] - public string FirstName { get; set; } = null!; - - /// - /// LastName - /// - [Required] - [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)] - [Display(Name = "Last Name")] - public string LastName { get; set; } = null!; - - /// - /// Email - /// - [Required] - [EmailAddress] - [Display(Name = "Email")] - public string Email { get; set; } = null!; - - /// - /// Password - /// - [Required] - [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] - [DataType(DataType.Password)] - [Display(Name = "Password")] - public string Password { get; set; } = null!; - - /// - /// Password confirmation - /// - [DataType(DataType.Password)] - [Display(Name = "Confirm password")] - [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] - public string ConfirmPassword { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/UserProfileViewModel.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/UserProfileViewModel.cs deleted file mode 100644 index f54b8bf5..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/UserProfileViewModel.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; - -/// -/// Application User Profile -/// -public class UserProfileViewModel -{ - /// - /// Identifier - /// - public Guid Id { get; set; } - - /// - /// FirstName - /// - public string FirstName { get; set; } = null!; - - /// - /// LastName - /// - public string LastName { get; set; } = null!; - - /// - /// Email - /// - public string Email { get; set; } = null!; - - /// - /// User Roles - /// - public List? Roles { get; set; } - - /// - /// User PhoneNumber - /// - public string? PhoneNumber { get; set; } - - /// - /// Position Name - /// - public string? PositionName { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/SECURITYENDPOINTS/AuthorizeEndpoints.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/SECURITYENDPOINTS/AuthorizeEndpoints.cs deleted file mode 100644 index 4c865320..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/SECURITYENDPOINTS/AuthorizeEndpoints.cs +++ /dev/null @@ -1,158 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Identity; -using OpenIddict.Abstractions; -using OpenIddict.Server.AspNetCore; - -namespace $safeprojectname$.Endpoints.SecurityEndpoints; - -/// -/// Authorize Endpoint for OpenIddict -/// You can test your authorization server with https://oidcdebugger.com/ -/// You can mock your authorization flow with https://oauth.mocklab.io/ -/// -public class AuthorizeEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("~/connect/authorize", AuthorizeAsync).ExcludeFromDescription(); - app.MapPost("~/connect/authorize", AuthorizeAsync).ExcludeFromDescription(); - } - - private async Task AuthorizeAsync( - HttpContext httpContext, - IOpenIddictScopeManager scopeManager, - UserManager userManager, - SignInManager signInManager, - IOpenIddictApplicationManager applicationManager, - IOpenIddictAuthorizationManager authorizationManager) - { - - var request = httpContext.Request; - var iRequest = httpContext.GetOpenIddictServerRequest() ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); - - // Retrieve the user principal stored in the authentication cookie. - var result = await httpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); - - if (!result.Succeeded) - { - return Results.Challenge(new AuthenticationProperties - { - RedirectUri = request.PathBase + request.Path + QueryString.Create(request.HasFormContentType - ? request.Form.ToList() - : request.Query.ToList()) - }, - new List { CookieAuthenticationDefaults.AuthenticationScheme }); - } - - // ATTENTION: If you use are "IN-Memory" mode, then system cannot track user that recreated every time on start. You should clear cookies (site data) in browser. - var user = await userManager.GetUserAsync(result.Principal) ?? throw new InvalidOperationException("The user details cannot be retrieved."); - - var application = await applicationManager.FindByClientIdAsync(iRequest.ClientId!) ?? throw new InvalidOperationException("Details concerning the calling client application cannot be found."); - var applicationId = await applicationManager.GetIdAsync(application); - var userId = await userManager.GetUserIdAsync(user); - - var authorizations = await authorizationManager.FindAsync( - subject: userId, - client: applicationId!, - status: OpenIddictConstants.Statuses.Valid, - type: OpenIddictConstants.AuthorizationTypes.Permanent, - scopes: iRequest.GetScopes()).ToListAsync(); - - switch (await applicationManager.GetConsentTypeAsync(application)) - { - // If the consent is external (e.g when authorizations are granted by a sysadmin), - // immediately return an error if no authorization can be found in the database. - case OpenIddictConstants.ConsentTypes.External when !authorizations.Any(): - return Results.Forbid( - authenticationSchemes: new[] { OpenIddictServerAspNetCoreDefaults.AuthenticationScheme }, - properties: new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = OpenIddictConstants.Errors.ConsentRequired, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "The logged in user is not allowed to access this client application." - }!)); - - // If the consent is implicit or if an authorization was found, - // return an authorization response without displaying the consent form. - case OpenIddictConstants.ConsentTypes.Implicit: - case OpenIddictConstants.ConsentTypes.External when authorizations.Any(): - case OpenIddictConstants.ConsentTypes.Explicit when authorizations.Any() && !iRequest.HasPrompt(OpenIddictConstants.Prompts.Consent): - - var principal = await signInManager.CreateUserPrincipalAsync(user); - - // Note: in this sample, the granted scopes match the requested scope - // but you may want to allow the user to uncheck specific scopes. - // For that, simply restrict the list of scopes before calling SetScopes. - - var sc = iRequest.GetScopes(); - principal.SetScopes(sc); - // principal.SetScopes(iRequest.GetScopes()); - principal.SetResources(await scopeManager.ListResourcesAsync(principal.GetScopes()).ToListAsync()); - - // Automatically create a permanent authorization to avoid requiring explicit consent - // for future authorization or token requests containing the same scopes. - var authorization = authorizations.LastOrDefault(); - if (authorization is null) - { - authorization = await authorizationManager.CreateAsync( - principal: principal, - subject: await userManager.GetUserIdAsync(user), - client: applicationId!, - type: OpenIddictConstants.AuthorizationTypes.Permanent, - scopes: principal.GetScopes()); - } - - principal.SetAuthorizationId(await authorizationManager.GetIdAsync(authorization)); - - foreach (var claim in principal.Claims) - { - claim.SetDestinations(claim.Type switch - { - // If the "profile" scope was granted, allow the "name" claim to be - // added to the access and identity tokens derived from the principal. - OpenIddictConstants.Claims.Name when principal.HasScope(OpenIddictConstants.Scopes.Profile) => new[] - { - OpenIddictConstants.Destinations.AccessToken, - OpenIddictConstants.Destinations.IdentityToken - }, - - // Never add the "secret_value" claim to access or identity tokens. - // In this case, it will only be added to authorization codes, - // refresh tokens and user/device codes, that are always encrypted. - "secret_value" => Array.Empty(), - - // Otherwise, add the claim to the access tokens only. - _ => new[] - { - OpenIddictConstants.Destinations.AccessToken - } - }); - } - - return Results.SignIn(principal, null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - - // At this point, no authorization was found in the database and an error must be returned - // if the client application specified prompt=none in the authorization request. - case OpenIddictConstants.ConsentTypes.Explicit when iRequest.HasPrompt(OpenIddictConstants.Prompts.None): - case OpenIddictConstants.ConsentTypes.Systematic when iRequest.HasPrompt(OpenIddictConstants.Prompts.None): - return Results.Forbid( - authenticationSchemes: new[] { OpenIddictServerAspNetCoreDefaults.AuthenticationScheme }, - properties: new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = OpenIddictConstants.Errors.ConsentRequired, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "Interactive user consent is required." - }!)); - - // In every other case, render the consent form. - default: - return Results.Challenge( - authenticationSchemes: new[] { OpenIddictServerAspNetCoreDefaults.AuthenticationScheme }, - properties: new AuthenticationProperties { RedirectUri = "/" }); - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/SECURITYENDPOINTS/TokenEndpoints.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/SECURITYENDPOINTS/TokenEndpoints.cs deleted file mode 100644 index d2997569..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/SECURITYENDPOINTS/TokenEndpoints.cs +++ /dev/null @@ -1,101 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using $safeprojectname$.Application.Services; -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Identity; -using OpenIddict.Abstractions; -using OpenIddict.Server.AspNetCore; -using System.Security.Claims; - -namespace $safeprojectname$.Endpoints.SecurityEndpoints; - -/// -/// Token Endpoint for OpenIddict -/// -public class TokenEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) => - app.MapPost("~/connect/token", TokenAsync).ExcludeFromDescription(); - - private async Task TokenAsync( - HttpContext httpContext, - IOpenIddictScopeManager manager, - UserManager userManager, - SignInManager signInManager, - IAccountService accountService) - { - var request = httpContext.GetOpenIddictServerRequest() ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); - - if (request.IsClientCredentialsGrantType()) - { - var identity = new ClaimsIdentity(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - - // Subject or sub is a required field, we use the client id as the subject identifier here. - identity.AddClaim(OpenIddictConstants.Claims.Subject, request.ClientId!); - identity.AddClaim(OpenIddictConstants.Claims.ClientId, request.ClientId!); - - - // Don't forget to add destination otherwise it won't be added to the access token. - identity.AddClaim(OpenIddictConstants.Claims.Scope, request.Scope!, OpenIddictConstants.Destinations.AccessToken); - identity.AddClaim("nimble", "framework", OpenIddictConstants.Destinations.AccessToken); - - var claimsPrincipal = new ClaimsPrincipal(identity); - - claimsPrincipal.SetScopes(request.GetScopes()); - return Results.SignIn(claimsPrincipal, new AuthenticationProperties(), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - } - - if (request.IsPasswordGrantType()) - { - var user = await userManager.FindByNameAsync(request.Username); - if (user == null) - { - return Results.Problem("Invalid operation"); - } - - // Ensure the user is allowed to sign in - if (!await signInManager.CanSignInAsync(user)) - { - return Results.Problem("Invalid operation"); - } - - - // Ensure the user is not already locked out - if (userManager.SupportsUserLockout && await userManager.IsLockedOutAsync(user)) - { - return Results.Problem("Invalid operation"); - } - - // Ensure the password is valid - if (!await userManager.CheckPasswordAsync(user, request.Password)) - { - if (userManager.SupportsUserLockout) - { - await userManager.AccessFailedAsync(user); - } - - return Results.Problem("Invalid operation"); - } - - // Reset the lockout count - if (userManager.SupportsUserLockout) - { - await userManager.ResetAccessFailedCountAsync(user); - } - - var principal = await accountService.GetPrincipalByEmailAsync(user.Email); - return Results.SignIn(principal, new AuthenticationProperties(), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - } - - if (request.IsAuthorizationCodeGrantType()) - { - var authenticateResult = await httpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - var properties = authenticateResult.Properties; - var claimsPrincipal = authenticateResult.Principal; - return Results.SignIn(claimsPrincipal!, properties ?? new AuthenticationProperties(), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - } - - return Results.Problem("The specified grant type is not supported."); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/HOSTEDSERVICES/OpenIddictWorker.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/HOSTEDSERVICES/OpenIddictWorker.cs deleted file mode 100644 index 64e6ba98..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/HOSTEDSERVICES/OpenIddictWorker.cs +++ /dev/null @@ -1,85 +0,0 @@ -using $ext_projectname$.Infrastructure; -using OpenIddict.Abstractions; - -namespace $safeprojectname$.HostedServices; - -public class OpenIddictWorker : IHostedService -{ - private readonly IServiceProvider _serviceProvider; - - public OpenIddictWorker(IServiceProvider serviceProvider) => _serviceProvider = serviceProvider; - - public async Task StartAsync(CancellationToken cancellationToken) - { - await using var scope = _serviceProvider.CreateAsyncScope(); - - var context = scope.ServiceProvider.GetRequiredService(); - await context.Database.EnsureCreatedAsync(cancellationToken); - - var manager = scope.ServiceProvider.GetRequiredService(); - - // credentials password - const string client_id1 = "client-id-sts"; - if (await manager.FindByClientIdAsync(client_id1, cancellationToken) is null) - { - await manager.CreateAsync(new OpenIddictApplicationDescriptor - { - ClientId = client_id1, - ClientSecret = "client-secret-sts", - DisplayName = "Service-To-Service demonstration", - Permissions = - { - // Endpoint permissions - OpenIddictConstants.Permissions.Endpoints.Token, - - // Grant type permissions - OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, - OpenIddictConstants.Permissions.GrantTypes.Password, - - // Scope permissions - OpenIddictConstants.Permissions.Prefixes.Scope + "api" - } - }, cancellationToken); - } - - const string client_id2 = "client-id-code"; - if (await manager.FindByClientIdAsync(client_id2, cancellationToken) is null) - { - var url = _serviceProvider.GetRequiredService().GetValue("AuthServer:Url"); - - await manager.CreateAsync(new OpenIddictApplicationDescriptor - { - ClientId = client_id2, - ConsentType = OpenIddictConstants.ConsentTypes.Implicit, - ClientSecret = "client-secret-code", - DisplayName = "API testing clients with Authorization Code Flow demonstration", - RedirectUris = { - new Uri("https://www.thunderclient.com/oauth/callback"), // https://www.thunderclient.com/ - new Uri($"{url}/swagger/oauth2-redirect.html"), // https://swagger.io/ - new Uri("https://localhost:20001/swagger/oauth2-redirect.html") // https://swagger.io/ for Module - }, - - Permissions = - { - // Endpoint permissions - OpenIddictConstants.Permissions.Endpoints.Authorization, - OpenIddictConstants.Permissions.Endpoints.Token, - - // Grant type permissions - OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, - OpenIddictConstants.Permissions.GrantTypes.RefreshToken, - - // Scope permissions - OpenIddictConstants.Permissions.Prefixes.Scope + "api", - OpenIddictConstants.Permissions.Prefixes.Scope + "custom", - - // Response types - OpenIddictConstants.Permissions.ResponseTypes.Code, - OpenIddictConstants.Permissions.ResponseTypes.IdToken - } - }, cancellationToken); - } - } - - public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/MyTemplate.vstemplate b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/MyTemplate.vstemplate deleted file mode 100644 index db12db76..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/MyTemplate.vstemplate +++ /dev/null @@ -1,144 +0,0 @@ - - - Calabonga.Microservice.IdentityModule.Web - Calabonga.Microservice.IdentityModule.Web - CSharp - - - 1000 - true - Calabonga.Microservice.IdentityModule.Web - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - launchSettings.json - - - - AccountService.cs - IAccountService.cs - - FeatureGroupNameAttribute.cs - LoggerExtensions.cs - ValidatorBehavior.cs - - - - CommonDefinition.cs - - - CorsDefinition.cs - - - DataSeedingDefinition.cs - - - DbContextDefinition.cs - - - ContainerDefinition.cs - - - ErrorHandlingDefinition.cs - - - ETagGeneratorDefinition.cs - - - FluentValidationDefinition.cs - - - ApplicationUserClaimsPrincipalFactory.cs - AuthorizationDefinition.cs - UserIdentity.cs - - - AutomapperDefinition.cs - PagedListConverter.cs - - - - UnitOfWorkTransactionBehavior.cs - - EventItemPostTransactionBehavior.cs - MediatorDefinition.cs - - - AppPermissionHandler.cs - AuthData.cs - AuthorizationPolicyProvider.cs - OpenIddictDefinition.cs - PermissionRequirement.cs - - - SwaggerDefinition.cs - - - UnitOfWorkDefinition.cs - - - - - - DeleteEventItem.cs - GetEventItemById.cs - GetEventItemPaged.cs - PostEventItem.cs - UpdateEventItem.cs - - - EventItemCreateViewModel.cs - EventItemUpdateViewModel.cs - EventItemViewModel.cs - - EventItemEndpoints.cs - EventItemMapperConfiguration.cs - EventItemValidator.cs - - - - GetRoles.cs - RegisterAccount.cs - - - RegisterViewModel.cs - UserProfileViewModel.cs - - ProfilesDefinition.cs - ProfilesMapperConfiguration.cs - - - AuthorizeEndpoints.cs - TokenEndpoints.cs - - - - OpenIddictWorker.cs - - - - Login.cshtml - Login.cshtml.cs - LoginViewModel.cs - - - _Layout.cshtml - - _ViewImports.cshtml - _ViewStart.cshtml - - appsettings.json - appsettings.Development.json - Program.cs - readme.md - tempkey.jwk - - - \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/Login.cshtml b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/Login.cshtml deleted file mode 100644 index 19017a63..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/Login.cshtml +++ /dev/null @@ -1,32 +0,0 @@ -@page -@model $safeprojectname$.Pages.Connect.LoginModel - -
- -
- -
- - - -
- -
- - - -
- - -
- - - -
-
- -
- -
-
-
\ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/Login.cshtml.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/Login.cshtml.cs deleted file mode 100644 index a0526147..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/Login.cshtml.cs +++ /dev/null @@ -1,68 +0,0 @@ -using $ext_projectname$.Infrastructure; -using $safeprojectname$.Application.Services; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace $safeprojectname$.Pages.Connect; - -public class LoginModel : PageModel -{ - private readonly IAccountService _accountService; - private readonly SignInManager _signInManager; - private readonly UserManager _userManager; - - public LoginModel( - IAccountService accountService, - SignInManager signInManager, - UserManager userManager) - { - _accountService = accountService; - _signInManager = signInManager; - _userManager = userManager; - } - - [BindProperty(SupportsGet = true)] - public string ReturnUrl { get; set; } - - [BindProperty] - public LoginViewModel Input { get; set; } - - public void OnGet() => Input = new LoginViewModel - { - ReturnUrl = ReturnUrl - }; - - public async Task OnPostAsync() - { - if (!ModelState.IsValid) - { - return Page(); - } - - var user = await _userManager.FindByNameAsync(Input.UserName); - if (user == null) - { - ModelState.AddModelError("UserName", "Пользователь не найден"); - return Page(); - } - - var signInResult = await _signInManager.PasswordSignInAsync(user, Input.Password, true, false); - if (signInResult.Succeeded) - { - var principal = await _accountService.GetPrincipalByIdAsync(user.Id.ToString()); - await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); - - if (Url.IsLocalUrl(ReturnUrl)) - { - return Redirect(ReturnUrl); - } - return RedirectToPage("/swagger"); - } - - ModelState.AddModelError("UserName", "Пользователь не найден"); - return Page(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/LoginViewModel.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/LoginViewModel.cs deleted file mode 100644 index bffae52e..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/LoginViewModel.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace $safeprojectname$.Pages.Connect; - -public class LoginViewModel -{ - - [Required] - [EmailAddress] - [Display(Name = "Имя для входа")] - public string UserName { get; set; } = null!; - - [Required] - [Display(Name = "Пароль")] - public string Password { get; set; } = null!; - - [Required] - public string ReturnUrl { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/SHARED/_Layout.cshtml b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/SHARED/_Layout.cshtml deleted file mode 100644 index 476c0e72..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/SHARED/_Layout.cshtml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - Authorization Server Nimble Framework - - - - -
-
-
- -

- Сервер авторизации -

-

- Version: 6.1.3 -

-
-
-
- @RenderBody() - -
-
-
-

- - Calabonga SOFT 2022 © Nimble Framework -

-
-
-
- - - - \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/_ViewImports.cshtml b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/_ViewImports.cshtml deleted file mode 100644 index 9018c789..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/_ViewImports.cshtml +++ /dev/null @@ -1 +0,0 @@ -@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/_ViewStart.cshtml b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/_ViewStart.cshtml deleted file mode 100644 index 1af6e494..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/PAGES/_ViewStart.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@{ - Layout = "_Layout"; -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/Program.cs b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/Program.cs deleted file mode 100644 index fac47e8b..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/Program.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -------------------------------------------------------------------- -// Name: Template for Micro service on ASP.NET Core API with -// OpenIddict (OAuth2.0) -// Author: Calabonga © 2005-2022 Calabonga SOFT -// Version: 6.1.4 -// Based on: .NET 6.0.x -// Created Date: 2019-04-13 3:28:39 PM -// Updated Date: 2022-10-02 11:33:14 AM -// -------------------------------------------------------------------- -// Contacts -// -------------------------------------------------------------------- -// Blog: https://www.calabonga.net -// GitHub: https://github.com/Calabonga -// YouTube: https://youtube.com/sergeicalabonga -// Zen: https://zen.yandex.ru/calabonga -// -------------------------------------------------------------------- -// Description: -// -------------------------------------------------------------------- -// Minimal API for NET6 used. -// This template implements Web API and OpenIddict (OAuth2.0) -// functionality. Also, support two type of Authentication: -// Cookie and Bearer -// -------------------------------------------------------------------- - -using Calabonga.AspNetCore.AppDefinitions; -using Serilog; -using Serilog.Events; - -try -{ - // configure logger (Serilog) - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .Enrich.FromLogContext() - .WriteTo.Console() - .CreateLogger(); - - // created builder - var builder = WebApplication.CreateBuilder(args); - builder.Host.UseSerilog(); - - // adding definitions for application - builder.Services.AddDefinitions(builder, typeof(Program)); - - // create application - var app = builder.Build(); - - // using definition for application - app.UseDefinitions(); - - // start application - app.Run(); - - return 0; -} -catch (Exception ex) -{ - var type = ex.GetType().Name; - if (type.Equals("StopTheHostException", StringComparison.Ordinal)) - { - throw; - } - - Log.Fatal(ex, "Unhandled exception"); - return 1; -} -finally -{ - Log.CloseAndFlush(); -} - - diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/__PreviewImage.png b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/__PreviewImage.png deleted file mode 100644 index d92b7a06..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/__TemplateIcon.png b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json deleted file mode 100644 index 94858a1a..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "Cors": { - "Origins": "*" - }, - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/appsettings.json b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/appsettings.json deleted file mode 100644 index 78158c32..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/appsettings.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=;User ID=;Password=" - }, - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AuthServer": { - "Url": "https://localhost:10001" - }, - "AllowedHosts": "*" -} diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/readme.md b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/readme.md deleted file mode 100644 index 1086aa6b..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/readme.md +++ /dev/null @@ -1,25 +0,0 @@ -# About - -| Name | Description | -| ------------ | ------------------------------------------ | -| Name | Microservice Template for ASP.NET Core API | -| Author | Calabonga SOFT © 2005-2022 Calabonga SOFT | -| Created Date | 2019-04-13 3:28:39 PM | - -# Versions - -Nimble Framework Templates build on .NET 6.0. That`s why it have the same major version. But the all improvements will increment minor versions. -Current version: 6.1.4 - -# Contacts - -You can contact me by using the next opportunities: - -* Blog: https://www.calabonga.net -* GitHub: https://github.com/Calabonga -* Zen: https://dzen.ru/calabonga -* YouTube: https://youtube.com/sergeicalabonga - -# Description: - -This template implements Web API functionality using minmal API feature from NET 6.0 \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk deleted file mode 100644 index 54a03371..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk +++ /dev/null @@ -1 +0,0 @@ -{"alg":"RS256","d":"P7dPY7Wy3wuD_Vls0NBNsrY_j5o70JJk0beTptSFEspyvBlFSpG3wLSqWBqnbZzRmEWJ12Kdn8BgMiB8kzUQk3JjA16o6_USGLCKCnNkWBya4xJ0Yh63YjIVltMNHclsep70NjoTbI8G3UjOUXtKGYyqcC_FSWfmkPugVv7eQwWOasP60sXExfmGHQ5EV8NkVc4VBIkhEGolpVaUbISWg1Gf_CTj_iwm1FzosoUB6dlrQ-CAcYQT0gCRXeP85cnxUrfXQrExyzGC5ablHj9IBMWrUW9KmUqG42gvbuUmkv-0GolHj0DivQjJRMvOhmYzfw-FVly64cSQdYjrdVyiEQ","dp":"vaf7y9sBxE33PlS87g-5besW6OcDYmbL2fHc1Jaqp_tudjk3KE2g608qz18EFNxhduf7n7ACpTCLTLzqYgubGrzvgFWhqJhh2Ts2aEC_EWAnTTyzgq3F6_AwNlpsLYw-FDWU7lLRjgeYu2ZRJcQ1LtrFcBf8lv7EORfGcZ7zeh0","dq":"1mMVHzMx-LnIbaAFht5nce0-8pLj1zf25Jzghlm8Wgi0FAGI8b8V3edbVSJo1V8JdI_we4HjsmC3RA686Z1NsSXIaUxel44GdZXIYAiZA3N30gs5mT07MUPrglPeNm6LMYeYn5fsTk12TSIWTUMTmyW5BNvHTVQjH0dk7maJWzU","e":"AQAB","kid":"72F4E7F8D19F17C0FC47D7CF1FBF61DF","kty":"RSA","n":"sf6uR2CqoZHzcEex5KT54OC6iAd1I-dELjp16-xmkSuqWGOIyyFqqQ5kyxvMlayfSUbdcLTCswaAyomnbu3tUuvccgdhO_7BsFN8eaosYqgUmUP0htI6lirysnFxRxaA-4qozXrNTxMcoxF0hgTtgIg6R8hdKMfpOZi90D1XGZUsNe9GjRLDZZVssM-idookwqTeMmLKLGUZiQwOTc9QOplHYbL52turG3kSTjoOVrrCM1szm9j5VSfmXAug3QJXZe0x0twfBhym8rEljsgr4IopNe8RA4Msg6uZFHCc4rCRXd5xajlSug4g8r_lq0M64Ug4nzIe1kfpMjY8nHnr2Q","p":"0rSFb90z1tu6BxUUQuL3DwJNu6YrSCTunkkgq943YuTV1XO2KXTW1mZbbD_KnvUMRz9CDsnFts-8W6fh7g8-_zFnhnDS7_XoYa7Yf2Aw9hN2VTKGuDNZo9Vidj4jbejXddbY2L3n0qD_iR9PIXuDM_at9zj7xMk88A5NPFY57mM","q":"2EINjDxepSzyh6BPltt3iqExQrtgseUermliIjHc8kSx_j25azscTZC3MYU6hy7AMISqXBoAsc2GCyKfhQpcNlOWXYeRn-QgYzea5kog8OEM1-hneTzhCAbb8IUm7l_JZ11Se423OVKBA9bgg7yj8K94Hid3ayJOTIe4Rzjvo5M","qi":"pst6tRwkUiKMpWSJ2aMp2jsf_14s96c_bzOMoJUgk3T2LjOJ6TTXYW8uyYm76RXJALBbows73rk9sMaohv08MjXT_QCBCDHQGwb1cH07j2aXslkq-pjO7J8vOUvBhc4ZSWzqmyQEqLOC76N_vem1j39w_eu12TbFncQYitmEtBs"} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Root.vstemplate b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Root.vstemplate deleted file mode 100644 index f7e1df87..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Root.vstemplate +++ /dev/null @@ -1,28 +0,0 @@ - - - Microservice API Template with OpenIddict OAuth 2.0 - Nimble microservice template with Authentication and Authorization. This template gives you a possibility to start developing a microservices system with integrated Swagger, Mediatr, Automapper, OpenIddict and other things. This template is using minimal API feature from .NET 6.0. That's why we implement a Vertical Slice Architecture approach used (Folding by Features) - CSharp - - 1000 - true - Calabonga.Microservice.IdentityModule - true - Enabled - true - __TemplateIcon.png - __PreviewImage.png - - - - - - - Calabonga.Microservice.IdentityModule.Web\MyTemplate.vstemplate - Calabonga.Microservice.IdentityModule.Domain\MyTemplate.vstemplate - Calabonga.Microservice.IdentityModule.Infrastructure\MyTemplate.vstemplate - - - - diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/__PreviewImage.png b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/__PreviewImage.png deleted file mode 100644 index d92b7a06..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/__TemplateIcon.png b/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/AppData.Common.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/AppData.Common.cs deleted file mode 100644 index b72a2218..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/AppData.Common.cs +++ /dev/null @@ -1,45 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Static data container - /// - public static partial class AppData - { - /// - /// CORS Policy name - /// - public const string PolicyName = "CorsPolicy"; - - /// - /// Current service name - /// - public const string ServiceName = "Microservice Template"; - - /// - /// Nimble Framework Microservice Template with integrated OpenIddict for OpenID Connect server and Token Validation - /// - public const string ServiceDescription = "Nimble Framework Microservice Template with integrated OpenIddict for OpenID Connect server and Token Validation"; - - /// - /// "SystemAdministrator" - /// - public const string SystemAdministratorRoleName = "Administrator"; - - /// - /// "BusinessOwner" - /// - public const string ManagerRoleName = "Manager"; - - /// - /// Roles - /// - public static IEnumerable Roles - { - get - { - yield return SystemAdministratorRoleName; - yield return ManagerRoleName; - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/AppData.Exceptions.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/AppData.Exceptions.cs deleted file mode 100644 index 6f8fad4b..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/AppData.Exceptions.cs +++ /dev/null @@ -1,61 +0,0 @@ -namespace $safeprojectname$.Base -{ - public static partial class AppData - { - /// - /// Exception messages - /// - public static class Exceptions - { - /// - /// "An exception was thrown" - /// - public static string ThrownException => "An exception was thrown"; - - /// - /// "Invalid cast exception" - /// - public static string TypeConverterException => "Invalid cast exception"; - - /// - /// "User not registered in the system" - /// - public static string UserNotFoundException => "User not registered in the system"; - - /// - /// "Object not found" - /// - public static string NotFoundException => "Object not found"; - - /// - /// "Unauthorized access denied" - /// - public static string UnauthorizedException => "Unauthorized access denied"; - - /// - /// "Argument null exception" - /// - public static string ArgumentNullException => "Argument null exception"; - - /// - /// "File already exists" - /// - public static string FileAlreadyExists => "File already exists"; - - /// - /// "Some errors occurred while checking the entity" - /// - public static string EntityValidationException => "Some errors occurred while checking the entity"; - - /// - /// "Invalid operation exception was thrown" - /// - public static string InvalidOperationException => "Invalid operation exception was thrown"; - - /// - /// "Argument out of range" - /// - public static string ArgumentOutOfRangeException => "Argument out of range"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/AppData.Messages.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/AppData.Messages.cs deleted file mode 100644 index 040c5666..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/AppData.Messages.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace $safeprojectname$.Base -{ - public static partial class AppData - { - /// - /// Common messages - /// - public static class Messages - { - /// - /// "User successfully registered" - /// - public static string UserSuccessfullyRegistered => "User successfully registered"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/Auditable.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/Auditable.cs deleted file mode 100644 index a73d7fb2..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/Auditable.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Represents 'Audit-able' table from the Property Database - /// - public abstract class Auditable : Identity, IAuditable - { - /// - /// DateTime when entity created. - /// It's never changed - /// - public DateTime CreatedAt { get; set; } - - /// - /// User name who created entity. - /// It's never changed - /// - public string CreatedBy { get; set; } - - /// - /// Last date entity updated - /// - public DateTime? UpdatedAt { get; set; } - - /// - /// Author of last updated - /// - public string UpdatedBy { get; set; } - - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/IAuditable.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/IAuditable.cs deleted file mode 100644 index f9d6bbc6..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/IAuditable.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Represent information about creation and last update - /// - public interface IAuditable - { - /// - /// DateTime of creation. This value will never changed - /// - DateTime CreatedAt { get; set; } - - /// - /// Author name. This value never changed - /// - string CreatedBy { get; set; } - - /// - /// DateTime of last value update. Should be updated when entity data updated - /// - DateTime? UpdatedAt { get; set; } - - /// - /// Author of last value update. Should be updated when entity data updated - /// - string UpdatedBy { get; set; } - - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/IHaveId.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/IHaveId.cs deleted file mode 100644 index 44fc68e3..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/IHaveId.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Identifier common interface - /// - public interface IHaveId - { - /// - /// Identifier - /// - Guid Id { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/IViewModel.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/IViewModel.cs deleted file mode 100644 index 73f7b0c7..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/IViewModel.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Represents ViewModel for CRUD controller - /// - public interface IViewModel { } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/Identity.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/Identity.cs deleted file mode 100644 index e5e6d0d1..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/Identity.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Identifier - /// - public abstract class Identity : IHaveId - { - /// - /// Identifier - /// - public Guid Id { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/NamedAuditable.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/NamedAuditable.cs deleted file mode 100644 index 75b37d0b..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/NamedAuditable.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Audit-able with name - /// - public abstract class NamedAuditable : Auditable - { - public string Name { get; set; } - - public string Description { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/NamedIdentity.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/NamedIdentity.cs deleted file mode 100644 index a4af146b..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/NamedIdentity.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// NamedIdentity dictionary for selector - /// - public abstract class NamedIdentity : Identity - { - /// - /// Entity name - /// - public string Name { get; set; } - - /// - /// Entity brief name - /// - public string BriefName { get; set; } - - /// - /// Brief descriptions - /// - public string Description { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/Sortable.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/Sortable.cs deleted file mode 100644 index 4f9dc4c5..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/Sortable.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Order - /// - public class Sortable : Auditable - { - /// - /// Sorting index for entity - /// - public int SortIndex { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/TypeHelper.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/TypeHelper.cs deleted file mode 100644 index 1ddfb335..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/TypeHelper.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Some helpful methods for Type manipulations - /// - public static class TypeHelper - { - /// - /// Check type before converting - /// - /// - /// - /// - public static bool CanChangeType(object value, Type conversionType) - { - if (conversionType == null) - { - return false; - } - return value is IConvertible; - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/ViewModelBase.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/ViewModelBase.cs deleted file mode 100644 index 92228811..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/BASE/ViewModelBase.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// ViewModelBase for WritableController - /// - public class ViewModelBase : IViewModel, IHaveId - { - /// - /// Identifier - /// - public Guid Id { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj deleted file mode 100644 index 27ac3865..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - - net6.0 - enable - enable - - - diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/EventItem.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/EventItem.cs deleted file mode 100644 index e1c7d3f2..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/EventItem.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace $safeprojectname$ -{ - /// - /// EventItem entity for demo purposes only - /// - public class EventItem : Identity - { - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; - - public string? ThreadId { get; set; } - - public string? ExceptionMessage { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/GlobalUsing.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/GlobalUsing.cs deleted file mode 100644 index e294041c..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/GlobalUsing.cs +++ /dev/null @@ -1 +0,0 @@ -global using $safeprojectname$.Base; \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/MyTemplate.vstemplate b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/MyTemplate.vstemplate deleted file mode 100644 index ddd88cfe..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/MyTemplate.vstemplate +++ /dev/null @@ -1,39 +0,0 @@ - - - Calabonga.Microservice.Module.Domain - Calabonga.Microservice.Module.Domain - CSharp - - - 1000 - true - Calabonga.Microservice.Module.Domain - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - AppData.Common.cs - AppData.Exceptions.cs - AppData.Messages.cs - Auditable.cs - IAuditable.cs - Identity.cs - IHaveId.cs - IViewModel.cs - NamedAuditable.cs - NamedIdentity.cs - Sortable.cs - TypeHelper.cs - ViewModelBase.cs - - EventItem.cs - GlobalUsing.cs - - - \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/__PreviewImage.png b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/__PreviewImage.png deleted file mode 100644 index d92b7a06..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/__TemplateIcon.png b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Domain/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs deleted file mode 100644 index 82153a35..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs +++ /dev/null @@ -1,49 +0,0 @@ -using $safeprojectname$.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Diagnostics; - -namespace $safeprojectname$ -{ - /// - /// Database context for current application - /// - public class ApplicationDbContext : DbContextBase - { - public ApplicationDbContext(DbContextOptions options) - : base(options) { } - - public DbSet EventItems { get; set; } - - public DbSet Profiles { get; set; } - - public DbSet Permissions { get; set; } - - /// - /// - /// Override this method to configure the database (and other options) to be used for this context. - /// This method is called for each instance of the context that is created. - /// The base implementation does nothing. - /// - /// - /// In situations where an instance of may or may not have been passed - /// to the constructor, you can use to determine if - /// the options have already been set, and skip some or all of the logic in - /// . - /// - /// - /// - /// See DbContext lifetime, configuration, and initialization - /// for more information. - /// - /// - /// A builder used to create or modify options for this context. Databases (and other extensions) - /// typically define extension methods on this object that allow you to configure the context. - /// - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)); - - base.OnConfiguring(optionsBuilder); - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationRole.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationRole.cs deleted file mode 100644 index dfcb2a39..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationRole.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace $safeprojectname$ -{ - /// - /// Application role - /// - public class ApplicationRole : IdentityRole - { - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationUser.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationUser.cs deleted file mode 100644 index 1f687374..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationUser.cs +++ /dev/null @@ -1,30 +0,0 @@ - -namespace $safeprojectname$ -{ - /// - /// Default user for application. - /// Add profile data for application users by adding properties to the ApplicationUser class - /// - public class ApplicationUser : IdentityUser - { - /// - /// FirstName - /// - public string FirstName { get; set; } - - /// - /// LastName - /// - public string LastName { get; set; } - - /// - /// Profile identity - /// - public Guid? ApplicationUserProfileId { get; set; } - - /// - /// User Profile - /// - public virtual ApplicationUserProfile ApplicationUserProfile { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationUserProfile.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationUserProfile.cs deleted file mode 100644 index 1ab40401..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationUserProfile.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace $safeprojectname$ -{ - /// - /// Represent person with login information (ApplicationUser) - /// - public class ApplicationUserProfile : Auditable - { - /// - /// Account - /// - public virtual ApplicationUser ApplicationUser { get; set; } - - /// - /// Microservice permission for policy-based authorization - /// - public ICollection Permissions { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationUserStore.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationUserStore.cs deleted file mode 100644 index f8062e23..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/ApplicationUserStore.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; - -namespace $safeprojectname$ -{ - /// - /// Application store for user - /// - public class ApplicationUserStore : UserStore - { - public ApplicationUserStore(ApplicationDbContext context, IdentityErrorDescriber describer = null) - : base(context, describer) - { - - } - - /// - public override Task FindByIdAsync(string userId, CancellationToken cancellationToken = new CancellationToken()) - { - return Users - .Include(x => x.ApplicationUserProfile) - .ThenInclude(x => x.Permissions) - .FirstOrDefaultAsync(u => u.Id.ToString() == userId, cancellationToken: cancellationToken); - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/BASE/DbContextBase.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/BASE/DbContextBase.cs deleted file mode 100644 index ba2c92c1..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/BASE/DbContextBase.cs +++ /dev/null @@ -1,258 +0,0 @@ -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; -using System.Reflection; - -namespace $safeprojectname$.Base -{ - /// - /// Base DbContext with predefined configuration - /// - public abstract class - DbContextBase : IdentityDbContext - { - private const string DefaultUserName = "Anonymous"; - - protected DbContextBase(DbContextOptions options) : base(options) - { - LastSaveChangesResult = new SaveChangesResult(); - } - - public SaveChangesResult LastSaveChangesResult { get; } - - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - /// - /// Saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// The number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override int SaveChanges(bool acceptAllChangesOnSuccess) - { - try - { - DbSaveChanges(); - return base.SaveChanges(acceptAllChangesOnSuccess); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - public override int SaveChanges() - { - try - { - DbSaveChanges(); - return base.SaveChanges(); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - private void DbSaveChanges() - { - var createdEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added); - foreach (var entry in createdEntries) - { - if (!(entry.Entity is IAuditable)) - { - continue; - } - - var creationDate = DateTime.Now.ToUniversalTime(); - var userName = entry.Property("CreatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("CreatedBy").CurrentValue; - var updatedAt = entry.Property("UpdatedAt").CurrentValue; - var createdAt = entry.Property("CreatedAt").CurrentValue; - if (createdAt != null) - { - if (DateTime.Parse(createdAt.ToString()).Year > 1970) - { - entry.Property("CreatedAt").CurrentValue = ((DateTime)createdAt).ToUniversalTime(); - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - - if (updatedAt != null) - { - if (DateTime.Parse(updatedAt.ToString()).Year > 1970) - { - entry.Property("UpdatedAt").CurrentValue = ((DateTime)updatedAt).ToUniversalTime(); - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - - entry.Property("CreatedBy").CurrentValue = userName; - entry.Property("UpdatedBy").CurrentValue = userName; - - LastSaveChangesResult.AddMessage($"ChangeTracker has new entities: {entry.Entity.GetType()}"); - } - - var updatedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified); - foreach (var entry in updatedEntries) - { - if (entry.Entity is IAuditable) - { - var userName = entry.Property("UpdatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("UpdatedBy").CurrentValue; - entry.Property("UpdatedAt").CurrentValue = DateTime.Now.ToUniversalTime(); - entry.Property("UpdatedBy").CurrentValue = userName; - } - - LastSaveChangesResult.AddMessage($"ChangeTracker has modified entities: {entry.Entity.GetType()}"); - } - } - - /// - /// Configures the schema needed for the identity framework. - /// - /// - /// The builder being used to construct the model for this context. - /// - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - var applyGenericMethod = typeof(ModelBuilder).GetMethods(BindingFlags.Instance | BindingFlags.Public).First(x => x.Name == "ApplyConfiguration"); - foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters)) - { - foreach (var item in type.GetInterfaces()) - { - if (!item.IsConstructedGenericType || item.GetGenericTypeDefinition() != typeof(IEntityTypeConfiguration<>)) - { - continue; - } - - var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(item.GenericTypeArguments[0]); - applyConcreteMethod.Invoke(builder, new[] { Activator.CreateInstance(type) }); - break; - } - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj deleted file mode 100644 index c2e3b30f..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - - - - - - - - - - - - diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/DATABASEINITIALIZATION/DatabaseInitializer.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/DATABASEINITIALIZATION/DatabaseInitializer.cs deleted file mode 100644 index d364e298..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/DATABASEINITIALIZATION/DatabaseInitializer.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace $safeprojectname$.DatabaseInitialization -{ - /// - /// Database Initializer - /// - public static class DatabaseInitializer - { - public static async void Seed(IServiceProvider serviceProvider) - { - using var scope = serviceProvider.CreateScope(); - await using var context = scope.ServiceProvider.GetService(); - - // It should be uncomment when using UseSqlServer() settings or any other providers. - // This is should not be used when UseInMemoryDatabase() - // await context!.Database.MigrateAsync(); - - await context!.EventItems.AddAsync(new EventItem - { - CreatedAt = DateTime.UtcNow, - Id = Guid.Parse("1467a5b9-e61f-82b0-425b-7ec75f5c5029"), - Level = "Information", - Logger = "SEED", - Message = "Seed method some entities successfully save to ApplicationDbContext" - }); - - await context.SaveChangesAsync(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/GlobalUsing.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/GlobalUsing.cs deleted file mode 100644 index 1abf8488..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/GlobalUsing.cs +++ /dev/null @@ -1,4 +0,0 @@ -global using $ext_projectname$.Domain; -global using $ext_projectname$.Domain.Base; -global using Microsoft.AspNetCore.Identity; -global using Microsoft.Extensions.DependencyInjection; \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/MicroservicePermission.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/MicroservicePermission.cs deleted file mode 100644 index 2f45dadd..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/MicroservicePermission.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace $safeprojectname$ -{ - /// - /// User permission for microservice - /// - public class MicroservicePermission : Auditable - { - /// - /// Application User profile identifier - /// - public Guid ApplicationUserProfileId { get; set; } - - /// - /// Application User Profile - /// - public virtual ApplicationUserProfile ApplicationUserProfile { get; set; } - - /// - /// Authorize attribute policy name - /// - public string PolicyName { get; set; } - - /// - /// Description for current permission - /// - public string Description { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/MyTemplate.vstemplate b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/MyTemplate.vstemplate deleted file mode 100644 index 2643bfce..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/MyTemplate.vstemplate +++ /dev/null @@ -1,35 +0,0 @@ - - - Calabonga.Microservice.Module.Infrastructure - Calabonga.Microservice.Module.Infrastructure - CSharp - - - 1000 - true - Calabonga.Microservice.Module.Infrastructure - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - DbContextBase.cs - - - DatabaseInitializer.cs - - ApplicationDbContext.cs - ApplicationRole.cs - ApplicationUser.cs - ApplicationUserProfile.cs - ApplicationUserStore.cs - GlobalUsing.cs - MicroservicePermission.cs - - - \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/__PreviewImage.png b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/__PreviewImage.png deleted file mode 100644 index d92b7a06..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/__TemplateIcon.png b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Infrastructure/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/.editorconfig b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/.editorconfig deleted file mode 100644 index ad6bdfaf..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/.editorconfig +++ /dev/null @@ -1,228 +0,0 @@ -root = true -# Remove the line below if you want to inherit .editorconfig settings from higher directories - -# C# files -[*.cs] - -#### Core EditorConfig Options #### -charset = utf-8-bom - -# Indentation and spacing -indent_size = 4 -indent_style = space -tab_width = 4 - -# New line preferences -end_of_line = crlf -insert_final_newline = false - -#### .NET Coding Conventions #### - -# Organize usings -dotnet_separate_import_directive_groups = false -dotnet_sort_system_directives_first = false - -# this. and Me. preferences -dotnet_style_qualification_for_event = false:suggestion -dotnet_style_qualification_for_field = false -dotnet_style_qualification_for_method = false:suggestion -dotnet_style_qualification_for_property = false:suggestion - -# Language keywords vs BCL types preferences -dotnet_style_predefined_type_for_locals_parameters_members = true -dotnet_style_predefined_type_for_member_access = true - -# Parentheses preferences -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_operators = never_if_unnecessary -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity - -# Modifier preferences -dotnet_style_require_accessibility_modifiers = for_non_interface_members - -# Expression-level preferences -dotnet_style_coalesce_expression = true -dotnet_style_collection_initializer = true -dotnet_style_explicit_tuple_names = true -dotnet_style_null_propagation = true -dotnet_style_object_initializer = true -dotnet_style_operator_placement_when_wrapping = beginning_of_line -dotnet_style_prefer_auto_properties = true:error -dotnet_style_prefer_compound_assignment = true -dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion -dotnet_style_prefer_conditional_expression_over_return = true:suggestion -dotnet_style_prefer_inferred_anonymous_type_member_names = true:error -dotnet_style_prefer_inferred_tuple_names = true -dotnet_style_prefer_is_null_check_over_reference_equality_method = true -dotnet_style_prefer_simplified_boolean_expressions = true -dotnet_style_prefer_simplified_interpolation = true - -# Field preferences -dotnet_style_readonly_field = true:error - -# Parameter preferences -dotnet_code_quality_unused_parameters = all - -# Suppression preferences -dotnet_remove_unnecessary_suppression_exclusions = none - -#### C# Coding Conventions #### - -# var preferences -csharp_style_var_elsewhere = true:suggestion -csharp_style_var_for_built_in_types = true:suggestion -csharp_style_var_when_type_is_apparent = true:suggestion - -# Expression-bodied members -csharp_style_expression_bodied_accessors = true:suggestion -csharp_style_expression_bodied_constructors = true:suggestion -csharp_style_expression_bodied_indexers = true:suggestion -csharp_style_expression_bodied_lambdas = true -csharp_style_expression_bodied_local_functions = false -csharp_style_expression_bodied_methods = true:suggestion -csharp_style_expression_bodied_operators = true:suggestion -csharp_style_expression_bodied_properties = true:suggestion - -# Pattern matching preferences -csharp_style_pattern_matching_over_as_with_null_check = true -csharp_style_pattern_matching_over_is_with_cast_check = true -csharp_style_prefer_not_pattern = true -csharp_style_prefer_pattern_matching = true -csharp_style_prefer_switch_expression = true - -# Null-checking preferences -csharp_style_conditional_delegate_call = true - -# Modifier preferences -csharp_prefer_static_local_function = true -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async - -# Code-block preferences -csharp_prefer_braces = true:error -csharp_prefer_simple_using_statement = true - -# Expression-level preferences -csharp_prefer_simple_default_expression = true -csharp_style_deconstructed_variable_declaration = true -csharp_style_implicit_object_creation_when_type_is_apparent = true -csharp_style_inlined_variable_declaration = true -csharp_style_pattern_local_over_anonymous_function = true -csharp_style_prefer_index_operator = true -csharp_style_prefer_range_operator = true -csharp_style_throw_expression = true -csharp_style_unused_value_assignment_preference = discard_variable -csharp_style_unused_value_expression_statement_preference = discard_variable - -# 'using' directive preferences -csharp_using_directive_placement = outside_namespace - -#### C# Formatting Rules #### - -# New line preferences -csharp_new_line_before_catch = true -csharp_new_line_before_else = true -csharp_new_line_before_finally = true -csharp_new_line_before_members_in_anonymous_types = true -csharp_new_line_before_members_in_object_initializers = true -csharp_new_line_before_open_brace = all -csharp_new_line_between_query_expression_clauses = true - -# Indentation preferences -csharp_indent_block_contents = true -csharp_indent_braces = false -csharp_indent_case_contents = true -csharp_indent_case_contents_when_block = true -csharp_indent_labels = no_change -csharp_indent_switch_labels = true - -# Space preferences -csharp_space_after_cast = false -csharp_space_after_colon_in_inheritance_clause = true -csharp_space_after_comma = true -csharp_space_after_dot = false -csharp_space_after_keywords_in_control_flow_statements = true -csharp_space_after_semicolon_in_for_statement = true -csharp_space_around_binary_operators = before_and_after -csharp_space_around_declaration_statements = false -csharp_space_before_colon_in_inheritance_clause = true -csharp_space_before_comma = false -csharp_space_before_dot = false -csharp_space_before_open_square_brackets = false -csharp_space_before_semicolon_in_for_statement = false -csharp_space_between_empty_square_brackets = false -csharp_space_between_method_call_empty_parameter_list_parentheses = false -csharp_space_between_method_call_name_and_opening_parenthesis = false -csharp_space_between_method_call_parameter_list_parentheses = false -csharp_space_between_method_declaration_empty_parameter_list_parentheses = false -csharp_space_between_method_declaration_name_and_open_parenthesis = false -csharp_space_between_method_declaration_parameter_list_parentheses = false -csharp_space_between_parentheses = false -csharp_space_between_square_brackets = false - -# Wrapping preferences -csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true - -#### Naming styles #### - -# Naming rules - -dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion -dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface -dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i - -dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.types_should_be_pascal_case.symbols = types -dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case - -dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members -dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case - -# Symbol specifications - -dotnet_naming_symbols.interface.applicable_kinds = interface -dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interface.required_modifiers = - -dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum -dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types.required_modifiers = - -dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method -dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.non_field_members.required_modifiers = - -# Naming styles - -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = -dotnet_naming_style.pascal_case.capitalization = pascal_case - -dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = -dotnet_naming_style.begins_with_i.capitalization = pascal_case - -# Instance fields are camelCase and start with _ -dotnet_naming_rule.instance_fields_should_be_camel_case.severity = hint -dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields -dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style - -dotnet_naming_symbols.instance_fields.applicable_kinds = field - -dotnet_naming_style.instance_field_style.capitalization = camel_case -dotnet_naming_style.instance_field_style.required_prefix = _ - -# ReSharper properties -max_line_length = 200 -resharper_csharp_max_line_length = 200 -resharper_csharp_wrap_after_declaration_lpar = true -resharper_csharp_wrap_extends_list_style = chop_if_long -resharper_csharp_wrap_lines = false -resharper_max_attribute_length_for_same_line = 300 -resharper_place_type_constraints_on_same_line = true -resharper_wrap_before_arrow_with_expressions = true -resharper_wrap_before_extends_colon = false \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/APPLICATION/LoggerExtensions.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/APPLICATION/LoggerExtensions.cs deleted file mode 100644 index 167281d7..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/APPLICATION/LoggerExtensions.cs +++ /dev/null @@ -1,75 +0,0 @@ - -namespace $safeprojectname$.Application; - -/// -/// The number identifiers for events in the microservices -/// -internal static class EventNumbers -{ - internal static readonly EventId UserRegistrationId = new EventId(9001, nameof(UserRegistrationId)); - internal static readonly EventId PostItemId = new EventId(9002, nameof(PostItemId)); -} - -/// -/// Event logging as ILogger extension. -/// Please see the video as the manual https://youtu.be/09EVKgHgwnM -/// -internal static class LoggerExtensions -{ - #region UserRegistration - - /// - /// EventItem register action event - /// - /// - /// - /// - internal static void MicroserviceUserRegistration(this ILogger source, string userName, Exception? exception = null) - { - switch (exception) - { - case null: - UserRegistrationExecute(source, userName, exception); - break; - default: - UserRegistrationFailedExecute(source, userName, exception); - break; - } - } - - private static readonly Action UserRegistrationExecute = - LoggerMessage.Define(LogLevel.Information, EventNumbers.UserRegistrationId, - "User {userName} successfully registred"); - - private static readonly Action UserRegistrationFailedExecute = - LoggerMessage.Define(LogLevel.Error, EventNumbers.UserRegistrationId, - "User {userName} registred failed"); - - #endregion - - #region PostItem - - internal static void MicroservicePostItem(this ILogger source, string entityName, Exception? exception = null) - { - switch (exception) - { - case null: - PostItemExecute(source, entityName, null); - break; - - default: - PostItemFailedExecute(source, entityName, exception); - break; - } - } - - private static readonly Action PostItemExecute = - LoggerMessage.Define(LogLevel.Information, EventNumbers.PostItemId, - "The {entityName} successfully saved"); - - private static readonly Action PostItemFailedExecute = - LoggerMessage.Define(LogLevel.Error, EventNumbers.PostItemId, - "The {entityName} saving failed"); - - #endregion -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj deleted file mode 100644 index 72f033b4..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj +++ /dev/null @@ -1,31 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/COMMON/CommonDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/COMMON/CommonDefinition.cs deleted file mode 100644 index e5f58c40..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/COMMON/CommonDefinition.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace $safeprojectname$.Definitions.Common; - -/// -/// AspNetCore common configuration -/// -public class CommonDefinition : AppDefinition -{ - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) - => app.UseHttpsRedirection(); - - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddLocalization(); - services.AddHttpContextAccessor(); - services.AddResponseCaching(); - services.AddMemoryCache(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/CORS/CorsDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/CORS/CorsDefinition.cs deleted file mode 100644 index 54bed485..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/CORS/CorsDefinition.cs +++ /dev/null @@ -1,47 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$.Definitions.Cors; - -/// -/// Cors configurations -/// -public class CorsDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - var origins = builder.Configuration.GetSection("Cors")?.GetSection("Origins")?.Value?.Split(','); - services.AddCors(options => - { - options.AddPolicy(AppData.PolicyName, builder => - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - if (origins is not {Length: > 0}) - { - return; - } - - if (origins.Contains("*")) - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - builder.SetIsOriginAllowed(host => true); - builder.AllowCredentials(); - } - else - { - foreach (var origin in origins) - { - builder.WithOrigins(origin); - } - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/DATASEEDING/DataSeedingDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/DATASEEDING/DataSeedingDefinition.cs deleted file mode 100644 index 8465db60..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/DATASEEDING/DataSeedingDefinition.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure.DatabaseInitialization; - -namespace $safeprojectname$.Definitions.DataSeeding; - -/// -/// Seeding DbContext for default data for EntityFrameworkCore -/// -public class DataSeedingDefinition : AppDefinition -{ - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) - => DatabaseInitializer.Seed(app.Services); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/DBCONTEXT/DbContextDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/DBCONTEXT/DbContextDefinition.cs deleted file mode 100644 index e5f233f4..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/DBCONTEXT/DbContextDefinition.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using Microsoft.EntityFrameworkCore; - -namespace $safeprojectname$.Definitions.DbContext; - -/// -/// ASP.NET Core services registration and configurations -/// -public class DbContextDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - => services.AddDbContext(config => - { - // UseInMemoryDatabase - This for demo purposes only! - // Should uninstall package "Microsoft.EntityFrameworkCore.InMemory" and install what you need. - // For example: "Microsoft.EntityFrameworkCore.SqlServer" - // uncomment line below to use UseSqlServer(). Don't forget setup connection string in appSettings.json - config.UseInMemoryDatabase("DEMO_PURPOSES_ONLY"); - // config.UseSqlServer(configuration.GetConnectionString(nameof(ApplicationDbContext))); - }); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/ERRORHANDLING/ErrorHandlingDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/ERRORHANDLING/ErrorHandlingDefinition.cs deleted file mode 100644 index 3844610a..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/ERRORHANDLING/ErrorHandlingDefinition.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using FluentValidation; -using Microsoft.AspNetCore.Diagnostics; -using Serilog; -using System.Text.Json; - -namespace $safeprojectname$.Definitions.ErrorHandling; - -/// -/// Custom Error handling -/// -public class ErrorHandlingDefinition : AppDefinition -{ - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) => - app.UseExceptionHandler(error => error.Run(async context => - { - - context.Response.ContentType = "application/json"; - var contextFeature = context.Features.Get(); - if (contextFeature is not null) - { - // handling validation errors - if (contextFeature.Error is ValidationException failures) - { - await context.Response.WriteAsync(JsonSerializer.Serialize(failures.Errors)); - context.Response.StatusCode = StatusCodes.Status400BadRequest; - return; - } - - // handling all another errors - Log.Error($"Something went wrong in the {contextFeature.Error}"); - context.Response.StatusCode = StatusCodes.Status500InternalServerError; - - if (app.Environment.IsDevelopment()) - { - await context.Response.WriteAsync($"INTERNAL SERVER ERROR: {contextFeature.Error}"); - } - else - { - await context.Response.WriteAsync("INTERNAL SERVER ERROR. PLEASE TRY AGAIN LATER"); - } - } - })); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/ETAGGENERATOR/ETagGeneratorDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/ETAGGENERATOR/ETagGeneratorDefinition.cs deleted file mode 100644 index 7d332004..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/ETAGGENERATOR/ETagGeneratorDefinition.cs +++ /dev/null @@ -1,69 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Net.Http.Headers; -using System.Security.Cryptography; - -namespace $safeprojectname$.Definitions.ETagGenerator; - -/// -/// ETag Generator -/// -public class ETagGeneratorDefinition : AppDefinition -{ - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) => - app.Use(async (context, next) => - { - var response = context.Response; - var originalStream = response.Body; - - await using var ms = new MemoryStream(); - response.Body = ms; - - await next(context); - - if (IsEtagSupported(response)) - { - var checksum = CalculateChecksum(ms); - - response.Headers[HeaderNames.ETag] = checksum; - - if (context.Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var etag) && checksum == etag) - { - response.StatusCode = StatusCodes.Status304NotModified; - return; - } - } - - ms.Position = 0; - await ms.CopyToAsync(originalStream); - }); - - - private static bool IsEtagSupported(HttpResponse response) - { - if (response.StatusCode != StatusCodes.Status200OK) - { - return false; - } - - // The 100kb length limit is not based in science. Feel free to change - if (response.Body.Length > 100 * 1024) - { - return false; - } - - return !response.Headers.ContainsKey(HeaderNames.ETag); - } - - private static string CalculateChecksum(MemoryStream ms) - { - using var algorithm = SHA1.Create(); - ms.Position = 0; - var bytes = algorithm.ComputeHash(ms); - return $"\"{WebEncoders.Base64UrlEncode(bytes)}\""; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/FLUENTVALIDATING/FluentValidationDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/FLUENTVALIDATING/FluentValidationDefinition.cs deleted file mode 100644 index 38f0e870..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/FLUENTVALIDATING/FluentValidationDefinition.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using FluentValidation; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Definitions.FluentValidating; - -/// -/// FluentValidation registration as MicroserviceDefinition -/// -public class FluentValidationDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.Configure(options => - { - options.SuppressModelStateInvalidFilter = true; - }); - - services.AddValidatorsFromAssembly(typeof(Program).Assembly); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/AuthData.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/AuthData.cs deleted file mode 100644 index df8dbc5a..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/AuthData.cs +++ /dev/null @@ -1,8 +0,0 @@ -using OpenIddict.Server.AspNetCore; - -namespace $safeprojectname$.Definitions.Identity; - -public static class AuthData -{ - public const string AuthSchemes = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/AuthorizationDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/AuthorizationDefinition.cs deleted file mode 100644 index ab7f6bb8..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/AuthorizationDefinition.cs +++ /dev/null @@ -1,108 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Domain.Base; -using $safeprojectname$.Definitions.OpenIddict; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Authorization; -using Microsoft.IdentityModel.Tokens; -using OpenIddict.Server.AspNetCore; -using System.Text.Json; - -namespace $safeprojectname$.Definitions.Identity; - -/// -/// Authorization Policy registration -/// -public class AuthorizationDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - var url = builder.Configuration.GetSection("AuthServer").GetValue("Url"); - - services - .AddAuthentication(options => - { - options.DefaultScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; - options.DefaultAuthenticateScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; - }) - .AddJwtBearer(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme, "Bearer", options => - { - options.SaveToken = true; - options.Audience = "client-id-code"; - options.Authority = url; - options.RequireHttpsMetadata = false; - options.TokenValidationParameters = new TokenValidationParameters - { - ValidateAudience = false, // Audience should be defined on the authorization server or disabled as shown - ClockSkew = new TimeSpan(0, 0, 30) - }; - options.Events = new JwtBearerEvents - { - OnChallenge = context => - { - context.HandleResponse(); - context.Response.StatusCode = StatusCodes.Status401Unauthorized; - context.Response.ContentType = "application/json"; - - // Ensure we always have an error and error description. - if (string.IsNullOrEmpty(context.Error)) - { - context.Error = "invalid_token"; - } - - if (string.IsNullOrEmpty(context.ErrorDescription)) - { - context.ErrorDescription = "This request requires a valid JWT access token to be provided"; - } - - // Add some extra context for expired tokens. - if (context.AuthenticateFailure != null && context.AuthenticateFailure.GetType() == typeof(SecurityTokenExpiredException)) - { - var authenticationException = context.AuthenticateFailure as SecurityTokenExpiredException; - context.Response.Headers.Add("x-token-expired", authenticationException?.Expires.ToString("o")); - context.ErrorDescription = $"The token expired on {authenticationException?.Expires:o}"; - } - - return context.Response.WriteAsync(JsonSerializer.Serialize(new - { - error = context.Error, - error_description = context.ErrorDescription - })); - } - }; - }); - - services.AddAuthorization(options => - { - options.AddPolicy(AuthData.AuthSchemes, policy => - { - policy.RequireAuthenticatedUser(); - policy.RequireClaim("scope", "api"); - }); - }); - - services.AddSingleton(); - services.AddSingleton(); - } - - /// - /// Configure application for current microservice - /// - /// - /// - public override void ConfigureApplication(WebApplication app) - { - app.UseRouting(); - app.UseCors(AppData.PolicyName); - app.UseAuthentication(); - app.UseAuthorization(); - - // registering UserIdentity helper as singleton - UserIdentity.Instance.Configure(app.Services.GetService()!); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/UserIdentity.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/UserIdentity.cs deleted file mode 100644 index 347c93bf..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/UserIdentity.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Calabonga.Microservices.Core.Exceptions; -using System.Security.Claims; -using System.Security.Principal; - -namespace $safeprojectname$.Definitions.Identity; - -/// -/// Identity helper for Requests operations -/// -public sealed class UserIdentity -{ - private UserIdentity() { } - - public static UserIdentity Instance => _lazy.Value; - - public void Configure(IHttpContextAccessor httpContextAccessor) - { - ContextAccessor = httpContextAccessor ?? throw new MicroserviceArgumentNullException(nameof(IHttpContextAccessor)); - IsInitialized = true; - } - - public IIdentity? User - { - get - { - if (IsInitialized) - { - return ContextAccessor.HttpContext!.User.Identity != null - && ContextAccessor.HttpContext != null - && ContextAccessor.HttpContext.User.Identity.IsAuthenticated - ? ContextAccessor.HttpContext.User.Identity - : null; - } - throw new MicroserviceArgumentNullException($"{nameof(UserIdentity)} has not been initialized. Please use {nameof(UserIdentity)}.Instance.Configure(...) in Configure Application method in Startup.cs"); - } - } - - public IEnumerable Claims - { - get - { - if (User != null) - { - return ContextAccessor.HttpContext!.User.Claims; - } - return Enumerable.Empty(); - } - } - - private static readonly Lazy _lazy = new(() => new UserIdentity()); - - private bool IsInitialized { get; set; } - - private static IHttpContextAccessor ContextAccessor { get; set; } = null!; - -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MAPPING/AutomapperDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MAPPING/AutomapperDefinition.cs deleted file mode 100644 index 7560aa3e..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MAPPING/AutomapperDefinition.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace $safeprojectname$.Definitions.Mapping; - -/// -/// Register Automapper as MicroserviceDefinition -/// -public class AutomapperDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - => services.AddAutoMapper(typeof(Program)); - - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) - { - var mapper = app.Services.GetRequiredService(); - if (app.Environment.IsDevelopment()) - { - // validate Mapper Configuration - mapper.AssertConfigurationIsValid(); - } - else - { - mapper.CompileMappings(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MAPPING/PagedListConverter.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MAPPING/PagedListConverter.cs deleted file mode 100644 index c66df094..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MAPPING/PagedListConverter.cs +++ /dev/null @@ -1,23 +0,0 @@ -using AutoMapper; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Definitions.Mapping; - -/// -/// Generic converter for IPagedList collections -/// -/// -/// -public class PagedListConverter : ITypeConverter, IPagedList> -{ - /// Performs conversion from source to destination type - /// Source object - /// Destination object - /// Resolution context - /// Destination object - public IPagedList Convert(IPagedList? source, IPagedList destination, ResolutionContext context) => - // ReSharper disable once ConditionIsAlwaysTrueOrFalse - source == null - ? PagedList.Empty() - : PagedList.From(source, items => context.Mapper.Map>(items)); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/BASE/UnitOfWorkTransactionBehavior.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/BASE/UnitOfWorkTransactionBehavior.cs deleted file mode 100644 index b588a961..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/BASE/UnitOfWorkTransactionBehavior.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Definitions.Mediator.Base; - -/// -/// Transaction Behavior -/// -/// -/// -public class TransactionBehavior : IPipelineBehavior - where TRequest : IRequest -{ - private readonly IUnitOfWork _unitOfWork; - - public TransactionBehavior(IUnitOfWork unitOfWork) => _unitOfWork = unitOfWork; - - - public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) - { - await using var transaction = await _unitOfWork.BeginTransactionAsync(); - try - { - var response = await next(); - await transaction.CommitAsync(cancellationToken); - return response; - } - catch (Exception) - { - await transaction.RollbackAsync(cancellationToken); - throw; - } - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/LogPostTransaction.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/LogPostTransaction.cs deleted file mode 100644 index 071a6126..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/LogPostTransaction.cs +++ /dev/null @@ -1,12 +0,0 @@ -using $safeprojectname$.Definitions.Mediator.Base; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Definitions.Mediator; - -public class LogPostTransactionBehavior : TransactionBehavior>, OperationResult> -{ - public LogPostTransactionBehavior(IUnitOfWork unitOfWork) : base(unitOfWork) { } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/MediatorDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/MediatorDefinition.cs deleted file mode 100644 index b5aebda0..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/MediatorDefinition.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Application; -using MediatR; -using System.Reflection; - -namespace $safeprojectname$.Definitions.Mediator; - -/// -/// Register Mediator as MicroserviceDefinition -/// -public class MediatorDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>)); - services.AddMediatR(Assembly.GetExecutingAssembly()); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/AppPermissionHandler.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/AppPermissionHandler.cs deleted file mode 100644 index b550bbe8..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/AppPermissionHandler.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Calabonga.Microservices.Core; -using Microsoft.AspNetCore.Authorization; -using System.Security.Claims; - -namespace $safeprojectname$.Definitions.OpenIddict; - -/// -/// Permission handler for custom authorization implementations -/// -public class AppPermissionHandler : AuthorizationHandler -{ - /// - protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) - { - if (context.User.Identity is null) - { - return Task.CompletedTask; - } - - var identity = (ClaimsIdentity)context.User.Identity; - var claim = ClaimsHelper.GetValue(identity, requirement.PermissionName); - if (claim == null) - { - return Task.CompletedTask; - } - - context.Succeed(requirement); - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/AuthorizationPolicyProvider.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/AuthorizationPolicyProvider.cs deleted file mode 100644 index 47dd81f1..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/AuthorizationPolicyProvider.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.Options; - -namespace $safeprojectname$.Definitions.OpenIddict; - -/// -/// Policy provider -/// -public class AuthorizationPolicyProvider : DefaultAuthorizationPolicyProvider -{ - private readonly AuthorizationOptions _options; - - /// - public AuthorizationPolicyProvider(IOptions options) : base(options) => _options = options.Value; - - /// - public override async Task GetPolicyAsync(string policyName) - { - var policyExists = await base.GetPolicyAsync(policyName); - if (policyExists != null) - { - return policyExists; - } - - policyExists = new AuthorizationPolicyBuilder().AddRequirements(new PermissionRequirement(policyName)).Build(); - _options.AddPolicy(policyName, policyExists); - return policyExists; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/OpenIddictDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/OpenIddictDefinition.cs deleted file mode 100644 index be6ebee9..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/OpenIddictDefinition.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace $safeprojectname$.Definitions.OpenIddict; - -public class OpenIddictDefinition : AppDefinition -{ - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) => - services - .AddOpenIddict() - .AddValidation(options => - { - // Import the configuration from the local OpenIddict server instance. - options.UseLocalServer(); - - // Register the ASP.NET Core host. - options.UseAspNetCore(); - }); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/PermissionRequirement.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/PermissionRequirement.cs deleted file mode 100644 index 5c3d40c2..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/PermissionRequirement.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Microsoft.AspNetCore.Authorization; - -namespace $safeprojectname$.Definitions.OpenIddict; - -/// -/// Permission requirement for user or service authorization -/// -public class PermissionRequirement : IAuthorizationRequirement -{ - public PermissionRequirement(string permissionName) => PermissionName = permissionName; - - /// - /// Permission name - /// - public string PermissionName { get; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/SWAGGER/SwaggerDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/SWAGGER/SwaggerDefinition.cs deleted file mode 100644 index 0a67684f..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/SWAGGER/SwaggerDefinition.cs +++ /dev/null @@ -1,117 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Domain.Base; -using Microsoft.AspNetCore.Mvc; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerUI; - -namespace $safeprojectname$.Definitions.Swagger; - -/// -/// Swagger definition for application -/// -public class SwaggerDefinition : AppDefinition -{ - - private const string _appVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - private const string _swaggerConfig = "/swagger/v1/swagger.json"; - - public override void ConfigureApplication(WebApplication app) - { - if (!app.Environment.IsDevelopment()) - { - return; - } - - app.UseSwagger(); - app.UseSwaggerUI(settings => - { - settings.SwaggerEndpoint(_swaggerConfig, $"{AppData.ServiceName} v.{_appVersion}"); - settings.HeadContent = $"{ThisAssembly.Git.Branch.ToUpper()} {ThisAssembly.Git.Commit.ToUpper()}"; - settings.DocumentTitle = $"{AppData.ServiceName}"; - settings.DefaultModelExpandDepth(0); - settings.DefaultModelRendering(ModelRendering.Model); - settings.DefaultModelsExpandDepth(0); - settings.DocExpansion(DocExpansion.None); - settings.OAuthScopeSeparator(" "); - settings.OAuthClientId("client-id-code"); - settings.OAuthClientSecret("client-secret-code"); - settings.DisplayRequestDuration(); - settings.OAuthAppName(AppData.ServiceName); - }); - } - - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - { - services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); - services.AddEndpointsApiExplorer(); - services.AddSwaggerGen(options => - { - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = AppData.ServiceName, - Version = _appVersion, - Description = AppData.ServiceDescription - }); - - options.ResolveConflictingActions(x => x.First()); - - options.TagActionsBy(api => - { - string tag; - if (api.ActionDescriptor is { } descriptor) - { - var attribute = descriptor.EndpointMetadata.OfType().FirstOrDefault(); - tag = attribute?.GroupName ?? descriptor.RouteValues["controller"] ?? "Untitled"; - } - else - { - tag = api.RelativePath!; - } - - var tags = new List(); - if (!string.IsNullOrEmpty(tag)) - { - tags.Add(tag); - } - return tags; - }); - - var url = builder.Configuration.GetSection("AuthServer").GetValue("Url"); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - AuthorizationCode = new OpenApiOAuthFlow - { - AuthorizationUrl = new Uri($"{url}/connect/authorize", UriKind.Absolute), - TokenUrl = new Uri($"{url}/connect/token", UriKind.Absolute), - Scopes = new Dictionary - { - { "api", "Default scope" } - } - } - } - }); - options.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "oauth2" - }, - Scheme = "oauth2", - Name = "Bearer", - In = ParameterLocation.Header, - - }, - new List() - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/UOW/UnitOfWorkDefinition.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/UOW/UnitOfWorkDefinition.cs deleted file mode 100644 index 41cba4db..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/DEFINITIONS/UOW/UnitOfWorkDefinition.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Definitions.UoW; - -/// -/// Unit of Work registration as MicroserviceDefinition -/// -public class UnitOfWorkDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(IServiceCollection services, WebApplicationBuilder builder) - => services.AddUnitOfWork(); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemEndpoints.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemEndpoints.cs deleted file mode 100644 index 88b6cf84..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemEndpoints.cs +++ /dev/null @@ -1,58 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Definitions.Identity; -using $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints; - -public class EventItemEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("/api/logs/{id}", LogGetById); - app.MapGet("/api/logs/paged", LogGetPaged); - app.MapPost("/api/logs/", PostLog); - app.MapPut("/api/logs/{id}", PutLog); - app.MapDelete("/api/logs/{id}", LogDelete); - } - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogGetById([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new GetEventItemByIdRequest(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogDelete([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new DeleteEventItemRequest(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task>> LogGetPaged([FromServices] IMediator mediator, int pageIndex, int pageSize, string? search, HttpContext context) - => await mediator.Send(new GetEventItemPagedRequest(pageIndex, pageSize, search), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PostLog([FromServices] IMediator mediator, EventItemCreateViewModel model, HttpContext context) - => await mediator.Send(new PostEventItemRequest(model), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PutLog([FromServices] IMediator mediator, Guid id, EventItemUpdateViewModel model, HttpContext context) - => await mediator.Send(new PutEventItemRequest(id, model), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemMapperConfiguration.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemMapperConfiguration.cs deleted file mode 100644 index 9fa595b9..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemMapperConfiguration.cs +++ /dev/null @@ -1,32 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Definitions.Mapping; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints; - -/// -/// Mapper Configuration for entity EventItem -/// -public class EventItemMapperConfiguration : Profile -{ - /// - public EventItemMapperConfiguration() - { - CreateMap() - .ForMember(x => x.Id, o => o.Ignore()); - - CreateMap(); - - CreateMap(); - - CreateMap() - .ForMember(x => x.CreatedAt, o => o.Ignore()) - .ForMember(x => x.ThreadId, o => o.Ignore()) - .ForMember(x => x.ExceptionMessage, o => o.Ignore()); - - CreateMap, IPagedList>() - .ConvertUsing>(); - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemValidator.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemValidator.cs deleted file mode 100644 index 46f08298..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemValidator.cs +++ /dev/null @@ -1,21 +0,0 @@ -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using FluentValidation; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints; - -/// -/// RegisterViewModel Validator -/// -public class EventItemCreateRequestValidator : AbstractValidator -{ - public EventItemCreateRequestValidator() => RuleSet("default", () => - { - RuleFor(x => x.CreatedAt).NotNull(); - RuleFor(x => x.Message).NotEmpty().NotNull().MaximumLength(4000); - RuleFor(x => x.Level).NotEmpty().NotNull().MaximumLength(50); - RuleFor(x => x.Logger).NotNull().NotEmpty().MaximumLength(255); - - RuleFor(x => x.ThreadId).MaximumLength(50); - RuleFor(x => x.ExceptionMessage).MaximumLength(4000); - }); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/DeleteEventItem.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/DeleteEventItem.cs deleted file mode 100644 index f1ab914b..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/DeleteEventItem.cs +++ /dev/null @@ -1,55 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem delete -/// -public record DeleteEventItemRequest(Guid Id) : IRequest>; - -/// -/// Request: EventItem delete -/// -public class DeleteEventItemRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - - private readonly IMapper _mapper; - - public DeleteEventItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(DeleteEventItemRequest request, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.FindAsync(request.Id); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException("Entity not found")); - return operation; - } - repository.Delete(entity); - await _unitOfWork.SaveChangesAsync(); - if (_unitOfWork.LastSaveChangesResult.IsOk) - { - operation.Result = _mapper.Map(entity); - return operation; - } - operation.AddError(_unitOfWork.LastSaveChangesResult.Exception); - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemById.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemById.cs deleted file mode 100644 index 1b4bd9a1..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemById.cs +++ /dev/null @@ -1,48 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request for EventItem by Identifier -/// -public record GetEventItemByIdRequest(Guid Id) : IRequest>; - -/// -/// Response for Request for EventItem by Identifier -/// -public class GetEventItemByIdRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public GetEventItemByIdRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request getting log by identifier - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(GetEventItemByIdRequest request, CancellationToken cancellationToken) - { - var id = request.Id; - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entityWithoutIncludes = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == id); - if (entityWithoutIncludes == null) - { - operation.AddError(new MicroserviceNotFoundException($"Entity with identifier {id} not found")); - return operation; - } - operation.Result = _mapper.Map(entityWithoutIncludes); - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemPaged.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemPaged.cs deleted file mode 100644 index 85565bca..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemPaged.cs +++ /dev/null @@ -1,75 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.PredicatesBuilder; -using Calabonga.UnitOfWork; -using MediatR; -using System.Linq.Expressions; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request for paged list of EventItems -/// -public record GetEventItemPagedRequest(int PageIndex, int PageSize, string? Search) : IRequest>>; - -/// -/// Request for paged list of EventItems -/// -public class GetEventItemPagedRequestHandler : IRequestHandler>> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public GetEventItemPagedRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task>> Handle(GetEventItemPagedRequest request, - CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult>(); - var predicate = GetPredicate(request.Search); - var pagedList = await _unitOfWork.GetRepository() - .GetPagedListAsync( - predicate: predicate, - pageIndex: request.PageIndex, - pageSize: request.PageSize, - cancellationToken: cancellationToken); - - if (pagedList == null) - { - operation.Result = PagedList.Empty(); - operation.AddWarning("Response does not return the result for pagination."); - return operation; - } - - if (pagedList.PageIndex > pagedList.TotalPages) - { - pagedList = await _unitOfWork.GetRepository() - .GetPagedListAsync( - pageIndex: 0, - pageSize: request.PageSize, cancellationToken: cancellationToken); - } - - operation.Result = _mapper.Map>(pagedList); - return operation; - } - - private Expression> GetPredicate(string? search) - { - var predicate = PredicateBuilder.True(); - if (search is null) - { - return predicate; - } - - predicate = predicate.And(x => x.Message.Contains(search)); - predicate = predicate.Or(x => x.Logger.Contains(search)); - predicate = predicate.Or(x => x.Level.Contains(search)); - return predicate; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/PostEventItem.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/PostEventItem.cs deleted file mode 100644 index 9cddfb14..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/PostEventItem.cs +++ /dev/null @@ -1,63 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem creation -/// -public record PostEventItemRequest(EventItemCreateViewModel Model) : IRequest>; - -/// -/// Request: EventItem creation -/// -public class PostEventItemRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - private readonly ILogger _logger; - - - public PostEventItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper, ILogger logger) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - _logger = logger; - } - - public async Task> Handle(PostEventItemRequest eventItemRequest, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - - var entity = _mapper.Map(eventItemRequest.Model); - if (entity == null) - { - operation.AddError(new MicroserviceUnauthorizedException(AppContracts.Exceptions.MappingException)); - return operation; - } - - await _unitOfWork.GetRepository().InsertAsync(entity, cancellationToken); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - - var mapped = _mapper.Map(entity); - - operation.Result = mapped; - operation.AddSuccess("Successfully created"); - return operation; - } - - operation.AddError(lastResult.Exception?? new ApplicationException("Something went wrong")); - - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/UpdateEventItem.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/UpdateEventItem.cs deleted file mode 100644 index 31c631e1..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/UpdateEventItem.cs +++ /dev/null @@ -1,59 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem edit -/// -public record PutEventItemRequest(Guid Id, EventItemUpdateViewModel Model) : IRequest>; - -/// -/// Request: EventItem creation -/// -public class PutEventItemRequestHandler : IRequestHandler> -{ - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public PutEventItemRequestHandler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task> Handle(PutEventItemRequest eventItemRequest, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == eventItemRequest.Id, disableTracking: false); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException(AppContracts.Exceptions.NotFoundException)); - return operation; - } - - _mapper.Map(eventItemRequest.Model, entity); - - repository.Update(entity); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("Successfully updated"); - return operation; - } - - operation.AddError(lastResult.Exception ?? new ApplicationException("Something went wrong")); - return operation; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemCreateViewModel.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemCreateViewModel.cs deleted file mode 100644 index 054466de..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemCreateViewModel.cs +++ /dev/null @@ -1,36 +0,0 @@ -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemCreateViewModel : IViewModel -{ - /// - /// EventItem Created At - /// - public DateTime CreatedAt { get; set; } - - /// - /// Service name or provider - /// - public string Logger { get; set; } = null!; - - /// - /// EventItem level for logging. See - /// - public string Level { get; set; } = null!; - - /// - /// EventItem Message - /// - public string Message { get; set; } = null!; - - /// - /// Thread identifier - /// - public string? ThreadId { get; set; } - - /// - /// Exception message - /// - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemUpdateViewModel.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemUpdateViewModel.cs deleted file mode 100644 index 6dc45417..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemUpdateViewModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemUpdateViewModel : ViewModelBase -{ - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemViewModel.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemViewModel.cs deleted file mode 100644 index 39211dbc..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemViewModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemViewModel -{ - public Guid Id { get; set; } - - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; - - public string? ThreadId { get; set; } - - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesEndpoint.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesEndpoint.cs deleted file mode 100644 index bed45ee6..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesEndpoint.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Definitions.Identity; -using $safeprojectname$.Endpoints.ProfileEndpoints.Queries; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints; - -public class ProfilesEndpointDefinition : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - => app.MapGet("/api/profiles/get-roles", GetRoles); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes, Policy = "EventItems:UserRoles:View")] - [FeatureGroupName("Profiles")] - private async Task GetRoles([FromServices] IMediator mediator, HttpContext context) - => await mediator.Send(new GetRolesRequest(), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesMapperConfiguration.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesMapperConfiguration.cs deleted file mode 100644 index 7028f518..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesMapperConfiguration.cs +++ /dev/null @@ -1,23 +0,0 @@ -using AutoMapper; -using $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using System.Security.Claims; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints; - -/// -/// Mapper Configuration for entity ApplicationUser -/// -public class ProfilesMapperConfiguration : Profile -{ - /// - public ProfilesMapperConfiguration() - => CreateMap() - .ForMember(x => x.Id, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Name))) - .ForMember(x => x.PositionName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Actor))) - .ForMember(x => x.FirstName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.GivenName))) - .ForMember(x => x.LastName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Surname))) - .ForMember(x => x.Roles, o => o.MapFrom(claims => ClaimsHelper.GetValues(claims, ClaimTypes.Role))) - .ForMember(x => x.Email, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Name))) - .ForMember(x => x.PhoneNumber, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.MobilePhone))); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/GetRoles.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/GetRoles.cs deleted file mode 100644 index 73911ab1..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/GetRoles.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Calabonga.Microservices.Core; -using MediatR; -using System.Security.Claims; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints.Queries; - -/// -/// Request: Returns user roles -/// -public record GetRolesRequest : IRequest; - -public class GetRolesRequestHandler : RequestHandler -{ - private readonly IHttpContextAccessor _httpContextAccessor; - - public GetRolesRequestHandler(IHttpContextAccessor httpContextAccessor) => _httpContextAccessor = httpContextAccessor; - - protected override string Handle(GetRolesRequest request) - { - var user = _httpContextAccessor.HttpContext!.User; - var roles = ClaimsHelper.GetValues((ClaimsIdentity)user.Identity!, ClaimTypes.Role); - return $"Current user ({user.Identity!.Name}) have following roles: {string.Join("|", roles)}"; - } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/UserProfileViewModel.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/UserProfileViewModel.cs deleted file mode 100644 index f54b8bf5..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/UserProfileViewModel.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; - -/// -/// Application User Profile -/// -public class UserProfileViewModel -{ - /// - /// Identifier - /// - public Guid Id { get; set; } - - /// - /// FirstName - /// - public string FirstName { get; set; } = null!; - - /// - /// LastName - /// - public string LastName { get; set; } = null!; - - /// - /// Email - /// - public string Email { get; set; } = null!; - - /// - /// User Roles - /// - public List? Roles { get; set; } - - /// - /// User PhoneNumber - /// - public string? PhoneNumber { get; set; } - - /// - /// Position Name - /// - public string? PositionName { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/FeatureGroupNameAttribute.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/FeatureGroupNameAttribute.cs deleted file mode 100644 index ff3f2d42..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/FeatureGroupNameAttribute.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace $safeprojectname$; - -/// -/// Swagger controller group attribute -/// -/// -[AttributeUsage(AttributeTargets.Method)] -public class FeatureGroupNameAttribute : Attribute -{ - /// - public FeatureGroupNameAttribute(string groupName) => GroupName = groupName; - - /// - /// Group name - /// - public string GroupName { get; } -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/MyTemplate.vstemplate b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/MyTemplate.vstemplate deleted file mode 100644 index e387a8fd..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/MyTemplate.vstemplate +++ /dev/null @@ -1,117 +0,0 @@ - - - Calabonga.Microservice.Module.Web - Calabonga.Microservice.Module.Web - CSharp - - - 1000 - true - Calabonga.Microservice.Module.Web - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - launchSettings.json - - - LoggerExtensions.cs - ValidatorBehavior.cs - - - - CommonDefinition.cs - - - CorsDefinition.cs - - - DataSeedingDefinition.cs - - - DbContextDefinition.cs - - - ErrorHandlingDefinition.cs - - - ETagGeneratorDefinition.cs - - - FluentValidationDefinition.cs - - - AuthData.cs - AuthorizationDefinition.cs - UserIdentity.cs - - - AutomapperDefinition.cs - PagedListConverter.cs - - - - UnitOfWorkTransactionBehavior.cs - - LogPostTransaction.cs - MediatorDefinition.cs - - - AppPermissionHandler.cs - AuthorizationPolicyProvider.cs - OpenIddictDefinition.cs - PermissionRequirement.cs - - - SwaggerDefinition.cs - - - UnitOfWorkDefinition.cs - - - - - - DeleteEventItem.cs - GetEventItemById.cs - GetEventItemPaged.cs - PostEventItem.cs - UpdateEventItem.cs - - - EventItemCreateViewModel.cs - EventItemUpdateViewModel.cs - EventItemViewModel.cs - - EventItemEndpoints.cs - EventItemMapperConfiguration.cs - EventItemValidator.cs - - - - GetRoles.cs - - - UserProfileViewModel.cs - - ProfilesEndpoint.cs - ProfilesMapperConfiguration.cs - - - .editorconfig - vstg0001.editorconfig - appsettings.json - appsettings.Development.json - FeatureGroupNameAttribute.cs - Program.cs - readme.md - tempkey.jwk - - - \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/Program.cs b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/Program.cs deleted file mode 100644 index 098fe1c2..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/Program.cs +++ /dev/null @@ -1,61 +0,0 @@ -// -------------------------------------------------------------------- -// Name: Template for Micro service on ASP.NET Core API with -// OpenIddict (OAuth2.0) -// Author: Calabonga © 2005-2022 Calabonga SOFT -// Version: 6.1.1 -// Based on: .NET 6.0.x -// Created Date: 2019-04-13 3:28:39 PM -// Updated Date: 2022-10-02 11:25:41 AM -// -------------------------------------------------------------------- -// Contacts -// -------------------------------------------------------------------- -// Blog: https://www.calabonga.net -// GitHub: https://github.com/Calabonga -// YouTube: https://youtube.com/sergeicalabonga -// -------------------------------------------------------------------- -// Description: -// -------------------------------------------------------------------- -// Minimal API for NET6 used. -// This template implements Web API and OpenIddict (OAuth2.0) -// functionality. Also, support two type of Authentication: -// Cookie and Bearer -// -------------------------------------------------------------------- - -using Calabonga.AspNetCore.AppDefinitions; -using Serilog; -using Serilog.Events; - -try -{ - // configure logger (Serilog) - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .Enrich.FromLogContext() - .WriteTo.Console() - .CreateLogger(); - - // created builder - var builder = WebApplication.CreateBuilder(args); - builder.Host.UseSerilog(); - - builder.Services.AddDefinitions(builder, typeof(Program)); - - // create application - var app = builder.Build(); - app.UseDefinitions(); - - // start application - app.Run(); - - return 0; -} -catch (Exception ex) -{ - Log.Fatal(ex, "Host terminated unexpectedly"); - return 1; -} -finally -{ - Log.CloseAndFlush(); -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/__PreviewImage.png b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/__PreviewImage.png deleted file mode 100644 index d92b7a06..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/__TemplateIcon.png b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/appsettings.Development.json b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/appsettings.Development.json deleted file mode 100644 index a6e41b5e..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/appsettings.Development.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=;User ID=;Password=" - }, - "Cors": { - "Origins": "*" - }, - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/appsettings.json b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/appsettings.json deleted file mode 100644 index 387377ec..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/appsettings.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AuthServer": { - "Url": "https://localhost:10001" - }, - "AllowedHosts": "*" -} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/readme.md b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/readme.md deleted file mode 100644 index ef570a14..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/readme.md +++ /dev/null @@ -1,25 +0,0 @@ -# About - -| Name | Description | -| ------------ | ------------------------------------------ | -| Name | Microservice Template for ASP.NET Core API | -| Author | Calabonga SOFT © 2005-2022 Calabonga SOFT | -| Created Date | 2019-04-19 | - -# Versions - -Nimble Framework Templates build on .NET 6.0. That`s why it have the same major version. But the all improvements will increment minor versions. -Current version: 6.1.1 - -# Contacts - -You can contact me by using the next opportunities: - -* Blog: https://www.calabonga.net -* GitHub: https://github.com/Calabonga -* Zen: https://dzen.ru/calabonga -* YouTube: https://youtube.com/sergeicalabonga - -# Description: - -This template implements Web API functionality using minmal API feature from NET 6.0 \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/tempkey.jwk b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/tempkey.jwk deleted file mode 100644 index 54a03371..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/tempkey.jwk +++ /dev/null @@ -1 +0,0 @@ -{"alg":"RS256","d":"P7dPY7Wy3wuD_Vls0NBNsrY_j5o70JJk0beTptSFEspyvBlFSpG3wLSqWBqnbZzRmEWJ12Kdn8BgMiB8kzUQk3JjA16o6_USGLCKCnNkWBya4xJ0Yh63YjIVltMNHclsep70NjoTbI8G3UjOUXtKGYyqcC_FSWfmkPugVv7eQwWOasP60sXExfmGHQ5EV8NkVc4VBIkhEGolpVaUbISWg1Gf_CTj_iwm1FzosoUB6dlrQ-CAcYQT0gCRXeP85cnxUrfXQrExyzGC5ablHj9IBMWrUW9KmUqG42gvbuUmkv-0GolHj0DivQjJRMvOhmYzfw-FVly64cSQdYjrdVyiEQ","dp":"vaf7y9sBxE33PlS87g-5besW6OcDYmbL2fHc1Jaqp_tudjk3KE2g608qz18EFNxhduf7n7ACpTCLTLzqYgubGrzvgFWhqJhh2Ts2aEC_EWAnTTyzgq3F6_AwNlpsLYw-FDWU7lLRjgeYu2ZRJcQ1LtrFcBf8lv7EORfGcZ7zeh0","dq":"1mMVHzMx-LnIbaAFht5nce0-8pLj1zf25Jzghlm8Wgi0FAGI8b8V3edbVSJo1V8JdI_we4HjsmC3RA686Z1NsSXIaUxel44GdZXIYAiZA3N30gs5mT07MUPrglPeNm6LMYeYn5fsTk12TSIWTUMTmyW5BNvHTVQjH0dk7maJWzU","e":"AQAB","kid":"72F4E7F8D19F17C0FC47D7CF1FBF61DF","kty":"RSA","n":"sf6uR2CqoZHzcEex5KT54OC6iAd1I-dELjp16-xmkSuqWGOIyyFqqQ5kyxvMlayfSUbdcLTCswaAyomnbu3tUuvccgdhO_7BsFN8eaosYqgUmUP0htI6lirysnFxRxaA-4qozXrNTxMcoxF0hgTtgIg6R8hdKMfpOZi90D1XGZUsNe9GjRLDZZVssM-idookwqTeMmLKLGUZiQwOTc9QOplHYbL52turG3kSTjoOVrrCM1szm9j5VSfmXAug3QJXZe0x0twfBhym8rEljsgr4IopNe8RA4Msg6uZFHCc4rCRXd5xajlSug4g8r_lq0M64Ug4nzIe1kfpMjY8nHnr2Q","p":"0rSFb90z1tu6BxUUQuL3DwJNu6YrSCTunkkgq943YuTV1XO2KXTW1mZbbD_KnvUMRz9CDsnFts-8W6fh7g8-_zFnhnDS7_XoYa7Yf2Aw9hN2VTKGuDNZo9Vidj4jbejXddbY2L3n0qD_iR9PIXuDM_at9zj7xMk88A5NPFY57mM","q":"2EINjDxepSzyh6BPltt3iqExQrtgseUermliIjHc8kSx_j25azscTZC3MYU6hy7AMISqXBoAsc2GCyKfhQpcNlOWXYeRn-QgYzea5kog8OEM1-hneTzhCAbb8IUm7l_JZ11Se423OVKBA9bgg7yj8K94Hid3ayJOTIe4Rzjvo5M","qi":"pst6tRwkUiKMpWSJ2aMp2jsf_14s96c_bzOMoJUgk3T2LjOJ6TTXYW8uyYm76RXJALBbows73rk9sMaohv08MjXT_QCBCDHQGwb1cH07j2aXslkq-pjO7J8vOUvBhc4ZSWzqmyQEqLOC76N_vem1j39w_eu12TbFncQYitmEtBs"} \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/vstg0001.editorconfig b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/vstg0001.editorconfig deleted file mode 100644 index ad6bdfaf..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/vstg0001.editorconfig +++ /dev/null @@ -1,228 +0,0 @@ -root = true -# Remove the line below if you want to inherit .editorconfig settings from higher directories - -# C# files -[*.cs] - -#### Core EditorConfig Options #### -charset = utf-8-bom - -# Indentation and spacing -indent_size = 4 -indent_style = space -tab_width = 4 - -# New line preferences -end_of_line = crlf -insert_final_newline = false - -#### .NET Coding Conventions #### - -# Organize usings -dotnet_separate_import_directive_groups = false -dotnet_sort_system_directives_first = false - -# this. and Me. preferences -dotnet_style_qualification_for_event = false:suggestion -dotnet_style_qualification_for_field = false -dotnet_style_qualification_for_method = false:suggestion -dotnet_style_qualification_for_property = false:suggestion - -# Language keywords vs BCL types preferences -dotnet_style_predefined_type_for_locals_parameters_members = true -dotnet_style_predefined_type_for_member_access = true - -# Parentheses preferences -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_operators = never_if_unnecessary -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity - -# Modifier preferences -dotnet_style_require_accessibility_modifiers = for_non_interface_members - -# Expression-level preferences -dotnet_style_coalesce_expression = true -dotnet_style_collection_initializer = true -dotnet_style_explicit_tuple_names = true -dotnet_style_null_propagation = true -dotnet_style_object_initializer = true -dotnet_style_operator_placement_when_wrapping = beginning_of_line -dotnet_style_prefer_auto_properties = true:error -dotnet_style_prefer_compound_assignment = true -dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion -dotnet_style_prefer_conditional_expression_over_return = true:suggestion -dotnet_style_prefer_inferred_anonymous_type_member_names = true:error -dotnet_style_prefer_inferred_tuple_names = true -dotnet_style_prefer_is_null_check_over_reference_equality_method = true -dotnet_style_prefer_simplified_boolean_expressions = true -dotnet_style_prefer_simplified_interpolation = true - -# Field preferences -dotnet_style_readonly_field = true:error - -# Parameter preferences -dotnet_code_quality_unused_parameters = all - -# Suppression preferences -dotnet_remove_unnecessary_suppression_exclusions = none - -#### C# Coding Conventions #### - -# var preferences -csharp_style_var_elsewhere = true:suggestion -csharp_style_var_for_built_in_types = true:suggestion -csharp_style_var_when_type_is_apparent = true:suggestion - -# Expression-bodied members -csharp_style_expression_bodied_accessors = true:suggestion -csharp_style_expression_bodied_constructors = true:suggestion -csharp_style_expression_bodied_indexers = true:suggestion -csharp_style_expression_bodied_lambdas = true -csharp_style_expression_bodied_local_functions = false -csharp_style_expression_bodied_methods = true:suggestion -csharp_style_expression_bodied_operators = true:suggestion -csharp_style_expression_bodied_properties = true:suggestion - -# Pattern matching preferences -csharp_style_pattern_matching_over_as_with_null_check = true -csharp_style_pattern_matching_over_is_with_cast_check = true -csharp_style_prefer_not_pattern = true -csharp_style_prefer_pattern_matching = true -csharp_style_prefer_switch_expression = true - -# Null-checking preferences -csharp_style_conditional_delegate_call = true - -# Modifier preferences -csharp_prefer_static_local_function = true -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async - -# Code-block preferences -csharp_prefer_braces = true:error -csharp_prefer_simple_using_statement = true - -# Expression-level preferences -csharp_prefer_simple_default_expression = true -csharp_style_deconstructed_variable_declaration = true -csharp_style_implicit_object_creation_when_type_is_apparent = true -csharp_style_inlined_variable_declaration = true -csharp_style_pattern_local_over_anonymous_function = true -csharp_style_prefer_index_operator = true -csharp_style_prefer_range_operator = true -csharp_style_throw_expression = true -csharp_style_unused_value_assignment_preference = discard_variable -csharp_style_unused_value_expression_statement_preference = discard_variable - -# 'using' directive preferences -csharp_using_directive_placement = outside_namespace - -#### C# Formatting Rules #### - -# New line preferences -csharp_new_line_before_catch = true -csharp_new_line_before_else = true -csharp_new_line_before_finally = true -csharp_new_line_before_members_in_anonymous_types = true -csharp_new_line_before_members_in_object_initializers = true -csharp_new_line_before_open_brace = all -csharp_new_line_between_query_expression_clauses = true - -# Indentation preferences -csharp_indent_block_contents = true -csharp_indent_braces = false -csharp_indent_case_contents = true -csharp_indent_case_contents_when_block = true -csharp_indent_labels = no_change -csharp_indent_switch_labels = true - -# Space preferences -csharp_space_after_cast = false -csharp_space_after_colon_in_inheritance_clause = true -csharp_space_after_comma = true -csharp_space_after_dot = false -csharp_space_after_keywords_in_control_flow_statements = true -csharp_space_after_semicolon_in_for_statement = true -csharp_space_around_binary_operators = before_and_after -csharp_space_around_declaration_statements = false -csharp_space_before_colon_in_inheritance_clause = true -csharp_space_before_comma = false -csharp_space_before_dot = false -csharp_space_before_open_square_brackets = false -csharp_space_before_semicolon_in_for_statement = false -csharp_space_between_empty_square_brackets = false -csharp_space_between_method_call_empty_parameter_list_parentheses = false -csharp_space_between_method_call_name_and_opening_parenthesis = false -csharp_space_between_method_call_parameter_list_parentheses = false -csharp_space_between_method_declaration_empty_parameter_list_parentheses = false -csharp_space_between_method_declaration_name_and_open_parenthesis = false -csharp_space_between_method_declaration_parameter_list_parentheses = false -csharp_space_between_parentheses = false -csharp_space_between_square_brackets = false - -# Wrapping preferences -csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true - -#### Naming styles #### - -# Naming rules - -dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion -dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface -dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i - -dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.types_should_be_pascal_case.symbols = types -dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case - -dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members -dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case - -# Symbol specifications - -dotnet_naming_symbols.interface.applicable_kinds = interface -dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interface.required_modifiers = - -dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum -dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types.required_modifiers = - -dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method -dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.non_field_members.required_modifiers = - -# Naming styles - -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = -dotnet_naming_style.pascal_case.capitalization = pascal_case - -dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = -dotnet_naming_style.begins_with_i.capitalization = pascal_case - -# Instance fields are camelCase and start with _ -dotnet_naming_rule.instance_fields_should_be_camel_case.severity = hint -dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields -dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style - -dotnet_naming_symbols.instance_fields.applicable_kinds = field - -dotnet_naming_style.instance_field_style.capitalization = camel_case -dotnet_naming_style.instance_field_style.required_prefix = _ - -# ReSharper properties -max_line_length = 200 -resharper_csharp_max_line_length = 200 -resharper_csharp_wrap_after_declaration_lpar = true -resharper_csharp_wrap_extends_list_style = chop_if_long -resharper_csharp_wrap_lines = false -resharper_max_attribute_length_for_same_line = 300 -resharper_place_type_constraints_on_same_line = true -resharper_wrap_before_arrow_with_expressions = true -resharper_wrap_before_extends_colon = false \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Root.vstemplate b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Root.vstemplate deleted file mode 100644 index 56955a68..00000000 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Root.vstemplate +++ /dev/null @@ -1,24 +0,0 @@ - - - Microservice API Template - Nimble microservice template. This template gives you a possibility to start developing a microservices system with integrated Swagger, Mediatr, Automapper and other things. This template is using minimal API feature from .NET 6.0. That's why we implement a Vertical Slice Architecture approach used (Folding by Features) - CSharp - true - Calabonga.Microservice.Module - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - - - Calabonga.Microservice.Module.Web\MyTemplate.vstemplate - Calabonga.Microservice.Module.Domain\MyTemplate.vstemplate - Calabonga.Microservice.Module.Infrastructure\MyTemplate.vstemplate - - - \ No newline at end of file diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/__PreviewImage.png b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/__PreviewImage.png deleted file mode 100644 index d92b7a06..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/__TemplateIcon.png b/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule..sln b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule..sln deleted file mode 100644 index 750ebbf6..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule..sln +++ /dev/null @@ -1,42 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.1.32421.90 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.IdentityModule.Web", "Calabonga.Microservice.IdentityModule.Web\Calabonga.Microservice.IdentityModule.Web.csproj", "{82820971-C4DD-4107-A397-29DA07713E28}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.IdentityModule.Domain", "Calabonga.Microservice.IdentityModule.Domain\Calabonga.Microservice.IdentityModule.Domain.csproj", "{F295EF4F-9873-49FC-983A-AC494F6131D2}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.IdentityModule.Infrastructure", "Calabonga.Microservice.IdentityModule.Infrastructure\Calabonga.Microservice.IdentityModule.Infrastructure.csproj", "{6B046F2A-2EE0-413D-859E-1D4CD30D066A}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{6FB183A6-17FD-4AF0-B653-09A8FD1F6765}" - ProjectSection(SolutionItems) = preProject - .editorconfig = .editorconfig - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {82820971-C4DD-4107-A397-29DA07713E28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {82820971-C4DD-4107-A397-29DA07713E28}.Debug|Any CPU.Build.0 = Debug|Any CPU - {82820971-C4DD-4107-A397-29DA07713E28}.Release|Any CPU.ActiveCfg = Release|Any CPU - {82820971-C4DD-4107-A397-29DA07713E28}.Release|Any CPU.Build.0 = Release|Any CPU - {F295EF4F-9873-49FC-983A-AC494F6131D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F295EF4F-9873-49FC-983A-AC494F6131D2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F295EF4F-9873-49FC-983A-AC494F6131D2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F295EF4F-9873-49FC-983A-AC494F6131D2}.Release|Any CPU.Build.0 = Release|Any CPU - {6B046F2A-2EE0-413D-859E-1D4CD30D066A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6B046F2A-2EE0-413D-859E-1D4CD30D066A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6B046F2A-2EE0-413D-859E-1D4CD30D066A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6B046F2A-2EE0-413D-859E-1D4CD30D066A}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {6C4879F7-325F-48F4-80E8-62B6E5409A8B} - EndGlobalSection -EndGlobal diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Common.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Common.cs deleted file mode 100644 index a88a590b..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Common.cs +++ /dev/null @@ -1,46 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Domain.Base; - -/// -/// Static data container -/// -public static partial class AppData -{ - /// - /// Current service name - /// - public const string ServiceName = "Microservice Template with OpenIddict"; - - /// - /// Nimble Framework Microservice Template with integrated OpenIddict - /// for OpenID Connect server and Token Validation - /// - public const string ServiceDescription = "Nimble Framework Microservice Template with integrated OpenIddict for OpenID Connect server and Token Validation"; - - /// - /// Default policy name - /// - public const string PolicyName = "CorsPolicy"; - - /// - /// "SystemAdministrator" - /// - public const string SystemAdministratorRoleName = "Administrator"; - - /// - /// "BusinessOwner" - /// - public const string ManagerRoleName = "Manager"; - - - /// - /// Roles - /// - public static IEnumerable Roles - { - get - { - yield return SystemAdministratorRoleName; - yield return ManagerRoleName; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Exceptions.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Exceptions.cs deleted file mode 100644 index 325bc88a..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Exceptions.cs +++ /dev/null @@ -1,60 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Domain.Base; - -public static partial class AppData -{ - /// - /// Exception messages - /// - public static class Exceptions - { - /// - /// "An exception was thrown" - /// - public static string ThrownException => "An exception was thrown"; - - /// - /// "Invalid cast exception" - /// - public static string TypeConverterException => "Invalid cast exception"; - - /// - /// "User not registered in the system" - /// - public static string UserNotFoundException => "User not registered in the system"; - - /// - /// "Object not found" - /// - public static string NotFoundException => "Object not found"; - - /// - /// "Unauthorized access denied" - /// - public static string UnauthorizedException => "Unauthorized access denied"; - - /// - /// "Argument null exception" - /// - public static string ArgumentNullException => "Argument null exception"; - - /// - /// "File already exists" - /// - public static string FileAlreadyExists => "File already exists"; - - /// - /// "Some errors occurred while checking the entity" - /// - public static string EntityValidationException => "Some errors occurred while checking the entity"; - - /// - /// "Invalid operation exception was thrown" - /// - public static string InvalidOperationException => "Invalid operation exception was thrown"; - - /// - /// "Argument out of range" - /// - public static string ArgumentOutOfRangeException => "Argument out of range"; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Messages.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Messages.cs deleted file mode 100644 index 0a28addc..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Messages.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Domain.Base; - -public static partial class AppData -{ - /// - /// Common messages - /// - public static class Messages - { - /// - /// "User successfully registered" - /// - public static string UserSuccessfullyRegistered => "User successfully registered"; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IHaveId.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IHaveId.cs deleted file mode 100644 index 661229f4..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IHaveId.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Domain.Base; - -/// -/// Identifier common interface -/// -public interface IHaveId -{ - /// - /// Identifier - /// - Guid Id { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IViewModel.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IViewModel.cs deleted file mode 100644 index 0012b249..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IViewModel.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Domain.Base; - -/// -/// Represents ViewModel for CRUD controller -/// -public interface IViewModel { } \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Identity.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Identity.cs deleted file mode 100644 index 8e1781ac..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Identity.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Domain.Base; - -/// -/// Identifier -/// -public abstract class Identity : IHaveId -{ - /// - /// Identifier - /// - public Guid Id { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Sortable.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Sortable.cs deleted file mode 100644 index 5e120e3b..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Sortable.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Domain.Base; - -/// -/// Order -/// -public class Sortable : Auditable -{ - /// - /// Sorting index for entity - /// - public int SortIndex { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/TypeHelper.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/TypeHelper.cs deleted file mode 100644 index b033044a..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/TypeHelper.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Domain.Base; - -/// -/// Some helpful methods for Type manipulations -/// -public static class TypeHelper -{ - /// - /// Check type before converting - /// - /// - /// - /// - public static bool CanChangeType(object value, Type conversionType) - { - if (conversionType == null) - { - return false; - } - return value is IConvertible; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/ViewModelBase.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/ViewModelBase.cs deleted file mode 100644 index 5336f060..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/ViewModelBase.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Calabonga.Microservice.IdentityModule.Domain.Base; - -/// -/// ViewModelBase for -/// -public class ViewModelBase : IViewModel, IHaveId -{ - /// - /// Identifier - /// - public Guid Id { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/EventItem.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/EventItem.cs deleted file mode 100644 index f493b1dc..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/EventItem.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Domain.Base; - -namespace Calabonga.Microservice.IdentityModule.Domain; - -/// -/// EventItem entity for demo purposes only -/// -public class EventItem : Identity -{ - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; - - public string? ThreadId { get; set; } - - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/AppPermission.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/AppPermission.cs deleted file mode 100644 index 52a7acf6..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/AppPermission.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Domain.Base; - -namespace Calabonga.Microservice.IdentityModule.Infrastructure; - -/// -/// User permission for application -/// -public class AppPermission : Auditable -{ - /// - /// Application User profile identifier - /// - public Guid ApplicationUserProfileId { get; set; } - - /// - /// Application User Profile - /// - public virtual ApplicationUserProfile? ApplicationUserProfile { get; set; } - - /// - /// Authorize attribute policy name - /// - public string PolicyName { get; set; } = null!; - - /// - /// Description for current permission - /// - public string Description { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs deleted file mode 100644 index 4133ecd4..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Infrastructure.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Design; -using Microsoft.EntityFrameworkCore.Diagnostics; - -namespace Calabonga.Microservice.IdentityModule.Infrastructure; - -/// -/// Database context for current application -/// -public class ApplicationDbContext : DbContextBase -{ - public ApplicationDbContext(DbContextOptions options) - : base(options) { } - - public DbSet EventItems { get; set; } - - public DbSet Profiles { get; set; } - - public DbSet Permissions { get; set; } - - protected override void OnModelCreating(ModelBuilder builder) - { - builder.UseOpenIddict(); - base.OnModelCreating(builder); - } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - // It should be removed when using real Database (not in memory mode) - optionsBuilder.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)); - base.OnConfiguring(optionsBuilder); - } -} - -///// -///// ATTENTION! -///// It should uncomment two line below when using real Database (not in memory mode). Don't forget update connection string. -///// -//public class ApplicationDbContextFactory : IDesignTimeDbContextFactory -//{ -// public ApplicationDbContext CreateDbContext(string[] args) -// { -// var optionsBuilder = new DbContextOptionsBuilder(); -// optionsBuilder.UseSqlServer("Server=;Database=;User ID=;Password="); -// return new ApplicationDbContext(optionsBuilder.Options); -// } -//} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRole.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRole.cs deleted file mode 100644 index 262d35a9..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRole.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Microsoft.AspNetCore.Identity; - -namespace Calabonga.Microservice.IdentityModule.Infrastructure; - -/// -/// Application role -/// -public class ApplicationRole : IdentityRole -{ -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUser.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUser.cs deleted file mode 100644 index 96729c0d..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUser.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Microsoft.AspNetCore.Identity; - -namespace Calabonga.Microservice.IdentityModule.Infrastructure; - -/// -/// Default user for application. -/// Add profile data for application users by adding properties to the ApplicationUser class -/// -public class ApplicationUser : IdentityUser -{ - /// - /// FirstName - /// - public string? FirstName { get; set; } - - /// - /// LastName - /// - public string? LastName { get; set; } - - /// - /// Profile identity - /// - public Guid? ApplicationUserProfileId { get; set; } - - /// - /// User Profile - /// - public virtual ApplicationUserProfile? ApplicationUserProfile { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserProfile.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserProfile.cs deleted file mode 100644 index 8d3f53c8..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserProfile.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Domain.Base; - -namespace Calabonga.Microservice.IdentityModule.Infrastructure; - -/// -/// Represent person with login information (ApplicationUser) -/// -public class ApplicationUserProfile : Auditable -{ - /// - /// Account - /// - public virtual ApplicationUser? ApplicationUser { get; set; } - - /// - /// Application permission for policy-based authorization - /// - public List? Permissions { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/DeleteEventItem.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/DeleteEventItem.cs deleted file mode 100644 index 30765b95..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/DeleteEventItem.cs +++ /dev/null @@ -1,57 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.Queries; - -/// -/// EventItem delete -/// -public class DeleteEventItem -{ - public record Request(Guid Id) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(Request request, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.FindAsync(request.Id); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException("Entity not found")); - return operation; - } - - repository.Delete(entity); - await _unitOfWork.SaveChangesAsync(); - if (_unitOfWork.LastSaveChangesResult.IsOk) - { - operation.Result = _mapper.Map(entity); - return operation; - } - - operation.AddError(_unitOfWork.LastSaveChangesResult.Exception); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemById.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemById.cs deleted file mode 100644 index 3ecf0e64..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemById.cs +++ /dev/null @@ -1,49 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.Queries; - -/// -/// EventItem by Identifier -/// -public class GetEventItemById -{ - public record Request(Guid Id) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request getting log by identifier - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(Request request, CancellationToken cancellationToken) - { - var id = request.Id; - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entityWithoutIncludes = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == id); - if (entityWithoutIncludes == null) - { - operation.AddError(new MicroserviceNotFoundException($"Entity with identifier {id} not found")); - return operation; - } - - operation.Result = _mapper.Map(entityWithoutIncludes); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/PostEventItem.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/PostEventItem.cs deleted file mode 100644 index f27c279f..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/PostEventItem.cs +++ /dev/null @@ -1,68 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.Queries; - -/// -/// Request: EventItem creation -/// -public class PostEventItem -{ - public record Request(EventItemCreateViewModel Model) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - private readonly ILogger _logger; - - - public Handler(IUnitOfWork unitOfWork, IMapper mapper, ILogger logger) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - _logger = logger; - } - - public async Task> Handle(Request eventItemRequest, CancellationToken cancellationToken) - { - _logger.LogDebug("Creating new EventItem"); - - var operation = OperationResult.CreateResult(); - - var entity = _mapper.Map(eventItemRequest.Model); - if (entity == null) - { - var exceptionMapper = new MicroserviceUnauthorizedException(AppContracts.Exceptions.MappingException); - operation.AddError(exceptionMapper); - _logger.LogError(exceptionMapper, "Mapper not configured correctly or something went wrong"); - return operation; - } - - await _unitOfWork.GetRepository().InsertAsync(entity, cancellationToken); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("Successfully created"); - _logger.LogInformation("New entity {@EventItem} successfully created", entity); - return operation; - } - - var exception = lastResult.Exception ?? new ApplicationException("Something went wrong"); - operation.AddError(exception); - _logger.LogError(exception, "Error data saving to Database or something went wrong"); - - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/UpdateEventItem.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/UpdateEventItem.cs deleted file mode 100644 index 95997c0b..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/UpdateEventItem.cs +++ /dev/null @@ -1,59 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.Queries; - -/// -/// Request: EventItem edit -/// -public class PutEventItem -{ - public record Request(Guid Id, EventItemUpdateViewModel Model) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task> Handle(Request eventItemRequest, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == eventItemRequest.Id, disableTracking: false); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException(AppContracts.Exceptions.NotFoundException)); - return operation; - } - - _mapper.Map(eventItemRequest.Model, entity); - - repository.Update(entity); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("Successfully updated"); - return operation; - } - - operation.AddError(lastResult.Exception ?? new ApplicationException("Something went wrong")); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/Queries/GetRoles.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/Queries/GetRoles.cs deleted file mode 100644 index 15b72397..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/Queries/GetRoles.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Calabonga.Microservices.Core; -using MediatR; -using System.Security.Claims; - -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileEndpoints.Queries; - -/// -/// Request: Returns user roles -/// -public class GetProfile -{ - public record Request : IRequest; - - public class Handler : IRequestHandler - { - private readonly ILogger _logger; - private readonly IHttpContextAccessor _httpContextAccessor; - - public Handler( - ILogger logger, - IHttpContextAccessor httpContextAccessor) - { - _logger = logger; - _httpContextAccessor = httpContextAccessor; - } - - public Task Handle(Request request, CancellationToken cancellationToken) - { - var user = _httpContextAccessor.HttpContext!.User; - var roles = ClaimsHelper.GetValues((ClaimsIdentity)user.Identity!, "role"); - var message = $"Current user ({user.Identity!.Name}) have following roles: {string.Join("|", roles)}"; - _logger.LogInformation(message); - return Task.FromResult(message); - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/Queries/RegisterAccount.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/Queries/RegisterAccount.cs deleted file mode 100644 index d5200454..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/Queries/RegisterAccount.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileEndpoints.ViewModels; -using Calabonga.Microservice.IdentityModule.Web.Application.Services; -using Calabonga.OperationResults; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileEndpoints.Queries; - -/// -/// Register new account -/// -public class RegisterAccount -{ - public class Request : IRequest> - { - public Request(RegisterViewModel model) => Model = model; - - public RegisterViewModel Model { get; } - } - - public class Handler : IRequestHandler> - { - private readonly IAccountService _accountService; - - public Handler(IAccountService accountService) - => _accountService = accountService; - - public Task> Handle(Request request, CancellationToken cancellationToken) - => _accountService.RegisterAsync(request.Model, cancellationToken); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DataSeeding/DataSeedingDefinition.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DataSeeding/DataSeedingDefinition.cs deleted file mode 100644 index bf0a4297..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DataSeeding/DataSeedingDefinition.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Infrastructure.DatabaseInitialization; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.DataSeeding; - -/// -/// Seeding DbContext for default data for EntityFrameworkCore -/// -public class DataSeedingDefinition : AppDefinition -{ - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) - { - DatabaseInitializer.SeedUsers(app.Services); - DatabaseInitializer.SeedEvents(app.Services); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/FluentValidating/ValidatorBehavior.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/FluentValidating/ValidatorBehavior.cs deleted file mode 100644 index 90227738..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/FluentValidating/ValidatorBehavior.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Calabonga.OperationResults; -using FluentValidation; -using MediatR; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.FluentValidating; - -/// -/// Base validator for requests -/// -/// -/// -public class ValidatorBehavior : IPipelineBehavior - where TRequest : IRequest -{ - private readonly IEnumerable> _validators; - - public ValidatorBehavior(IEnumerable> validators) => _validators = validators; - - /// - /// Pipeline handler. Perform any additional behavior and await the delegate as necessary - /// - /// Incoming request - /// Cancellation token - /// Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler. - /// Awaitable task returning the - public Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) - { - var failures = _validators - .Select(x => x.Validate(new ValidationContext(request))) - .SelectMany(x => x.Errors) - .Where(x => x != null) - .ToList(); - - if (!failures.Any()) - { - return next(); - } - - var type = typeof(TResponse); - if (!type.IsSubclassOf(typeof(OperationResult))) - { - throw new ValidationException(failures); - } - - var result = Activator.CreateInstance(type); - ((OperationResult)result!).AddError(new ValidationException(failures)); - return Task.FromResult((TResponse)result!); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/AuthorizationDefinition.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/AuthorizationDefinition.cs deleted file mode 100644 index f8a0918c..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/AuthorizationDefinition.cs +++ /dev/null @@ -1,53 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Authorization; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Identity; - -/// -/// Authorization Policy registration -/// -public class AuthorizationDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - public override void ConfigureServices(WebApplicationBuilder builder) - { - builder.Services - .AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; - }) - .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => - { - options.LoginPath = "/connect/login"; - }); - - builder.Services.AddAuthorization(); - builder.Services.AddSingleton(); - builder.Services.AddSingleton(); - } - - /// - /// Configure application for current application - /// - /// - /// - public override void ConfigureApplication(WebApplication app) - { - app.UseHttpsRedirection(); - app.UseRouting(); - app.UseCors("CorsPolicy"); - app.UseAuthentication(); - app.UseAuthorization(); - - // registering UserIdentity helper as singleton - UserIdentity.Instance.Configure(app.Services.GetService()!); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/UserIdentity.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/UserIdentity.cs deleted file mode 100644 index dde93011..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/UserIdentity.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Calabonga.Microservices.Core.Exceptions; -using System.Security.Claims; -using System.Security.Principal; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Identity; - -/// -/// Identity helper for Requests operations -/// -public sealed class UserIdentity -{ - private UserIdentity() { } - - public static UserIdentity Instance => Lazy.Value; - - public void Configure(IHttpContextAccessor httpContextAccessor) - { - ContextAccessor = httpContextAccessor ?? throw new MicroserviceArgumentNullException(nameof(IHttpContextAccessor)); - IsInitialized = true; - } - - public IIdentity? User - { - get - { - if (IsInitialized) - { - return ContextAccessor.HttpContext!.User.Identity != null - && ContextAccessor.HttpContext != null - && ContextAccessor.HttpContext.User.Identity.IsAuthenticated - ? ContextAccessor.HttpContext.User.Identity - : null; - } - throw new MicroserviceArgumentNullException($"{nameof(UserIdentity)} has not been initialized. Please use {nameof(UserIdentity)}.Instance.Configure(...) in Configure Application method in Startup.cs"); - } - } - - public IEnumerable Claims - { - get - { - if (User != null) - { - return ContextAccessor.HttpContext!.User.Claims; - } - return Enumerable.Empty(); - } - } - - private static readonly Lazy Lazy = new Lazy(() => new UserIdentity()); - - private bool IsInitialized { get; set; } - - private static IHttpContextAccessor ContextAccessor { get; set; } = null!; - -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/PagedListConverter.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/PagedListConverter.cs deleted file mode 100644 index 2414e948..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/PagedListConverter.cs +++ /dev/null @@ -1,23 +0,0 @@ -using AutoMapper; -using Calabonga.UnitOfWork; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Mapping; - -/// -/// Generic converter for IPagedList collections -/// -/// -/// -public class PagedListConverter : ITypeConverter, IPagedList> -{ - /// Performs conversion from source to destination type - /// Source object - /// Destination object - /// Resolution context - /// Destination object - public IPagedList Convert(IPagedList source, IPagedList destination, ResolutionContext context) => - // ReSharper disable once ConditionIsAlwaysTrueOrFalse - source == null - ? PagedList.Empty() - : PagedList.From(source, items => context.Mapper.Map>(items)); -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AuthData.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AuthData.cs deleted file mode 100644 index d1f7a410..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AuthData.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Microsoft.AspNetCore.Authentication.Cookies; -using OpenIddict.Validation.AspNetCore; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; - -public static class AuthData -{ - public const string AuthSchemes = CookieAuthenticationDefaults.AuthenticationScheme + "," + OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme; -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs deleted file mode 100644 index bfb18e4e..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.Options; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; - -/// -/// Policy provider -/// -public class AuthorizationPolicyProvider : DefaultAuthorizationPolicyProvider -{ - private readonly AuthorizationOptions _options; - - /// - public AuthorizationPolicyProvider(IOptions options) : base(options) => _options = options.Value; - - /// - public override async Task GetPolicyAsync(string policyName) - { - var policyExists = await base.GetPolicyAsync(policyName); - if (policyExists != null) - { - return policyExists; - } - - policyExists = new AuthorizationPolicyBuilder().AddRequirements(new PermissionRequirement(policyName)).Build(); - _options.AddPolicy(policyName, policyExists); - return policyExists; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/PermissionRequirement.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/PermissionRequirement.cs deleted file mode 100644 index 5817cc5e..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/PermissionRequirement.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Microsoft.AspNetCore.Authorization; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; - -/// -/// Permission requirement for user or service authorization -/// -public class PermissionRequirement : IAuthorizationRequirement -{ - public PermissionRequirement(string permissionName) => PermissionName = permissionName; - - /// - /// Permission name - /// - public string PermissionName { get; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Swagger/SwaggerDefinition.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Swagger/SwaggerDefinition.cs deleted file mode 100644 index db1576b3..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Swagger/SwaggerDefinition.cs +++ /dev/null @@ -1,130 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Domain.Base; -using Calabonga.Microservices.Core; -using Microsoft.AspNetCore.Mvc; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerUI; - -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Swagger; - -/// -/// Swagger definition for application -/// -public class SwaggerDefinition : AppDefinition -{ - // ATTENTION! - // If you use are git repository then you can uncomment line with "ThisAssembly" below for versioning by GIT possibilities. - // Otherwise, you can change versions of your API by manually. - // If you are not going to use git-versioning, do not forget install package "GitInfo" - // private const string AppVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - public const string AppVersion = "7.0.8"; - - private const string _swaggerConfig = "/swagger/v1/swagger.json"; - - public override void ConfigureApplication(WebApplication app) - { - if (!app.Environment.IsDevelopment()) - { - return; - } - - var url = app.Services.GetRequiredService().GetValue("AuthServer:Url"); - - app.UseSwagger(); - app.UseSwaggerUI(settings => - { - settings.SwaggerEndpoint(_swaggerConfig, $"{AppData.ServiceName} v.{AppVersion}"); - - // ATTENTION! - // If you use are git repository then you can uncomment line with "ThisAssembly" below for versioning by GIT possibilities. - // settings.HeadContent = $"{ThisAssembly.Git.Branch.ToUpper()} {ThisAssembly.Git.Commit.ToUpper()}"; - - settings.DocumentTitle = $"{AppData.ServiceName}"; - settings.DefaultModelExpandDepth(0); - settings.DefaultModelRendering(ModelRendering.Model); - settings.DefaultModelsExpandDepth(0); - settings.DocExpansion(DocExpansion.None); - settings.OAuthScopeSeparator(" "); - settings.OAuthClientId("client-id-code"); - settings.OAuthClientSecret("client-secret-code"); - settings.DisplayRequestDuration(); - settings.OAuthAppName(AppData.ServiceName); - settings.OAuth2RedirectUrl($"{url}/swagger/oauth2-redirect.html"); - }); - } - - public override void ConfigureServices(WebApplicationBuilder builder) - { - builder.Services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); - builder.Services.AddEndpointsApiExplorer(); - builder.Services.AddSwaggerGen(options => - { - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = AppData.ServiceName, - Version = AppVersion, - Description = AppData.ServiceDescription - }); - - options.ResolveConflictingActions(x => x.First()); - - options.TagActionsBy(api => - { - string tag; - if (api.ActionDescriptor is { } descriptor) - { - var attribute = descriptor.EndpointMetadata.OfType().FirstOrDefault(); - tag = attribute?.GroupName ?? descriptor.RouteValues["controller"] ?? "Untitled"; - } - else - { - tag = api.RelativePath!; - } - - var tags = new List(); - if (!string.IsNullOrEmpty(tag)) - { - tags.Add(tag); - } - return tags; - }); - - var url = builder.Configuration.GetSection("AuthServer").GetValue("Url"); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - AuthorizationCode = new OpenApiOAuthFlow - { - TokenUrl = new Uri($"{url}/connect/token", UriKind.Absolute), - AuthorizationUrl = new Uri($"{url}/connect/authorize", UriKind.Absolute), - Scopes = new Dictionary - { - { "api", "Default scope" } - } - } - } - }); - - options.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "oauth2" - }, - In = ParameterLocation.Cookie, - Type = SecuritySchemeType.OAuth2 - - }, - new List() - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemEndpoints.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemEndpoints.cs deleted file mode 100644 index ad9054ce..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemEndpoints.cs +++ /dev/null @@ -1,59 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.Queries; -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.ViewModels; -using Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; -using Calabonga.Microservices.Core; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints; - -public class EventItemEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("/api/event-items/{id:guid}", LogGetById); - app.MapGet("/api/event-items/paged", LogGetPaged); - app.MapPost("/api/event-items/", PostLog); - app.MapPut("/api/event-items/{id:guid}", PutLog); - app.MapDelete("/api/event-items/{id:guid}", LogDelete); - } - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogGetById([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new GetEventItemById.Request(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogDelete([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new DeleteEventItem.Request(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task>> LogGetPaged([FromServices] IMediator mediator, int pageIndex, int pageSize, string? search, HttpContext context) - => await mediator.Send(new GetEventItemPaged.Request(pageIndex, pageSize, search), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PostLog([FromServices] IMediator mediator, EventItemCreateViewModel model, HttpContext context) - => await mediator.Send(new PostEventItem.Request(model), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PutLog([FromServices] IMediator mediator, Guid id, EventItemUpdateViewModel model, HttpContext context) - => await mediator.Send(new PutEventItem.Request(id, model), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfilesEndpoints.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfilesEndpoints.cs deleted file mode 100644 index 33d0cb7d..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfilesEndpoints.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileEndpoints.Queries; -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileEndpoints.ViewModels; -using Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; -using Calabonga.Microservices.Core; -using Calabonga.OperationResults; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints; - -public class ProfilesEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("/api/profiles/get-roles", GetRoles); - app.MapPost("/api/profiles/register", RegisterAccount); - } - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("Profiles")] - private async Task GetRoles([FromServices] IMediator mediator, HttpContext context) - => await mediator.Send(new GetProfile.Request(), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [FeatureGroupName("Profiles")] - private async Task> RegisterAccount([FromServices] IMediator mediator, RegisterViewModel model, HttpContext context) - => await mediator.Send(new RegisterAccount.Request(model), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/TokenEndpoints.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/TokenEndpoints.cs deleted file mode 100644 index 11535e95..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/TokenEndpoints.cs +++ /dev/null @@ -1,111 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.Microservice.IdentityModule.Web.Application.Services; -using Calabonga.Microservices.Core.Extensions; -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Identity; -using OpenIddict.Abstractions; -using OpenIddict.Server.AspNetCore; -using System.Security.Claims; - -namespace Calabonga.Microservice.IdentityModule.Web.Endpoints; - -/// -/// Token Endpoint for OpenIddict -/// -public class TokenEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) => - app.MapPost("~/connect/token", TokenAsync).ExcludeFromDescription(); - - private async Task TokenAsync( - HttpContext httpContext, - IOpenIddictScopeManager manager, - UserManager userManager, - SignInManager signInManager, - IAccountService accountService) - { - var request = httpContext.GetOpenIddictServerRequest() ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); - //if (request.Scope is null) - //{ - // return Results.Problem("The specified grant type is not supported."); - //} - - if (request.IsClientCredentialsGrantType()) - { - var identity = new ClaimsIdentity(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - - // Subject or sub is a required field, we use the client id as the subject identifier here. - identity.AddClaim(OpenIddictConstants.Claims.Subject, request.ClientId!); - identity.AddClaim(OpenIddictConstants.Claims.ClientId, request.ClientId!); - - // Don't forget to add destination otherwise it won't be added to the access token. - if (request.Scope.IsNullOrEmpty()) - { - identity.AddClaim(OpenIddictConstants.Claims.Scope, request.Scope!, OpenIddictConstants.Destinations.AccessToken); - } - - identity.AddClaim("nimble", "framework", OpenIddictConstants.Destinations.AccessToken); - - var claimsPrincipal = new ClaimsPrincipal(identity); - - claimsPrincipal.SetScopes(request.GetScopes()); - return Results.SignIn(claimsPrincipal, new AuthenticationProperties(), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - } - - if (request.IsPasswordGrantType()) - { - if (request.Username != null) - { - var user = await userManager.FindByNameAsync(request.Username); - if (user == null) - { - return Results.Problem("Invalid operation"); - } - - // Ensure the user is allowed to sign in - if (!await signInManager.CanSignInAsync(user)) - { - return Results.Problem("Invalid operation"); - } - - - // Ensure the user is not already locked out - if (userManager.SupportsUserLockout && await userManager.IsLockedOutAsync(user)) - { - return Results.Problem("Invalid operation"); - } - - // Ensure the password is valid - if (request.Password != null && !await userManager.CheckPasswordAsync(user, request.Password)) - { - if (userManager.SupportsUserLockout) - { - await userManager.AccessFailedAsync(user); - } - - return Results.Problem("Invalid operation"); - } - - // Reset the lockout count - if (userManager.SupportsUserLockout) - { - await userManager.ResetAccessFailedCountAsync(user); - } - - var principal = await accountService.GetPrincipalForUserAsync(user); - return Results.SignIn(principal, null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - } - } - - if (request.IsAuthorizationCodeGrantType()) - { - var authenticateResult = await httpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - var claimsPrincipal = authenticateResult.Principal; - return Results.SignIn(claimsPrincipal!, null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - } - - return Results.Problem("The specified grant type is not supported."); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/HostedServices/OpenIddictWorker.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/HostedServices/OpenIddictWorker.cs deleted file mode 100644 index d3234d44..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/HostedServices/OpenIddictWorker.cs +++ /dev/null @@ -1,85 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Infrastructure; -using OpenIddict.Abstractions; - -namespace Calabonga.Microservice.IdentityModule.Web.HostedServices; - -public class OpenIddictWorker : IHostedService -{ - private readonly IServiceProvider _serviceProvider; - - public OpenIddictWorker(IServiceProvider serviceProvider) => _serviceProvider = serviceProvider; - - public async Task StartAsync(CancellationToken cancellationToken) - { - await using var scope = _serviceProvider.CreateAsyncScope(); - - var context = scope.ServiceProvider.GetRequiredService(); - await context.Database.EnsureCreatedAsync(cancellationToken); - - var manager = scope.ServiceProvider.GetRequiredService(); - - // credentials password - const string client_id1 = "client-id-sts"; - if (await manager.FindByClientIdAsync(client_id1, cancellationToken) is null) - { - await manager.CreateAsync(new OpenIddictApplicationDescriptor - { - ClientId = client_id1, - ClientSecret = "client-secret-sts", - DisplayName = "Service-To-Service demonstration", - Permissions = - { - // Endpoint permissions - OpenIddictConstants.Permissions.Endpoints.Token, - - // Grant type permissions - OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, - OpenIddictConstants.Permissions.GrantTypes.Password, - - // Scope permissions - OpenIddictConstants.Permissions.Prefixes.Scope + "api" - } - }, cancellationToken); - } - - const string client_id2 = "client-id-code"; - if (await manager.FindByClientIdAsync(client_id2, cancellationToken) is null) - { - var url = _serviceProvider.GetRequiredService().GetValue("AuthServer:Url"); - - await manager.CreateAsync(new OpenIddictApplicationDescriptor - { - ClientId = client_id2, - ConsentType = OpenIddictConstants.ConsentTypes.Implicit, - ClientSecret = "client-secret-code", - DisplayName = "API testing clients with Authorization Code Flow demonstration", - RedirectUris = { - new Uri("https://www.thunderclient.com/oauth/callback"), // https://www.thunderclient.com/ - new Uri($"{url}/swagger/oauth2-redirect.html"), // https://swagger.io/ - new Uri("https://localhost:20001/swagger/oauth2-redirect.html") // https://swagger.io/ for Module - }, - - Permissions = - { - // Endpoint permissions - OpenIddictConstants.Permissions.Endpoints.Authorization, - OpenIddictConstants.Permissions.Endpoints.Token, - - // Grant type permissions - OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, - OpenIddictConstants.Permissions.GrantTypes.RefreshToken, - - // Scope permissions - OpenIddictConstants.Permissions.Prefixes.Scope + "api", - OpenIddictConstants.Permissions.Prefixes.Scope + "custom", - - // Response types - OpenIddictConstants.Permissions.ResponseTypes.Code, - OpenIddictConstants.Permissions.ResponseTypes.IdToken - } - }, cancellationToken); - } - } - - public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml deleted file mode 100644 index ffe8abc3..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml +++ /dev/null @@ -1,33 +0,0 @@ -@page -@model Calabonga.Microservice.IdentityModule.Web.Pages.Connect.LoginModel - -
- -
- @if (Model.Input != null) - { -
- - - -
- -
- - - -
- -
- - - -
-
- -
- -
- } -
-
\ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml.cs deleted file mode 100644 index 377a3d93..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml.cs +++ /dev/null @@ -1,71 +0,0 @@ -using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.Microservice.IdentityModule.Web.Application.Services; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace Calabonga.Microservice.IdentityModule.Web.Pages.Connect; - -public class LoginModel : PageModel -{ - private readonly IAccountService _accountService; - private readonly SignInManager _signInManager; - private readonly UserManager _userManager; - - public LoginModel( - IAccountService accountService, - SignInManager signInManager, - UserManager userManager) - { - _accountService = accountService; - _signInManager = signInManager; - _userManager = userManager; - } - - [BindProperty(SupportsGet = true)] - public string? ReturnUrl { get; set; } - - [BindProperty] - public LoginViewModel? Input { get; set; } - - public void OnGet() => Input = new LoginViewModel - { - ReturnUrl = ReturnUrl - }; - - public async Task OnPostAsync() - { - if (!ModelState.IsValid) - { - return Page(); - } - - if (Input != null) - { - var user = await _userManager.FindByNameAsync(Input.UserName); - if (user == null) - { - ModelState.AddModelError("UserName", "Пользователь не найден"); - return Page(); - } - - var signInResult = await _signInManager.PasswordSignInAsync(user, Input.Password, true, false); - if (signInResult.Succeeded) - { - var principal = await _accountService.GetPrincipalByIdAsync(user.Id.ToString()); - await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); - - if (Url.IsLocalUrl(ReturnUrl)) - { - return Redirect(ReturnUrl); - } - return RedirectToPage("/swagger"); - } - } - - ModelState.AddModelError("UserName", "Пользователь не найден"); - return Page(); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewImports.cshtml b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewImports.cshtml deleted file mode 100644 index 9018c789..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewImports.cshtml +++ /dev/null @@ -1 +0,0 @@ -@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewStart.cshtml b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewStart.cshtml deleted file mode 100644 index 1af6e494..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewStart.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@{ - Layout = "_Layout"; -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Program.cs b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Program.cs deleted file mode 100644 index 28a019c7..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Program.cs +++ /dev/null @@ -1,77 +0,0 @@ -// -------------------------------------------------------------------- -// Name: Template for Micro service on ASP.NET Core API with -// OpenIddict (OAuth2.0) -// Author: Calabonga © 2005-2023 Calabonga SOFT -// Version: 7.0.8 -// Based on: .NET 7.0.x -// Created Date: 2022-11-12 09:29 -// Updated Date: 2023-09-24 09:08 -// -------------------------------------------------------------------- -// Contacts -// -------------------------------------------------------------------- -// Donate: https://boosty.to/calabonga/donate -// Blog: https://www.calabonga.net/blog/post/nimble-framework-7 -// GitHub: https://github.com/Calabonga/Microservice-Template -// BoostyTo: https://boosty.to/calabonga -// YouTube: https://youtube.com/sergeicalabonga -// DZen: https://dzen.ru/calabonga -// -------------------------------------------------------------------- -// Description: -// -------------------------------------------------------------------- -// Minimal API for NET7 used with Definitions. -// This template implements Web API and OpenIddict (OAuth2.0). -// functionality. Also, support two type of Authentication: -// Cookie and Bearer -// -------------------------------------------------------------------- - -using Calabonga.AspNetCore.AppDefinitions; -using Serilog; -using Serilog.Events; - -try -{ - // configure logger (Serilog) - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .Enrich.FromLogContext() - .WriteTo.Console() - .CreateLogger(); - - // created builder - var builder = WebApplication.CreateBuilder(args); - builder.Host.UseSerilog((context, configuration) => - configuration.ReadFrom.Configuration(context.Configuration)); - - // adding definitions for application - builder.AddDefinitions(typeof(Program)); - - // create application - var app = builder.Build(); - - // using definition for application - app.UseDefinitions(); - - // using Serilog request logging - app.UseSerilogRequestLogging(); - - // start application - app.Run(); - - return 0; -} -catch (Exception ex) -{ - var type = ex.GetType().Name; - if (type.Equals("HostAbortedException", StringComparison.Ordinal)) - { - throw; - } - - Log.Fatal(ex, "Unhandled exception"); - return 1; -} -finally -{ - Log.CloseAndFlush(); -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk b/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk deleted file mode 100644 index 54a03371..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk +++ /dev/null @@ -1 +0,0 @@ -{"alg":"RS256","d":"P7dPY7Wy3wuD_Vls0NBNsrY_j5o70JJk0beTptSFEspyvBlFSpG3wLSqWBqnbZzRmEWJ12Kdn8BgMiB8kzUQk3JjA16o6_USGLCKCnNkWBya4xJ0Yh63YjIVltMNHclsep70NjoTbI8G3UjOUXtKGYyqcC_FSWfmkPugVv7eQwWOasP60sXExfmGHQ5EV8NkVc4VBIkhEGolpVaUbISWg1Gf_CTj_iwm1FzosoUB6dlrQ-CAcYQT0gCRXeP85cnxUrfXQrExyzGC5ablHj9IBMWrUW9KmUqG42gvbuUmkv-0GolHj0DivQjJRMvOhmYzfw-FVly64cSQdYjrdVyiEQ","dp":"vaf7y9sBxE33PlS87g-5besW6OcDYmbL2fHc1Jaqp_tudjk3KE2g608qz18EFNxhduf7n7ACpTCLTLzqYgubGrzvgFWhqJhh2Ts2aEC_EWAnTTyzgq3F6_AwNlpsLYw-FDWU7lLRjgeYu2ZRJcQ1LtrFcBf8lv7EORfGcZ7zeh0","dq":"1mMVHzMx-LnIbaAFht5nce0-8pLj1zf25Jzghlm8Wgi0FAGI8b8V3edbVSJo1V8JdI_we4HjsmC3RA686Z1NsSXIaUxel44GdZXIYAiZA3N30gs5mT07MUPrglPeNm6LMYeYn5fsTk12TSIWTUMTmyW5BNvHTVQjH0dk7maJWzU","e":"AQAB","kid":"72F4E7F8D19F17C0FC47D7CF1FBF61DF","kty":"RSA","n":"sf6uR2CqoZHzcEex5KT54OC6iAd1I-dELjp16-xmkSuqWGOIyyFqqQ5kyxvMlayfSUbdcLTCswaAyomnbu3tUuvccgdhO_7BsFN8eaosYqgUmUP0htI6lirysnFxRxaA-4qozXrNTxMcoxF0hgTtgIg6R8hdKMfpOZi90D1XGZUsNe9GjRLDZZVssM-idookwqTeMmLKLGUZiQwOTc9QOplHYbL52turG3kSTjoOVrrCM1szm9j5VSfmXAug3QJXZe0x0twfBhym8rEljsgr4IopNe8RA4Msg6uZFHCc4rCRXd5xajlSug4g8r_lq0M64Ug4nzIe1kfpMjY8nHnr2Q","p":"0rSFb90z1tu6BxUUQuL3DwJNu6YrSCTunkkgq943YuTV1XO2KXTW1mZbbD_KnvUMRz9CDsnFts-8W6fh7g8-_zFnhnDS7_XoYa7Yf2Aw9hN2VTKGuDNZo9Vidj4jbejXddbY2L3n0qD_iR9PIXuDM_at9zj7xMk88A5NPFY57mM","q":"2EINjDxepSzyh6BPltt3iqExQrtgseUermliIjHc8kSx_j25azscTZC3MYU6hy7AMISqXBoAsc2GCyKfhQpcNlOWXYeRn-QgYzea5kog8OEM1-hneTzhCAbb8IUm7l_JZ11Se423OVKBA9bgg7yj8K94Hid3ayJOTIe4Rzjvo5M","qi":"pst6tRwkUiKMpWSJ2aMp2jsf_14s96c_bzOMoJUgk3T2LjOJ6TTXYW8uyYm76RXJALBbows73rk9sMaohv08MjXT_QCBCDHQGwb1cH07j2aXslkq-pjO7J8vOUvBhc4ZSWzqmyQEqLOC76N_vem1j39w_eu12TbFncQYitmEtBs"} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Common.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Common.cs deleted file mode 100644 index fadb6aa2..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Common.cs +++ /dev/null @@ -1,45 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain.Base -{ - /// - /// Static data container - /// - public static partial class AppData - { - /// - /// CORS Policy name - /// - public const string PolicyName = "CorsPolicy"; - - /// - /// Current service name - /// - public const string ServiceName = "Microservice Template"; - - /// - /// Nimble Framework Microservice Template with integrated OpenIddict for OpenID Connect server and Token Validation - /// - public const string ServiceDescription = "Nimble Framework Microservice Template with integrated OpenIddict for OpenID Connect server and Token Validation"; - - /// - /// "SystemAdministrator" - /// - public const string SystemAdministratorRoleName = "Administrator"; - - /// - /// "BusinessOwner" - /// - public const string ManagerRoleName = "Manager"; - - /// - /// Roles - /// - public static IEnumerable Roles - { - get - { - yield return SystemAdministratorRoleName; - yield return ManagerRoleName; - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Messages.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Messages.cs deleted file mode 100644 index 9af17e0b..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Messages.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain.Base -{ - public static partial class AppData - { - /// - /// Common messages - /// - public static class Messages - { - /// - /// "User successfully registered" - /// - public static string UserSuccessfullyRegistered => "User successfully registered"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IHaveId.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IHaveId.cs deleted file mode 100644 index 15403663..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IHaveId.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain.Base -{ - /// - /// Identifier common interface - /// - public interface IHaveId - { - /// - /// Identifier - /// - Guid Id { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IViewModel.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IViewModel.cs deleted file mode 100644 index 46fb5a42..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IViewModel.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain.Base -{ - /// - /// Represents ViewModel for CRUD controller - /// - public interface IViewModel { } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Identity.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Identity.cs deleted file mode 100644 index c6e68c46..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Identity.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain.Base -{ - /// - /// Identifier - /// - public abstract class Identity : IHaveId - { - /// - /// Identifier - /// - public Guid Id { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Sortable.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Sortable.cs deleted file mode 100644 index f285b70f..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Sortable.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain.Base -{ - /// - /// Order - /// - public class Sortable : Auditable - { - /// - /// Sorting index for entity - /// - public int SortIndex { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/TypeHelper.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/TypeHelper.cs deleted file mode 100644 index 180d17df..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/TypeHelper.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain.Base -{ - /// - /// Some helpful methods for Type manipulations - /// - public static class TypeHelper - { - /// - /// Check type before converting - /// - /// - /// - /// - public static bool CanChangeType(object value, Type conversionType) - { - if (conversionType == null) - { - return false; - } - return value is IConvertible; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/ViewModelBase.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/ViewModelBase.cs deleted file mode 100644 index 0c3ddd7d..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/ViewModelBase.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain.Base -{ - /// - /// ViewModelBase for WritableController - /// - public class ViewModelBase : IViewModel, IHaveId - { - /// - /// Identifier - /// - public Guid Id { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/EventItem.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/EventItem.cs deleted file mode 100644 index c90fec77..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/EventItem.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace Calabonga.Microservice.Module.Domain -{ - /// - /// EventItem entity for demo purposes only - /// - public class EventItem : Identity - { - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; - - public string? ThreadId { get; set; } - - public string? ExceptionMessage { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/GlobalUsing.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/GlobalUsing.cs deleted file mode 100644 index ee0fe29c..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/GlobalUsing.cs +++ /dev/null @@ -1 +0,0 @@ -global using Calabonga.Microservice.Module.Domain.Base; \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs deleted file mode 100644 index 8eae06cf..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Calabonga.Microservice.Module.Infrastructure.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Diagnostics; - -namespace Calabonga.Microservice.Module.Infrastructure -{ - /// - /// Database context for current application - /// - public class ApplicationDbContext : DbContextBase - { - public ApplicationDbContext(DbContextOptions options) - : base(options) { } - - public DbSet EventItems { get; set; } - - public DbSet Profiles { get; set; } - - public DbSet Permissions { get; set; } - - /// - /// - /// Override this method to configure the database (and other options) to be used for this context. - /// This method is called for each instance of the context that is created. - /// The base implementation does nothing. - /// - /// - /// In situations where an instance of may or may not have been passed - /// to the constructor, you can use to determine if - /// the options have already been set, and skip some or all of the logic in - /// . - /// - /// - /// - /// See DbContext lifetime, configuration, and initialization - /// for more information. - /// - /// - /// A builder used to create or modify options for this context. Databases (and other extensions) - /// typically define extension methods on this object that allow you to configure the context. - /// - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)); - - base.OnConfiguring(optionsBuilder); - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationRole.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationRole.cs deleted file mode 100644 index ff2f8e8d..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationRole.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Calabonga.Microservice.Module.Infrastructure -{ - /// - /// Application role - /// - public class ApplicationRole : IdentityRole - { - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/GlobalUsing.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/GlobalUsing.cs deleted file mode 100644 index ec7c9741..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/GlobalUsing.cs +++ /dev/null @@ -1,4 +0,0 @@ -global using Calabonga.Microservice.Module.Domain; -global using Calabonga.Microservice.Module.Domain.Base; -global using Microsoft.AspNetCore.Identity; -global using Microsoft.Extensions.DependencyInjection; \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/DeleteEventItem.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/DeleteEventItem.cs deleted file mode 100644 index 8ab5bc24..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/DeleteEventItem.cs +++ /dev/null @@ -1,57 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.Module.Domain; -using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.Queries; - -/// -/// Request: EventItem delete -/// -public class DeleteEventItem -{ - public record Request(Guid Id) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(Request request, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.FindAsync(request.Id); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException("Entity not found")); - return operation; - } - - repository.Delete(entity); - await _unitOfWork.SaveChangesAsync(); - if (_unitOfWork.LastSaveChangesResult.IsOk) - { - operation.Result = _mapper.Map(entity); - return operation; - } - - operation.AddError(_unitOfWork.LastSaveChangesResult.Exception); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemById.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemById.cs deleted file mode 100644 index 0b64173e..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemById.cs +++ /dev/null @@ -1,49 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.Module.Domain; -using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.Queries; - -/// -/// Request for EventItem by Identifier -/// -public class GetEventItemById -{ - public record Request(Guid Id) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request getting log by identifier - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(Request request, CancellationToken cancellationToken) - { - var id = request.Id; - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entityWithoutIncludes = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == id); - if (entityWithoutIncludes == null) - { - operation.AddError(new MicroserviceNotFoundException($"Entity with identifier {id} not found")); - return operation; - } - - operation.Result = _mapper.Map(entityWithoutIncludes); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/PostEventItem.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/PostEventItem.cs deleted file mode 100644 index 6e6f15c8..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/PostEventItem.cs +++ /dev/null @@ -1,68 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.Module.Domain; -using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.Queries; - -/// -/// Request: EventItem creation -/// -public class PostEventItem -{ - public record Request(EventItemCreateViewModel Model) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - private readonly ILogger _logger; - - - public Handler(IUnitOfWork unitOfWork, IMapper mapper, ILogger logger) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - _logger = logger; - } - - public async Task> Handle(Request eventItemRequest, CancellationToken cancellationToken) - { - _logger.LogDebug("Creating new EventItem"); - - var operation = OperationResult.CreateResult(); - - var entity = _mapper.Map(eventItemRequest.Model); - if (entity == null) - { - var exceptionMapper = new MicroserviceUnauthorizedException(AppContracts.Exceptions.MappingException); - operation.AddError(exceptionMapper); - _logger.LogError(exceptionMapper, "Mapper not configured correctly or something went wrong"); - return operation; - } - - await _unitOfWork.GetRepository().InsertAsync(entity, cancellationToken); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("Successfully created"); - _logger.LogInformation("New entity {@EventItem} successfully created", entity); - return operation; - } - - var exception = lastResult.Exception ?? new ApplicationException("Something went wrong"); - operation.AddError(exception); - _logger.LogError(exception, "Error data saving to Database or something went wrong"); - - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/UpdateEventItem.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/UpdateEventItem.cs deleted file mode 100644 index 5ea28197..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/UpdateEventItem.cs +++ /dev/null @@ -1,59 +0,0 @@ -using AutoMapper; -using Calabonga.Microservice.Module.Domain; -using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.Queries; - -/// -/// Request: EventItem edit -/// -public class PutEventItem -{ - public record Request(Guid Id, EventItemUpdateViewModel Model) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task> Handle(Request eventItemRequest, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == eventItemRequest.Id, disableTracking: false); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException(AppContracts.Exceptions.NotFoundException)); - return operation; - } - - _mapper.Map(eventItemRequest.Model, entity); - - repository.Update(entity); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("Successfully updated"); - return operation; - } - - operation.AddError(lastResult.Exception ?? new ApplicationException("Something went wrong")); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/Queries/GetRoles.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/Queries/GetRoles.cs deleted file mode 100644 index f0f38df3..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/Queries/GetRoles.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Calabonga.Microservices.Core; -using MediatR; -using System.Security.Claims; - -namespace Calabonga.Microservice.Module.Web.Application.Messaging.ProfileMessages.Queries; - -/// -/// Request: Returns user roles -/// -public class GetProfile -{ - public record Request : IRequest; - - public class Handler : IRequestHandler - { - private readonly ILogger _logger; - private readonly IHttpContextAccessor _httpContextAccessor; - - public Handler( - ILogger logger, - IHttpContextAccessor httpContextAccessor) - { - _logger = logger; - _httpContextAccessor = httpContextAccessor; - } - - public Task Handle(Request request, CancellationToken cancellationToken) - { - var user = _httpContextAccessor.HttpContext!.User; - var roles = ClaimsHelper.GetValues((ClaimsIdentity)user.Identity!, ClaimTypes.Role); - var message = $"Current user ({user.Identity!.Name}) have following roles: {string.Join("|", roles)}"; - _logger.LogInformation(message); - return Task.FromResult(message); - } - } -} diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj deleted file mode 100644 index 11d1e688..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj +++ /dev/null @@ -1,33 +0,0 @@ - - - - net7.0 - enable - enable - true - enable - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Cors/CorsDefinition.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Cors/CorsDefinition.cs deleted file mode 100644 index 1c3bd821..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Cors/CorsDefinition.cs +++ /dev/null @@ -1,46 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.Module.Domain.Base; - -namespace Calabonga.Microservice.Module.Web.Definitions.Cors; - -/// -/// Cors configurations -/// -public class CorsDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - public override void ConfigureServices(WebApplicationBuilder builder) - { - var origins = builder.Configuration.GetSection("Cors")?.GetSection("Origins")?.Value?.Split(','); - builder.Services.AddCors(options => - { - options.AddPolicy(AppData.PolicyName, builder => - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - if (origins is not { Length: > 0 }) - { - return; - } - - if (origins.Contains("*")) - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - builder.SetIsOriginAllowed(host => true); - builder.AllowCredentials(); - } - else - { - foreach (var origin in origins) - { - builder.WithOrigins(origin); - } - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/DataSeeding/DataSeedingDefinition.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/DataSeeding/DataSeedingDefinition.cs deleted file mode 100644 index 1f244aa0..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/DataSeeding/DataSeedingDefinition.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.Module.Infrastructure.DatabaseInitialization; - -namespace Calabonga.Microservice.Module.Web.Definitions.DataSeeding; - -/// -/// Seeding DbContext for default data for EntityFrameworkCore -/// -public class DataSeedingDefinition : AppDefinition -{ - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) - => DatabaseInitializer.Seed(app.Services); -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/FluentValidating/ValidatorBehavior.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/FluentValidating/ValidatorBehavior.cs deleted file mode 100644 index 69ae58cb..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/FluentValidating/ValidatorBehavior.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Calabonga.OperationResults; -using FluentValidation; -using MediatR; - -namespace Calabonga.Microservice.Module.Web.Definitions.FluentValidating; - -/// -/// Base validator for requests -/// -/// -/// -public class ValidatorBehavior : IPipelineBehavior - where TRequest : IRequest -{ - private readonly IEnumerable> _validators; - - public ValidatorBehavior(IEnumerable> validators) => _validators = validators; - - /// - /// Pipeline handler. Perform any additional behavior and await the delegate as necessary - /// - /// Incoming request - /// Cancellation token - /// Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler. - /// Awaitable task returning the - public Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) - { - var failures = _validators - .Select(x => x.Validate(new ValidationContext(request))) - .SelectMany(x => x.Errors) - .Where(x => x != null) - .ToList(); - - if (!failures.Any()) - { - return next(); - } - - var type = typeof(TResponse); - if (!type.IsSubclassOf(typeof(OperationResult))) - { - throw new ValidationException(failures); - } - - var result = Activator.CreateInstance(type); - ((OperationResult)result!).AddError(new ValidationException(failures)); - return Task.FromResult((TResponse)result!); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs deleted file mode 100644 index 4343d9a1..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Calabonga.UnitOfWork; -using MediatR; - -namespace Calabonga.Microservice.Module.Web.Definitions.Mediator.Base; - -/// -/// Transaction Behavior -/// -/// -/// -public class TransactionBehavior : IPipelineBehavior - where TRequest : IRequest -{ - private readonly IUnitOfWork _unitOfWork; - - public TransactionBehavior(IUnitOfWork unitOfWork) => _unitOfWork = unitOfWork; - - - public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) - { - await using var transaction = await _unitOfWork.BeginTransactionAsync(); - try - { - var response = await next(); - await transaction.CommitAsync(cancellationToken); - return response; - } - catch (Exception) - { - await transaction.RollbackAsync(cancellationToken); - throw; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AppPermissionHandler.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AppPermissionHandler.cs deleted file mode 100644 index afb91ae1..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AppPermissionHandler.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Calabonga.Microservices.Core; -using Microsoft.AspNetCore.Authorization; -using System.Security.Claims; - -namespace Calabonga.Microservice.Module.Web.Definitions.OpenIddict; - -/// -/// Permission handler for custom authorization implementations -/// -public class AppPermissionHandler : AuthorizationHandler -{ - /// - protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) - { - if (context.User.Identity is null) - { - return Task.CompletedTask; - } - - var identity = (ClaimsIdentity)context.User.Identity; - var claim = ClaimsHelper.GetValue(identity, requirement.PermissionName); - if (claim == null) - { - return Task.CompletedTask; - } - - context.Succeed(requirement); - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs deleted file mode 100644 index 9c783cd9..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.Options; - -namespace Calabonga.Microservice.Module.Web.Definitions.OpenIddict; - -/// -/// Policy provider -/// -public class AuthorizationPolicyProvider : DefaultAuthorizationPolicyProvider -{ - private readonly AuthorizationOptions _options; - - /// - public AuthorizationPolicyProvider(IOptions options) : base(options) => _options = options.Value; - - /// - public override async Task GetPolicyAsync(string policyName) - { - var policyExists = await base.GetPolicyAsync(policyName); - if (policyExists != null) - { - return policyExists; - } - - policyExists = new AuthorizationPolicyBuilder().AddRequirements(new PermissionRequirement(policyName)).Build(); - _options.AddPolicy(policyName, policyExists); - return policyExists; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/PermissionRequirement.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/PermissionRequirement.cs deleted file mode 100644 index 23b40a01..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/PermissionRequirement.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Microsoft.AspNetCore.Authorization; - -namespace Calabonga.Microservice.Module.Web.Definitions.OpenIddict; - -/// -/// Permission requirement for user or service authorization -/// -public class PermissionRequirement : IAuthorizationRequirement -{ - public PermissionRequirement(string permissionName) => PermissionName = permissionName; - - /// - /// Permission name - /// - public string PermissionName { get; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Swagger/SwaggerDefinition.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Swagger/SwaggerDefinition.cs deleted file mode 100644 index f91c50af..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Swagger/SwaggerDefinition.cs +++ /dev/null @@ -1,127 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.Module.Domain.Base; -using Calabonga.Microservices.Core; -using Microsoft.AspNetCore.Mvc; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerUI; - -namespace Calabonga.Microservice.Module.Web.Definitions.Swagger; - -/// -/// Swagger definition for application -/// -public class SwaggerDefinition : AppDefinition -{ - // ATTENTION! - // If you use are git repository then you can uncomment line with "ThisAssembly" below for versioning by GIT possibilities. - // Otherwise, you can change versions of your API by manually. - // If you are not going to use git-versioning, do not forget install package "GitInfo" - // private const string _appVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - private const string _appVersion = "7.0.8"; - - private const string _swaggerConfig = "/swagger/v1/swagger.json"; - - public override void ConfigureApplication(WebApplication app) - { - if (!app.Environment.IsDevelopment()) - { - return; - } - - app.UseSwagger(); - app.UseSwaggerUI(settings => - { - settings.SwaggerEndpoint(_swaggerConfig, $"{AppData.ServiceName} v.{_appVersion}"); - - // ATTENTION! - // If you use are git repository then you can uncomment line with "ThisAssembly" below for versioning by GIT possibilities. - // settings.HeadContent = $"{ThisAssembly.Git.Branch.ToUpper()} {ThisAssembly.Git.Commit.ToUpper()}"; - - settings.DocumentTitle = $"{AppData.ServiceName}"; - settings.DefaultModelExpandDepth(0); - settings.DefaultModelRendering(ModelRendering.Model); - settings.DefaultModelsExpandDepth(0); - settings.DocExpansion(DocExpansion.None); - settings.OAuthScopeSeparator(" "); - settings.OAuthClientId("client-id-code"); - settings.OAuthClientSecret("client-secret-code"); - settings.DisplayRequestDuration(); - settings.OAuthAppName(AppData.ServiceName); - }); - } - - public override void ConfigureServices(WebApplicationBuilder builder) - { - builder.Services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); - builder.Services.AddEndpointsApiExplorer(); - builder.Services.AddSwaggerGen(options => - { - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = AppData.ServiceName, - Version = _appVersion, - Description = AppData.ServiceDescription - }); - - options.ResolveConflictingActions(x => x.First()); - - options.TagActionsBy(api => - { - string tag; - if (api.ActionDescriptor is { } descriptor) - { - var attribute = descriptor.EndpointMetadata.OfType().FirstOrDefault(); - tag = attribute?.GroupName ?? descriptor.RouteValues["controller"] ?? "Untitled"; - } - else - { - tag = api.RelativePath!; - } - - var tags = new List(); - if (!string.IsNullOrEmpty(tag)) - { - tags.Add(tag); - } - return tags; - }); - - var url = builder.Configuration.GetSection("AuthServer").GetValue("Url"); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - AuthorizationCode = new OpenApiOAuthFlow - { - AuthorizationUrl = new Uri($"{url}/connect/authorize", UriKind.Absolute), - TokenUrl = new Uri($"{url}/connect/token", UriKind.Absolute), - Scopes = new Dictionary - { - { "api", "Default scope" } - } - } - } - }); - options.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "oauth2" - }, - Scheme = "oauth2", - Name = "Bearer", - In = ParameterLocation.Header, - - }, - new List() - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Endpoints/EventItemEndpoints.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Endpoints/EventItemEndpoints.cs deleted file mode 100644 index d814431b..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Endpoints/EventItemEndpoints.cs +++ /dev/null @@ -1,59 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.Queries; -using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.ViewModels; -using Calabonga.Microservice.Module.Web.Definitions.Identity; -using Calabonga.Microservices.Core; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.Module.Web.Endpoints; - -public class EventItemEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("/api/logs/{id}", LogGetById); - app.MapGet("/api/logs/paged", LogGetPaged); - app.MapPost("/api/logs/", PostLog); - app.MapPut("/api/logs/{id}", PutLog); - app.MapDelete("/api/logs/{id}", LogDelete); - } - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogGetById([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new GetEventItemById.Request(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogDelete([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new DeleteEventItem.Request(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task>> LogGetPaged([FromServices] IMediator mediator, int pageIndex, int pageSize, string? search, HttpContext context) - => await mediator.Send(new GetEventItemPaged.Request(pageIndex, pageSize, search), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PostLog([FromServices] IMediator mediator, EventItemCreateViewModel model, HttpContext context) - => await mediator.Send(new PostEventItem.Request(model), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PutLog([FromServices] IMediator mediator, Guid id, EventItemUpdateViewModel model, HttpContext context) - => await mediator.Send(new PutEventItem.Request(id, model), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Endpoints/ProfilesEndpoint.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Endpoints/ProfilesEndpoint.cs deleted file mode 100644 index 80693f69..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Endpoints/ProfilesEndpoint.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Calabonga.Microservice.Module.Web.Application.Messaging.ProfileMessages.Queries; -using Calabonga.Microservice.Module.Web.Definitions.Identity; -using Calabonga.Microservices.Core; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.Module.Web.Endpoints; - -public class ProfilesEndpointDefinition : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - => app.MapGet("/api/profiles/get-roles", GetRoles); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes, Policy = "EventItems:UserRoles:View")] - [FeatureGroupName("Profiles")] - private async Task GetRoles([FromServices] IMediator mediator, HttpContext context) - => await mediator.Send(new GetProfile.Request(), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Program.cs b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Program.cs deleted file mode 100644 index e667cea2..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Program.cs +++ /dev/null @@ -1,76 +0,0 @@ -// -------------------------------------------------------------------- -// Name: Template for Micro service on ASP.NET Core API with -// OpenIddict (OAuth2.0) -// Author: Calabonga © 2005-2023 Calabonga SOFT -// Version: 7.0.8 -// Based on: .NET 7.0.x -// Created Date: 2022-11-12 09:29 -// Updated Date: 2023-09-24 09:08 -// -------------------------------------------------------------------- -// Contacts -// -------------------------------------------------------------------- -// Donate: https://boosty.to/calabonga/donate -// Blog: https://www.calabonga.net/blog/post/nimble-framework-7 -// GitHub: https://github.com/Calabonga/Microservice-Template -// BoostyTo: https://boosty.to/calabonga -// YouTube: https://youtube.com/sergeicalabonga -// DZen: https://dzen.ru/calabonga -// -------------------------------------------------------------------- -// Description: -// -------------------------------------------------------------------- -// Minimal API for NET7 used with Definitions. -// This template implements Web API and OpenIddict (OAuth2.0) -// functionality. Also, support two type of Authentication: -// Cookie and Bearer -// -------------------------------------------------------------------- - -using Calabonga.AspNetCore.AppDefinitions; -using Serilog; -using Serilog.Events; - -try -{ - // configure logger (Serilog) - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Debug() - .MinimumLevel.Override("Microsoft", LogEventLevel.Information) - .Enrich.FromLogContext() - .WriteTo.Console() - .CreateLogger(); - - // created builder - var builder = WebApplication.CreateBuilder(args); - builder.Host.UseSerilog((context, configuration) => - configuration.ReadFrom.Configuration(context.Configuration)); - - builder.AddDefinitions(typeof(Program)); - - // create application - var app = builder.Build(); - - // using definition for application - app.UseDefinitions(); - - // using Serilog request logging - app.UseSerilogRequestLogging(); - - // start application - app.Run(); - - return 0; -} -catch (Exception ex) -{ - var type = ex.GetType().Name; - if (type.Equals("HostAbortedException", StringComparison.Ordinal)) - { - throw; - } - - Log.Fatal(ex, "Unhandled exception"); - return 1; -} -finally -{ - Log.CloseAndFlush(); -} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/readme.md b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/readme.md deleted file mode 100644 index 68a16080..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/readme.md +++ /dev/null @@ -1,29 +0,0 @@ -# Attentions - -Please find out all comments with 'ATTENTION!' because that is required some decisions from you - -# About - -| Name | Description | -| ------------ | ------------------------------------------ | -| Name | Microservice Template for ASP.NET Core API | -| Author | Calabonga SOFT © 2005-2023 Calabonga SOFT | -| Created Date | 2019-04-19 | - -# Versions - -Nimble Framework Templates build on .NET 7.0. That`s why it have the same major version. But the all improvements will increment minor versions. - -# Contacts - -You can contact me by using the next opportunities: - -* Donate: https://boosty.to/calabonga/donate -* Blog: https://www.calabonga.net -* GitHub: https://github.com/Calabonga -* Zen: https://dzen.ru/calabonga -* YouTube: https://youtube.com/sergeicalabonga - -# Description: - -This template implements Web API functionality using minmal API feature from NET 7.0 \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/tempkey.jwk b/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/tempkey.jwk deleted file mode 100644 index 54a03371..00000000 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/tempkey.jwk +++ /dev/null @@ -1 +0,0 @@ -{"alg":"RS256","d":"P7dPY7Wy3wuD_Vls0NBNsrY_j5o70JJk0beTptSFEspyvBlFSpG3wLSqWBqnbZzRmEWJ12Kdn8BgMiB8kzUQk3JjA16o6_USGLCKCnNkWBya4xJ0Yh63YjIVltMNHclsep70NjoTbI8G3UjOUXtKGYyqcC_FSWfmkPugVv7eQwWOasP60sXExfmGHQ5EV8NkVc4VBIkhEGolpVaUbISWg1Gf_CTj_iwm1FzosoUB6dlrQ-CAcYQT0gCRXeP85cnxUrfXQrExyzGC5ablHj9IBMWrUW9KmUqG42gvbuUmkv-0GolHj0DivQjJRMvOhmYzfw-FVly64cSQdYjrdVyiEQ","dp":"vaf7y9sBxE33PlS87g-5besW6OcDYmbL2fHc1Jaqp_tudjk3KE2g608qz18EFNxhduf7n7ACpTCLTLzqYgubGrzvgFWhqJhh2Ts2aEC_EWAnTTyzgq3F6_AwNlpsLYw-FDWU7lLRjgeYu2ZRJcQ1LtrFcBf8lv7EORfGcZ7zeh0","dq":"1mMVHzMx-LnIbaAFht5nce0-8pLj1zf25Jzghlm8Wgi0FAGI8b8V3edbVSJo1V8JdI_we4HjsmC3RA686Z1NsSXIaUxel44GdZXIYAiZA3N30gs5mT07MUPrglPeNm6LMYeYn5fsTk12TSIWTUMTmyW5BNvHTVQjH0dk7maJWzU","e":"AQAB","kid":"72F4E7F8D19F17C0FC47D7CF1FBF61DF","kty":"RSA","n":"sf6uR2CqoZHzcEex5KT54OC6iAd1I-dELjp16-xmkSuqWGOIyyFqqQ5kyxvMlayfSUbdcLTCswaAyomnbu3tUuvccgdhO_7BsFN8eaosYqgUmUP0htI6lirysnFxRxaA-4qozXrNTxMcoxF0hgTtgIg6R8hdKMfpOZi90D1XGZUsNe9GjRLDZZVssM-idookwqTeMmLKLGUZiQwOTc9QOplHYbL52turG3kSTjoOVrrCM1szm9j5VSfmXAug3QJXZe0x0twfBhym8rEljsgr4IopNe8RA4Msg6uZFHCc4rCRXd5xajlSug4g8r_lq0M64Ug4nzIe1kfpMjY8nHnr2Q","p":"0rSFb90z1tu6BxUUQuL3DwJNu6YrSCTunkkgq943YuTV1XO2KXTW1mZbbD_KnvUMRz9CDsnFts-8W6fh7g8-_zFnhnDS7_XoYa7Yf2Aw9hN2VTKGuDNZo9Vidj4jbejXddbY2L3n0qD_iR9PIXuDM_at9zj7xMk88A5NPFY57mM","q":"2EINjDxepSzyh6BPltt3iqExQrtgseUermliIjHc8kSx_j25azscTZC3MYU6hy7AMISqXBoAsc2GCyKfhQpcNlOWXYeRn-QgYzea5kog8OEM1-hneTzhCAbb8IUm7l_JZ11Se423OVKBA9bgg7yj8K94Hid3ayJOTIe4Rzjvo5M","qi":"pst6tRwkUiKMpWSJ2aMp2jsf_14s96c_bzOMoJUgk3T2LjOJ6TTXYW8uyYm76RXJALBbows73rk9sMaohv08MjXT_QCBCDHQGwb1cH07j2aXslkq-pjO7J8vOUvBhc4ZSWzqmyQEqLOC76N_vem1j39w_eu12TbFncQYitmEtBs"} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Common.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Common.cs deleted file mode 100644 index 387b870e..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Common.cs +++ /dev/null @@ -1,46 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Static data container -/// -public static partial class AppData -{ - /// - /// Current service name - /// - public const string ServiceName = "Microservice Template with OpenIddict"; - - /// - /// Nimble Framework Microservice Template with integrated OpenIddict - /// for OpenID Connect server and Token Validation - /// - public const string ServiceDescription = "Nimble Framework Microservice Template with integrated OpenIddict for OpenID Connect server and Token Validation"; - - /// - /// Default policy name - /// - public const string PolicyName = "CorsPolicy"; - - /// - /// "SystemAdministrator" - /// - public const string SystemAdministratorRoleName = "Administrator"; - - /// - /// "BusinessOwner" - /// - public const string ManagerRoleName = "Manager"; - - - /// - /// Roles - /// - public static IEnumerable Roles - { - get - { - yield return SystemAdministratorRoleName; - yield return ManagerRoleName; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Exceptions.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Exceptions.cs deleted file mode 100644 index 9ca24ec3..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Exceptions.cs +++ /dev/null @@ -1,60 +0,0 @@ -namespace $safeprojectname$.Base; - -public static partial class AppData -{ - /// - /// Exception messages - /// - public static class Exceptions - { - /// - /// "An exception was thrown" - /// - public static string ThrownException => "An exception was thrown"; - - /// - /// "Invalid cast exception" - /// - public static string TypeConverterException => "Invalid cast exception"; - - /// - /// "User not registered in the system" - /// - public static string UserNotFoundException => "User not registered in the system"; - - /// - /// "Object not found" - /// - public static string NotFoundException => "Object not found"; - - /// - /// "Unauthorized access denied" - /// - public static string UnauthorizedException => "Unauthorized access denied"; - - /// - /// "Argument null exception" - /// - public static string ArgumentNullException => "Argument null exception"; - - /// - /// "File already exists" - /// - public static string FileAlreadyExists => "File already exists"; - - /// - /// "Some errors occurred while checking the entity" - /// - public static string EntityValidationException => "Some errors occurred while checking the entity"; - - /// - /// "Invalid operation exception was thrown" - /// - public static string InvalidOperationException => "Invalid operation exception was thrown"; - - /// - /// "Argument out of range" - /// - public static string ArgumentOutOfRangeException => "Argument out of range"; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Messages.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Messages.cs deleted file mode 100644 index 4e00b9ed..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/AppData.Messages.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace $safeprojectname$.Base; - -public static partial class AppData -{ - /// - /// Common messages - /// - public static class Messages - { - /// - /// "User successfully registered" - /// - public static string UserSuccessfullyRegistered => "User successfully registered"; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/Auditable.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/Auditable.cs deleted file mode 100644 index 76eb902c..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/Auditable.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Represents 'Audit-able' table from the Property Database -/// -public abstract class Auditable : Identity, IAuditable -{ - /// - /// DateTime when entity created. - /// It's never changed - /// - public DateTime CreatedAt { get; set; } - - /// - /// User name who created entity. - /// It's never changed - /// - public string CreatedBy { get; set; } - - /// - /// Last date entity updated - /// - public DateTime? UpdatedAt { get; set; } - - /// - /// Author of last updated - /// - public string UpdatedBy { get; set; } - -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/IAuditable.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/IAuditable.cs deleted file mode 100644 index c7026a64..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/IAuditable.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Represent information about creation and last update -/// -public interface IAuditable -{ - /// - /// DateTime of creation. This value will never changed - /// - DateTime CreatedAt { get; set; } - - /// - /// Author name. This value never changed - /// - string CreatedBy { get; set; } - - /// - /// DateTime of last value update. Should be updated when entity data updated - /// - DateTime? UpdatedAt { get; set; } - - /// - /// Author of last value update. Should be updated when entity data updated - /// - string UpdatedBy { get; set; } - -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/IHaveId.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/IHaveId.cs deleted file mode 100644 index 829eaed7..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/IHaveId.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Identifier common interface -/// -public interface IHaveId -{ - /// - /// Identifier - /// - Guid Id { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/IViewModel.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/IViewModel.cs deleted file mode 100644 index 4afc0b1f..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/IViewModel.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Represents ViewModel for CRUD controller -/// -public interface IViewModel { } \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/Identity.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/Identity.cs deleted file mode 100644 index 8fd4099e..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/Identity.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Identifier -/// -public abstract class Identity : IHaveId -{ - /// - /// Identifier - /// - public Guid Id { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/NamedAuditable.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/NamedAuditable.cs deleted file mode 100644 index 1aa2d784..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/NamedAuditable.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Audit-able with name -/// -public abstract class NamedAuditable : Auditable -{ - public string Name { get; set; } - - public string Description { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/NamedIdentity.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/NamedIdentity.cs deleted file mode 100644 index 45b5d66f..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/NamedIdentity.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// NamedIdentity dictionary for selector -/// -public abstract class NamedIdentity : Identity -{ - /// - /// Entity name - /// - public string Name { get; set; } - - /// - /// Entity brief name - /// - public string BriefName { get; set; } - - /// - /// Brief descriptions - /// - public string Description { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/Sortable.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/Sortable.cs deleted file mode 100644 index ce0b2ce8..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/Sortable.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Order -/// -public class Sortable : Auditable -{ - /// - /// Sorting index for entity - /// - public int SortIndex { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/TypeHelper.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/TypeHelper.cs deleted file mode 100644 index f5d84f70..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/TypeHelper.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// Some helpful methods for Type manipulations -/// -public static class TypeHelper -{ - /// - /// Check type before converting - /// - /// - /// - /// - public static bool CanChangeType(object value, Type conversionType) - { - if (conversionType == null) - { - return false; - } - return value is IConvertible; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/ViewModelBase.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/ViewModelBase.cs deleted file mode 100644 index 218dd783..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/BASE/ViewModelBase.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace $safeprojectname$.Base; - -/// -/// ViewModelBase for -/// -public class ViewModelBase : IViewModel, IHaveId -{ - /// - /// Identifier - /// - public Guid Id { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj deleted file mode 100644 index a1ed5b3f..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - - net7.0 - enable - enable - - - diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/EventItem.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/EventItem.cs deleted file mode 100644 index e3433e39..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/EventItem.cs +++ /dev/null @@ -1,21 +0,0 @@ -using $safeprojectname$.Base; - -namespace $safeprojectname$; - -/// -/// EventItem entity for demo purposes only -/// -public class EventItem : Identity -{ - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; - - public string? ThreadId { get; set; } - - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/MyTemplate.vstemplate b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/MyTemplate.vstemplate deleted file mode 100644 index 82649efb..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/MyTemplate.vstemplate +++ /dev/null @@ -1,38 +0,0 @@ - - - Calabonga.Microservice.IdentityModule.Domain - Calabonga.Microservice.IdentityModule.Domain - CSharp - - - 1000 - true - Calabonga.Microservice.IdentityModule.Domain - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - AppData.Common.cs - AppData.Exceptions.cs - AppData.Messages.cs - Auditable.cs - IAuditable.cs - Identity.cs - IHaveId.cs - IViewModel.cs - NamedAuditable.cs - NamedIdentity.cs - Sortable.cs - TypeHelper.cs - ViewModelBase.cs - - EventItem.cs - - - \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/__PreviewImage.png b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/__PreviewImage.png deleted file mode 100644 index a75ffa16..00000000 Binary files a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/__TemplateIcon.png b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Domain/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/AppPermission.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/AppPermission.cs deleted file mode 100644 index be8cdeb1..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/AppPermission.cs +++ /dev/null @@ -1,29 +0,0 @@ -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$; - -/// -/// User permission for application -/// -public class AppPermission : Auditable -{ - /// - /// Application User profile identifier - /// - public Guid ApplicationUserProfileId { get; set; } - - /// - /// Application User Profile - /// - public virtual ApplicationUserProfile? ApplicationUserProfile { get; set; } - - /// - /// Authorize attribute policy name - /// - public string PolicyName { get; set; } = null!; - - /// - /// Description for current permission - /// - public string Description { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs deleted file mode 100644 index a83ca5c3..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs +++ /dev/null @@ -1,49 +0,0 @@ -using $ext_projectname$.Domain; -using $safeprojectname$.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Design; -using Microsoft.EntityFrameworkCore.Diagnostics; - -namespace $safeprojectname$; - -/// -/// Database context for current application -/// -public class ApplicationDbContext : DbContextBase -{ - public ApplicationDbContext(DbContextOptions options) - : base(options) { } - - public DbSet EventItems { get; set; } - - public DbSet Profiles { get; set; } - - public DbSet Permissions { get; set; } - - protected override void OnModelCreating(ModelBuilder builder) - { - builder.UseOpenIddict(); - base.OnModelCreating(builder); - } - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - // It should be removed when using real Database (not in memory mode) - optionsBuilder.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)); - base.OnConfiguring(optionsBuilder); - } -} - -///// -///// ATTENTION! -///// It should uncomment two line below when using real Database (not in memory mode). Don't forget update connection string. -///// -//public class ApplicationDbContextFactory : IDesignTimeDbContextFactory -//{ -// public ApplicationDbContext CreateDbContext(string[] args) -// { -// var optionsBuilder = new DbContextOptionsBuilder(); -// optionsBuilder.UseSqlServer("Server=;Database=;User ID=;Password="); -// return new ApplicationDbContext(optionsBuilder.Options); -// } -//} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRole.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRole.cs deleted file mode 100644 index ebd1b27b..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRole.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Microsoft.AspNetCore.Identity; - -namespace $safeprojectname$; - -/// -/// Application role -/// -public class ApplicationRole : IdentityRole -{ -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRoleStore.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRoleStore.cs deleted file mode 100644 index 92ef4948..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRoleStore.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -namespace $safeprojectname$; - -/// -/// Application store for user -/// -public class ApplicationRoleStore : RoleStore -{ - public ApplicationRoleStore(ApplicationDbContext context, IdentityErrorDescriber describer = null) : base(context, describer) - { - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUser.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUser.cs deleted file mode 100644 index acf4fa79..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUser.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Microsoft.AspNetCore.Identity; - -namespace $safeprojectname$; - -/// -/// Default user for application. -/// Add profile data for application users by adding properties to the ApplicationUser class -/// -public class ApplicationUser : IdentityUser -{ - /// - /// FirstName - /// - public string? FirstName { get; set; } - - /// - /// LastName - /// - public string? LastName { get; set; } - - /// - /// Profile identity - /// - public Guid? ApplicationUserProfileId { get; set; } - - /// - /// User Profile - /// - public virtual ApplicationUserProfile? ApplicationUserProfile { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserProfile.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserProfile.cs deleted file mode 100644 index 6b14bb02..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserProfile.cs +++ /dev/null @@ -1,19 +0,0 @@ -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$; - -/// -/// Represent person with login information (ApplicationUser) -/// -public class ApplicationUserProfile : Auditable -{ - /// - /// Account - /// - public virtual ApplicationUser? ApplicationUser { get; set; } - - /// - /// Application permission for policy-based authorization - /// - public List? Permissions { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserStore.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserStore.cs deleted file mode 100644 index 950fe52e..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserStore.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; - -namespace $safeprojectname$; - -/// -/// Application store for user -/// -public class ApplicationUserStore : UserStore -{ - public ApplicationUserStore(ApplicationDbContext context, IdentityErrorDescriber describer) - : base(context, describer) - { - - } - - /// - /// Finds and returns a user, if any, who has the specified . - /// - /// The user ID to search for. - /// The used to propagate notifications that the operation should be canceled. - /// - /// The that represents the asynchronous operation, containing the user matching the specified if it exists. - /// - public override Task FindByIdAsync(string userId, CancellationToken cancellationToken = default) - => Users - .Include(x => x.ApplicationUserProfile).ThenInclude(x => x.Permissions) - .FirstOrDefaultAsync(u => u.Id.ToString() == userId, cancellationToken: cancellationToken)!; - - public override Task FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default) - => Users - .Include(x => x.ApplicationUserProfile).ThenInclude(x => x.Permissions) - .FirstOrDefaultAsync(u => u.NormalizedUserName == normalizedUserName, cancellationToken: cancellationToken)!; -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/BASE/DbContextBase.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/BASE/DbContextBase.cs deleted file mode 100644 index 5db95c51..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/BASE/DbContextBase.cs +++ /dev/null @@ -1,257 +0,0 @@ -using $ext_projectname$.Domain.Base; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; -using System.Reflection; - -namespace $safeprojectname$.Base; - -/// -/// Base DbContext with predefined configuration -/// -public abstract class DbContextBase : IdentityDbContext -{ - private const string DefaultUserName = "Anonymous"; - - protected DbContextBase(DbContextOptions options) : base(options) - { - LastSaveChangesResult = new SaveChangesResult(); - } - - public SaveChangesResult LastSaveChangesResult { get; } - - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - /// - /// Saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// The number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override int SaveChanges(bool acceptAllChangesOnSuccess) - { - try - { - DbSaveChanges(); - return base.SaveChanges(acceptAllChangesOnSuccess); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - public override int SaveChanges() - { - try - { - DbSaveChanges(); - return base.SaveChanges(); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - private void DbSaveChanges() - { - var createdEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added); - foreach (var entry in createdEntries) - { - if (!(entry.Entity is IAuditable)) - { - continue; - } - - var creationDate = DateTime.Now.ToUniversalTime(); - var userName = entry.Property("CreatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("CreatedBy").CurrentValue; - var updatedAt = entry.Property("UpdatedAt").CurrentValue; - var createdAt = entry.Property("CreatedAt").CurrentValue; - if (createdAt != null) - { - if (DateTime.Parse(createdAt.ToString()).Year > 1970) - { - entry.Property("CreatedAt").CurrentValue = ((DateTime)createdAt).ToUniversalTime(); - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - - if (updatedAt != null) - { - if (DateTime.Parse(updatedAt.ToString()).Year > 1970) - { - entry.Property("UpdatedAt").CurrentValue = ((DateTime)updatedAt).ToUniversalTime(); - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - - entry.Property("CreatedBy").CurrentValue = userName; - entry.Property("UpdatedBy").CurrentValue = userName; - - LastSaveChangesResult.AddMessage($"ChangeTracker has new entities: {entry.Entity.GetType()}"); - } - - var updatedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified); - foreach (var entry in updatedEntries) - { - if (entry.Entity is IAuditable) - { - var userName = entry.Property("UpdatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("UpdatedBy").CurrentValue; - entry.Property("UpdatedAt").CurrentValue = DateTime.Now.ToUniversalTime(); - entry.Property("UpdatedBy").CurrentValue = userName; - } - - LastSaveChangesResult.AddMessage($"ChangeTracker has modified entities: {entry.Entity.GetType()}"); - } - } - - /// - /// Configures the schema needed for the identity framework. - /// - /// - /// The builder being used to construct the model for this context. - /// - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - var applyGenericMethod = typeof(ModelBuilder).GetMethods(BindingFlags.Instance | BindingFlags.Public).First(x => x.Name == "ApplyConfiguration"); - foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters)) - { - foreach (var item in type.GetInterfaces()) - { - if (!item.IsConstructedGenericType || item.GetGenericTypeDefinition() != typeof(IEntityTypeConfiguration<>)) - { - continue; - } - - var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(item.GenericTypeArguments[0]); - applyConcreteMethod.Invoke(builder, new[] { Activator.CreateInstance(type) }); - break; - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj deleted file mode 100644 index 9a6ca5da..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj +++ /dev/null @@ -1,29 +0,0 @@ - - - - net7.0 - enable - enable - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/DATABASEINITIALIZATION/DatabaseInitializer.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/DATABASEINITIALIZATION/DatabaseInitializer.cs deleted file mode 100644 index 5706b74b..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/DATABASEINITIALIZATION/DatabaseInitializer.cs +++ /dev/null @@ -1,146 +0,0 @@ -using $ext_projectname$.Domain; -using $ext_projectname$.Domain.Base; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; - -namespace $safeprojectname$.DatabaseInitialization; - -/// -/// Database Initializer -/// -public static class DatabaseInitializer -{ - /// - /// Seeds one default users to database for demo purposes only - /// - /// - /// - public static async void SeedUsers(IServiceProvider serviceProvider) - { - using var scope = serviceProvider.CreateScope(); - await using var context = scope.ServiceProvider.GetService(); - - // ATTENTION! - // ----------------------------------------------------------------------------- - // This is should not be used when UseInMemoryDatabase() - // It should be uncomment when using UseSqlServer() settings or any other providers. - // ----------------------------------------------------------------------------- - //await context!.Database.EnsureCreatedAsync(); - //var pending = await context.Database.GetPendingMigrationsAsync(); - //if (pending.Any()) - //{ - // await context!.Database.MigrateAsync(); - //} - - if (context.Users.Any()) - { - return; - } - - var roles = AppData.Roles.ToArray(); - - foreach (var role in roles) - { - var roleManager = scope.ServiceProvider.GetRequiredService>(); - if (!context!.Roles.Any(r => r.Name == role)) - { - await roleManager.CreateAsync(new ApplicationRole { Name = role, NormalizedName = role.ToUpper() }); - } - } - - #region developer - - var developer1 = new ApplicationUser - { - Email = "microservice@yopmail.com", - NormalizedEmail = "MICROSERVICE@YOPMAIL.COM", - UserName = "microservice@yopmail.com", - FirstName = "Microservice", - LastName = "Administrator", - NormalizedUserName = "MICROSERVICE@YOPMAIL.COM", - PhoneNumber = "+79000000000", - EmailConfirmed = true, - PhoneNumberConfirmed = true, - SecurityStamp = Guid.NewGuid().ToString("D"), - ApplicationUserProfile = new ApplicationUserProfile - { - CreatedAt = DateTime.Now, - CreatedBy = "SEED", - Permissions = new List - { - new() - { - CreatedAt = DateTime.Now, - CreatedBy = "SEED", - PolicyName = "EventItems:UserRoles:View", - Description = "Access policy for EventItems controller user view" - } - } - } - }; - - if (!context!.Users.Any(u => u.UserName == developer1.UserName)) - { - var password = new PasswordHasher(); - var hashed = password.HashPassword(developer1, "123qwe!@#"); - developer1.PasswordHash = hashed; - var userStore = scope.ServiceProvider.GetRequiredService(); - var result = await userStore.CreateAsync(developer1); - if (!result.Succeeded) - { - throw new InvalidOperationException("Cannot create account"); - } - - var userManager = scope.ServiceProvider.GetService>(); - foreach (var role in roles) - { - var roleAdded = await userManager!.AddToRoleAsync(developer1, role); - if (roleAdded.Succeeded) - { - await context.SaveChangesAsync(); - } - } - } - - #endregion - - await context.SaveChangesAsync(); - } - - /// - /// Seeds one event to database for demo purposes only - /// - /// - public static async void SeedEvents(IServiceProvider serviceProvider) - { - using var scope = serviceProvider.CreateScope(); - await using var context = scope.ServiceProvider.GetService(); - - // ATTENTION! - // ----------------------------------------------------------------------------- - // This is should not be used when UseInMemoryDatabase() - // It should be uncomment when using UseSqlServer() settings or any other providers. - // ----------------------------------------------------------------------------- - //await context!.Database.EnsureCreatedAsync(); - //var pending = await context.Database.GetPendingMigrationsAsync(); - //if (pending.Any()) - //{ - // await context!.Database.MigrateAsync(); - //} - - if (context.EventItems.Any()) - { - return; - } - - await context.EventItems.AddAsync(new EventItem - { - CreatedAt = DateTime.UtcNow, - Id = Guid.Parse("1467a5b9-e61f-82b0-425b-7ec75f5c5029"), - Level = "Information", - Logger = "SEED", - Message = "Seed method some entities successfully save to ApplicationDbContext" - }); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/MyTemplate.vstemplate b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/MyTemplate.vstemplate deleted file mode 100644 index dea56f43..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/MyTemplate.vstemplate +++ /dev/null @@ -1,35 +0,0 @@ - - - Calabonga.Microservice.IdentityModule.Infrastructure - Calabonga.Microservice.IdentityModule.Infrastructure - CSharp - - - 1000 - true - Calabonga.Microservice.IdentityModule.Infrastructure - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - DbContextBase.cs - - - DatabaseInitializer.cs - - ApplicationDbContext.cs - ApplicationRole.cs - ApplicationRoleStore.cs - ApplicationUser.cs - ApplicationUserProfile.cs - ApplicationUserStore.cs - AppPermission.cs - - - \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/__PreviewImage.png b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/__PreviewImage.png deleted file mode 100644 index a75ffa16..00000000 Binary files a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/__TemplateIcon.png b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/APPLICATION/FeatureGroupNameAttribute.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/APPLICATION/FeatureGroupNameAttribute.cs deleted file mode 100644 index 9e4d374b..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/APPLICATION/FeatureGroupNameAttribute.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace $safeprojectname$.Application; - -/// -/// Swagger controller group attribute -/// -/// -[AttributeUsage(AttributeTargets.Method)] -public class FeatureGroupNameAttribute : Attribute -{ - /// - public FeatureGroupNameAttribute(string groupName) => GroupName = groupName; - - /// - /// Group name - /// - public string GroupName { get; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/APPLICATION/SERVICES/AccountService.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/APPLICATION/SERVICES/AccountService.cs deleted file mode 100644 index 1dd2e400..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/APPLICATION/SERVICES/AccountService.cs +++ /dev/null @@ -1,239 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain.Base; -using $ext_projectname$.Infrastructure; -using $safeprojectname$.Definitions.Identity; -using $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.Microservices.Core.Extensions; -using Calabonga.Microservices.Core.Validators; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using OpenIddict.Abstractions; -using System.Security.Claims; - -namespace $safeprojectname$.Application.Services; - -/// -/// Account service -/// -public class AccountService : IAccountService -{ - private readonly IUnitOfWork _unitOfWork; - private readonly ILogger _logger; - private readonly ApplicationUserClaimsPrincipalFactory _claimsFactory; - private readonly IHttpContextAccessor _httpContext; - private readonly IMapper _mapper; - private readonly UserManager _userManager; - private readonly RoleManager _roleManager; - - public AccountService( - IUserStore userStore, - IOptions optionsAccessor, - IPasswordHasher passwordHasher, - IEnumerable> userValidators, - IEnumerable> passwordValidators, - ILookupNormalizer keyNormalizer, - IdentityErrorDescriber errors, - IServiceProvider services, - ILogger> loggerRole, - IEnumerable> roleValidators, - IUnitOfWork unitOfWork, - ILogger logger, - ILogger> loggerUser, - ApplicationUserClaimsPrincipalFactory claimsFactory, - IHttpContextAccessor httpContext, - IMapper mapper) - { - _unitOfWork = unitOfWork; - _logger = logger; - _claimsFactory = claimsFactory; - _httpContext = httpContext; - _mapper = mapper; - - // We need to created a custom instance for current service - // It'll help to use Transaction in the Unit Of Work - _userManager = new UserManager(userStore, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, loggerUser); - var roleStore = new RoleStore(_unitOfWork.DbContext); - _roleManager = new RoleManager(roleStore, roleValidators, keyNormalizer, errors, loggerRole); - } - - /// - public Guid GetCurrentUserId() - { - var identity = _httpContext.HttpContext?.User.Identity; - var identitySub = identity?.GetSubjectId(); - return identitySub?.ToGuid() ?? Guid.Empty; - } - - /// - /// Returns instance after successful registration - /// - /// - /// - - public async Task> RegisterAsync(RegisterViewModel model, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var user = _mapper.Map(model); - await using var transaction = await _unitOfWork.BeginTransactionAsync(); - var result = await _userManager.CreateAsync(user, model.Password); - const string role = AppData.ManagerRoleName; - - if (result.Succeeded) - { - if (await _roleManager.FindByNameAsync(role) == null) - { - operation.Exception = new MicroserviceUserNotFoundException(); - operation.AddError(AppData.Exceptions.UserNotFoundException); - return await Task.FromResult(operation); - } - - await _userManager.AddToRoleAsync(user, role); - - var profile = _mapper.Map(model); - var profileRepository = _unitOfWork.GetRepository(); - - await profileRepository.InsertAsync(profile, cancellationToken); - await _unitOfWork.SaveChangesAsync(); - if (_unitOfWork.LastSaveChangesResult.IsOk) - { - var principal = await _claimsFactory.CreateAsync(user); - operation.Result = _mapper.Map(principal.Identity); - operation.AddSuccess(AppData.Messages.UserSuccessfullyRegistered); - _logger.LogInformation(operation.GetMetadataMessages()); - await transaction.CommitAsync(cancellationToken); - _logger.LogInformation("User {@User} successfully created with {@Role}", model, role); - return await Task.FromResult(operation); - } - } - var errors = result.Errors.Select(x => $"{x.Code}: {x.Description}"); - operation.AddError(string.Join(", ", errors)); - operation.Exception = _unitOfWork.LastSaveChangesResult.Exception; - await transaction.RollbackAsync(cancellationToken); - _logger.LogError(operation.Exception, "User {@User} creation failed", model); - return await Task.FromResult(operation); - } - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - - public async Task GetPrincipalByIdAsync(string identifier) - { - if (string.IsNullOrEmpty(identifier)) - { - throw new MicroserviceException(); - } - var userManager = _userManager; - var user = await userManager.FindByIdAsync(identifier); - if (user == null) - { - throw new MicroserviceUserNotFoundException(); - } - - var defaultClaims = await _claimsFactory.CreateAsync(user); - return defaultClaims; - } - - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - public Task GetPrincipalForUserAsync(ApplicationUser user) => _claimsFactory.CreateAsync(user); - - /// - /// Returns user by his identifier - /// - /// - public Task GetByIdAsync(Guid id) - { - var userManager = _userManager; - return userManager.FindByIdAsync(id.ToString()); - } - - /// - /// Returns current user account information or null when user does not logged in - /// - - public async Task GetCurrentUserAsync() - { - var userManager = _userManager; - var userId = GetCurrentUserId().ToString(); - var user = await userManager.FindByIdAsync(userId); - return user; - } - - /// - /// Returns a collection of the by emails - /// - /// - public async Task> GetUsersByEmailsAsync(IEnumerable emails) - { - var userManager = _userManager; - var result = new List(); - foreach (var email in emails) - { - var user = await userManager.FindByEmailAsync(email); - if (user != null && !result.Contains(user)) - { - result.Add(user); - } - } - return await Task.FromResult(result); - } - - /// - /// Check roles for current user - /// - /// - - public async Task IsInRolesAsync(string[] roleNames) - { - var userManager = _userManager; - var userId = GetCurrentUserId().ToString(); - var user = await userManager.FindByIdAsync(userId); - if (user == null) - { - var resultUserNotFound = new PermissionValidationResult(); - resultUserNotFound.AddError(AppData.Exceptions.UnauthorizedException); - return await Task.FromResult(resultUserNotFound); - } - foreach (var roleName in roleNames) - { - var ok = await userManager.IsInRoleAsync(user, roleName); - if (ok) - { - return new PermissionValidationResult(); - } - } - - var result = new PermissionValidationResult(); - result.AddError(AppData.Exceptions.UnauthorizedException); - return result; - } - - /// - public async Task> GetUsersInRoleAsync(string roleName) - { - var userManager = _userManager; - return await userManager.GetUsersInRoleAsync(roleName); - } - - #region privates - - private async Task AddClaimsToUser(UserManager userManager, ApplicationUser user, string role) - { - await userManager.AddClaimAsync(user, new Claim(OpenIddictConstants.Claims.Name, user.UserName)); - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.GivenName, user.FirstName ?? "John")); - await userManager.AddClaimAsync(user, new Claim(ClaimTypes.Surname, user.LastName ?? "Doe")); - await userManager.AddClaimAsync(user, new Claim(OpenIddictConstants.Claims.Email, user.Email)); - await userManager.AddClaimAsync(user, new Claim(OpenIddictConstants.Claims.Role, role)); - } - - #endregion -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/APPLICATION/SERVICES/IAccountService.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/APPLICATION/SERVICES/IAccountService.cs deleted file mode 100644 index fa869eeb..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/APPLICATION/SERVICES/IAccountService.cs +++ /dev/null @@ -1,75 +0,0 @@ -using $ext_projectname$.Infrastructure; -using $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.Microservices.Core.Validators; -using Calabonga.OperationResults; -using System.Security.Claims; - -namespace $safeprojectname$.Application.Services; - -/// -/// Represent interface for account management -/// -public interface IAccountService -{ - /// - /// Returns a collection of the by emails - /// - /// - - Task> GetUsersByEmailsAsync(IEnumerable emails); - - /// - /// Get User Id from HttpContext - /// - - Guid GetCurrentUserId(); - - /// - /// Returns instance after successful registration - /// - /// - /// - - Task> RegisterAsync(RegisterViewModel model, CancellationToken cancellationToken); - - /// - /// Returns User by user identifier - /// - /// - - Task GetByIdAsync(Guid id); - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - - Task GetPrincipalByIdAsync(string identifier); - - /// - /// Returns ClaimPrincipal by user identity - /// - /// - - Task GetPrincipalForUserAsync(ApplicationUser user); - - /// - /// Returns current user account information or null when user does not logged in - /// - - Task GetCurrentUserAsync(); - - /// - /// Check roles for current user - /// - /// - - Task IsInRolesAsync(string[] roleNames); - - /// - /// Returns all system administrators registered in the system - /// - /// - - Task> GetUsersInRoleAsync(string roleName); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/APPLICATION/ValidatorBehavior.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/APPLICATION/ValidatorBehavior.cs deleted file mode 100644 index 6ab3152d..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/APPLICATION/ValidatorBehavior.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Calabonga.OperationResults; -using FluentValidation; -using MediatR; - -namespace $safeprojectname$.Application; - -/// -/// Base validator for requests -/// -/// -/// -public class ValidatorBehavior : IPipelineBehavior - where TRequest : IRequest -{ - private readonly IEnumerable> _validators; - - public ValidatorBehavior(IEnumerable> validators) => _validators = validators; - - /// - /// Pipeline handler. Perform any additional behavior and await the delegate as necessary - /// - /// Incoming request - /// Cancellation token - /// Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler. - /// Awaitable task returning the - public Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) - { - var failures = _validators - .Select(x => x.Validate(new ValidationContext(request))) - .SelectMany(x => x.Errors) - .Where(x => x != null) - .ToList(); - - if (!failures.Any()) - { - return next(); - } - - var type = typeof(TResponse); - if (!type.IsSubclassOf(typeof(OperationResult))) - { - throw new ValidationException(failures); - } - - var result = Activator.CreateInstance(type); - ((OperationResult)result!).AddError(new ValidationException(failures)); - return Task.FromResult((TResponse)result!); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj deleted file mode 100644 index 12b454f4..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj +++ /dev/null @@ -1,42 +0,0 @@ - - - - net7.0 - enable - enable - - - - - - - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/COMMON/CommonDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/COMMON/CommonDefinition.cs deleted file mode 100644 index 1cefbe63..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/COMMON/CommonDefinition.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace $safeprojectname$.Definitions.Common; - -/// -/// AspNetCore common configuration -/// -public class CommonDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - public override void ConfigureServices(WebApplicationBuilder builder) - { - builder.Services.AddLocalization(); - builder.Services.AddHttpContextAccessor(); - builder.Services.AddResponseCaching(); - builder.Services.AddMemoryCache(); - builder.Services.AddMvc(); - builder.Services.AddRazorPages(); - } - - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) - { - app.UseHttpsRedirection(); - app.MapRazorPages(); - app.MapDefaultControllerRoute(); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DATASEEDING/DataSeedingDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DATASEEDING/DataSeedingDefinition.cs deleted file mode 100644 index ce8299e6..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DATASEEDING/DataSeedingDefinition.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure.DatabaseInitialization; - -namespace $safeprojectname$.Definitions.DataSeeding; - -/// -/// Seeding DbContext for default data for EntityFrameworkCore -/// -public class DataSeedingDefinition : AppDefinition -{ - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) - { - DatabaseInitializer.SeedUsers(app.Services); - DatabaseInitializer.SeedEvents(app.Services); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DBCONTEXT/DbContextDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DBCONTEXT/DbContextDefinition.cs deleted file mode 100644 index 0574c73a..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DBCONTEXT/DbContextDefinition.cs +++ /dev/null @@ -1,64 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using $safeprojectname$.Definitions.Identity; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; -using OpenIddict.Abstractions; - -namespace $safeprojectname$.Definitions.DbContext; - -/// -/// ASP.NET Core services registration and configurations -/// -public class DbContextDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - public override void ConfigureServices(WebApplicationBuilder builder) - { - builder.Services.AddDbContext(config => - { - // UseInMemoryDatabase - This for demo purposes only! - // Should uninstall package "Microsoft.EntityFrameworkCore.InMemory" and install what you need. - // For example: "Microsoft.EntityFrameworkCore.SqlServer" - config.UseInMemoryDatabase("DEMO-PURPOSES-ONLY"); - - // uncomment line below to use UseSqlServer(). Don't forget setup connection string in appSettings.json - //config.UseSqlServer(configuration.GetConnectionString(nameof(ApplicationDbContext))); - - // Register the entity sets needed by OpenIddict. - // Note: use the generic overload if you need to replace the default OpenIddict entities. - config.UseOpenIddict(); - }); - - - builder.Services.Configure(options => - { - options.ClaimsIdentity.UserNameClaimType = OpenIddictConstants.Claims.Name; - options.ClaimsIdentity.UserIdClaimType = OpenIddictConstants.Claims.Subject; - options.ClaimsIdentity.RoleClaimType = OpenIddictConstants.Claims.Role; - options.ClaimsIdentity.EmailClaimType = OpenIddictConstants.Claims.Email; - // configure more options if you need - }); - - builder.Services.AddIdentity(options => - { - options.Password.RequireDigit = false; - options.Password.RequireLowercase = false; - options.Password.RequireNonAlphanumeric = false; - options.Password.RequiredLength = 8; - options.Password.RequireUppercase = false; - }) - .AddSignInManager() - .AddEntityFrameworkStores() - .AddUserStore() - .AddRoleStore() - .AddUserManager>() - .AddClaimsPrincipalFactory() - .AddDefaultTokenProviders(); - - builder.Services.AddTransient(); - } -} diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DEPENDENCYCONTAINER/ContainerDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DEPENDENCYCONTAINER/ContainerDefinition.cs deleted file mode 100644 index 46e81be2..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/DEPENDENCYCONTAINER/ContainerDefinition.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Application.Services; -using $safeprojectname$.Definitions.Identity; - -namespace $safeprojectname$.Definitions.DependencyContainer; - -/// -/// Dependency container definition -/// -public class ContainerDefinition : AppDefinition -{ - public override void ConfigureServices(WebApplicationBuilder builder) - { - builder.Services.AddTransient(); - builder.Services.AddTransient(); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/ERRORHANDLING/ErrorHandlingDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/ERRORHANDLING/ErrorHandlingDefinition.cs deleted file mode 100644 index e0403a1b..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/ERRORHANDLING/ErrorHandlingDefinition.cs +++ /dev/null @@ -1,58 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using FluentValidation; -using Microsoft.AspNetCore.Diagnostics; -using Serilog; -using System.Net; -using System.Security.Authentication; - -namespace $safeprojectname$.Definitions.ErrorHandling; - -/// -/// Custom Error handling -/// -public class ErrorHandlingDefinition : AppDefinition -{ - -#if DEBUG - public override bool Enabled => false; -#else - public override bool Enabled => true; -#endif - - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) => - app.UseExceptionHandler(error => error.Run(async context => - { - - context.Response.ContentType = "application/json"; - var contextFeature = context.Features.Get(); - if (contextFeature is not null) - { - - // handling all another errors - Log.Error($"Something went wrong in the {contextFeature.Error}"); - context.Response.StatusCode = StatusCodes.Status500InternalServerError; - - if (app.Environment.IsDevelopment()) - { - await context.Response.WriteAsync($"INTERNAL SERVER ERROR: {contextFeature.Error}"); - } - else - { - await context.Response.WriteAsync("INTERNAL SERVER ERROR. PLEASE TRY AGAIN LATER"); - } - } - })); - - private static HttpStatusCode GetErrorCode(Exception e) - => e switch - { - ValidationException _ => HttpStatusCode.BadRequest, - AuthenticationException _ => HttpStatusCode.Forbidden, - NotImplementedException _ => HttpStatusCode.NotImplemented, - _ => HttpStatusCode.InternalServerError - }; -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/ETAGGENERATOR/ETagGeneratorDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/ETAGGENERATOR/ETagGeneratorDefinition.cs deleted file mode 100644 index 98df32c7..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/ETAGGENERATOR/ETagGeneratorDefinition.cs +++ /dev/null @@ -1,77 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Net.Http.Headers; -using System.Diagnostics; -using System.Security.Cryptography; - -namespace $safeprojectname$.Definitions.ETagGenerator; - -/// -/// ETag Generator -/// -public class ETagGeneratorDefinition : AppDefinition -{ - -#if DEBUG - public override bool Enabled => false; -#else - public override bool Enabled => true; -#endif - - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) => - app.Use(async (context, next) => - { - var response = context.Response; - var originalStream = response.Body; - - await using var ms = new MemoryStream(); - response.Body = ms; - - await next(context); - - if (IsEtagSupported(response)) - { - var checksum = CalculateChecksum(ms); - - response.Headers[HeaderNames.ETag] = checksum; - - if (context.Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var etag) && checksum == etag) - { - response.StatusCode = StatusCodes.Status304NotModified; - return; - } - } - - ms.Position = 0; - await ms.CopyToAsync(originalStream); - }); - - - private static bool IsEtagSupported(HttpResponse response) - { - if (response.StatusCode != StatusCodes.Status200OK) - { - return false; - } - - // The 100kb length limit is not based in science. Feel free to change - if (response.Body.Length > 100 * 1024) - { - return false; - } - - return !response.Headers.ContainsKey(HeaderNames.ETag); - } - - private static string CalculateChecksum(MemoryStream ms) - { - using var algorithm = SHA1.Create(); - ms.Position = 0; - var bytes = algorithm.ComputeHash(ms); - return $"\"{WebEncoders.Base64UrlEncode(bytes)}\""; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/FLUENTVALIDATING/FluentValidationDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/FLUENTVALIDATING/FluentValidationDefinition.cs deleted file mode 100644 index 2a530adb..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/FLUENTVALIDATING/FluentValidationDefinition.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using FluentValidation; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Definitions.FluentValidating; - -/// -/// FluentValidation registration as Application definition -/// -public class FluentValidationDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - public override void ConfigureServices(WebApplicationBuilder builder) - { - builder.Services.Configure(options => - { - options.SuppressModelStateInvalidFilter = true; - }); - - builder.Services.AddValidatorsFromAssembly(typeof(Program).Assembly); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/ApplicationUserClaimsPrincipalFactory.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/ApplicationUserClaimsPrincipalFactory.cs deleted file mode 100644 index 925d5218..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/ApplicationUserClaimsPrincipalFactory.cs +++ /dev/null @@ -1,58 +0,0 @@ -using $ext_projectname$.Infrastructure; -using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.Options; -using System.Security.Claims; - -namespace $safeprojectname$.Definitions.Identity; - -/// -/// User Claims Principal Factory override from Microsoft Identity framework -/// -public class ApplicationUserClaimsPrincipalFactory : UserClaimsPrincipalFactory -{ - /// - public ApplicationUserClaimsPrincipalFactory( - UserManager userManager, - RoleManager roleManager, - IOptions optionsAccessor) - : base(userManager, roleManager, optionsAccessor) { } - - /// - /// Creates a from an user asynchronously. - /// - /// The user to create a from. - /// The that represents the asynchronous creation operation, containing the created . - public override async Task CreateAsync(ApplicationUser user) - { - var principal = await base.CreateAsync(user); - - if (user.ApplicationUserProfile?.Permissions != null) - { - var permissions = user.ApplicationUserProfile.Permissions.ToList(); - if (permissions.Any()) - { - permissions.ForEach(x => ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim(x.PolicyName, nameof(x.PolicyName).ToLower()))); - } - } - - ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim("framework", "nimble")); - - if (!string.IsNullOrWhiteSpace(user.UserName)) - { - ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim(ClaimTypes.Name, user.UserName)); - } - - if (!string.IsNullOrWhiteSpace(user.FirstName)) - { - ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName)); - } - - if (!string.IsNullOrWhiteSpace(user.LastName)) - { - ((ClaimsIdentity)principal.Identity!).AddClaim(new Claim(ClaimTypes.Surname, user.LastName)); - } - - return principal; - } - -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/AuthorizationDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/AuthorizationDefinition.cs deleted file mode 100644 index f7e77327..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/AuthorizationDefinition.cs +++ /dev/null @@ -1,53 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Definitions.OpenIddict; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Authorization; - -namespace $safeprojectname$.Definitions.Identity; - -/// -/// Authorization Policy registration -/// -public class AuthorizationDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - public override void ConfigureServices(WebApplicationBuilder builder) - { - builder.Services - .AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; - }) - .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => - { - options.LoginPath = "/connect/login"; - }); - - builder.Services.AddAuthorization(); - builder.Services.AddSingleton(); - builder.Services.AddSingleton(); - } - - /// - /// Configure application for current application - /// - /// - /// - public override void ConfigureApplication(WebApplication app) - { - app.UseHttpsRedirection(); - app.UseRouting(); - app.UseCors("CorsPolicy"); - app.UseAuthentication(); - app.UseAuthorization(); - - // registering UserIdentity helper as singleton - UserIdentity.Instance.Configure(app.Services.GetService()!); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/UserIdentity.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/UserIdentity.cs deleted file mode 100644 index 9b7b2756..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/IDENTITY/UserIdentity.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Calabonga.Microservices.Core.Exceptions; -using System.Security.Claims; -using System.Security.Principal; - -namespace $safeprojectname$.Definitions.Identity; - -/// -/// Identity helper for Requests operations -/// -public sealed class UserIdentity -{ - private UserIdentity() { } - - public static UserIdentity Instance => Lazy.Value; - - public void Configure(IHttpContextAccessor httpContextAccessor) - { - ContextAccessor = httpContextAccessor ?? throw new MicroserviceArgumentNullException(nameof(IHttpContextAccessor)); - IsInitialized = true; - } - - public IIdentity? User - { - get - { - if (IsInitialized) - { - return ContextAccessor.HttpContext!.User.Identity != null - && ContextAccessor.HttpContext != null - && ContextAccessor.HttpContext.User.Identity.IsAuthenticated - ? ContextAccessor.HttpContext.User.Identity - : null; - } - throw new MicroserviceArgumentNullException($"{nameof(UserIdentity)} has not been initialized. Please use {nameof(UserIdentity)}.Instance.Configure(...) in Configure Application method in Startup.cs"); - } - } - - public IEnumerable Claims - { - get - { - if (User != null) - { - return ContextAccessor.HttpContext!.User.Claims; - } - return Enumerable.Empty(); - } - } - - private static readonly Lazy Lazy = new Lazy(() => new UserIdentity()); - - private bool IsInitialized { get; set; } - - private static IHttpContextAccessor ContextAccessor { get; set; } = null!; - -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MAPPING/AutomapperDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MAPPING/AutomapperDefinition.cs deleted file mode 100644 index 45a69fdc..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MAPPING/AutomapperDefinition.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace $safeprojectname$.Definitions.Mapping; - -/// -/// Register Automapper as application definition -/// -public class AutomapperDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - public override void ConfigureServices(WebApplicationBuilder builder) - => builder.Services.AddAutoMapper(typeof(Program)); - - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) - { - var mapper = app.Services.GetRequiredService(); - if (app.Environment.IsDevelopment()) - { - // validate Mapper Configuration - mapper.AssertConfigurationIsValid(); - } - else - { - mapper.CompileMappings(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MAPPING/PagedListConverter.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MAPPING/PagedListConverter.cs deleted file mode 100644 index 82b4c28a..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MAPPING/PagedListConverter.cs +++ /dev/null @@ -1,23 +0,0 @@ -using AutoMapper; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Definitions.Mapping; - -/// -/// Generic converter for IPagedList collections -/// -/// -/// -public class PagedListConverter : ITypeConverter, IPagedList> -{ - /// Performs conversion from source to destination type - /// Source object - /// Destination object - /// Resolution context - /// Destination object - public IPagedList Convert(IPagedList source, IPagedList destination, ResolutionContext context) => - // ReSharper disable once ConditionIsAlwaysTrueOrFalse - source == null - ? PagedList.Empty() - : PagedList.From(source, items => context.Mapper.Map>(items)); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/BASE/UnitOfWorkTransactionBehavior.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/BASE/UnitOfWorkTransactionBehavior.cs deleted file mode 100644 index b588a961..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/BASE/UnitOfWorkTransactionBehavior.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Definitions.Mediator.Base; - -/// -/// Transaction Behavior -/// -/// -/// -public class TransactionBehavior : IPipelineBehavior - where TRequest : IRequest -{ - private readonly IUnitOfWork _unitOfWork; - - public TransactionBehavior(IUnitOfWork unitOfWork) => _unitOfWork = unitOfWork; - - - public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) - { - await using var transaction = await _unitOfWork.BeginTransactionAsync(); - try - { - var response = await next(); - await transaction.CommitAsync(cancellationToken); - return response; - } - catch (Exception) - { - await transaction.RollbackAsync(cancellationToken); - throw; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/EventItemPostTransactionBehavior.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/EventItemPostTransactionBehavior.cs deleted file mode 100644 index 0d7f292e..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/EventItemPostTransactionBehavior.cs +++ /dev/null @@ -1,12 +0,0 @@ -using $safeprojectname$.Definitions.Mediator.Base; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Definitions.Mediator; - -public class EventItemPostTransactionBehavior : TransactionBehavior>, OperationResult> -{ - public EventItemPostTransactionBehavior(IUnitOfWork unitOfWork) : base(unitOfWork) { } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/MediatorDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/MediatorDefinition.cs deleted file mode 100644 index 03b9ed49..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/MEDIATOR/MediatorDefinition.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Application; -using MediatR; - -namespace $safeprojectname$.Definitions.Mediator; - -/// -/// Register Mediator as application definition -/// -public class MediatorDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - public override void ConfigureServices(WebApplicationBuilder builder) - { - builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>)); - builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining()); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AppPermissionHandler.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AppPermissionHandler.cs deleted file mode 100644 index b550bbe8..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AppPermissionHandler.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Calabonga.Microservices.Core; -using Microsoft.AspNetCore.Authorization; -using System.Security.Claims; - -namespace $safeprojectname$.Definitions.OpenIddict; - -/// -/// Permission handler for custom authorization implementations -/// -public class AppPermissionHandler : AuthorizationHandler -{ - /// - protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) - { - if (context.User.Identity is null) - { - return Task.CompletedTask; - } - - var identity = (ClaimsIdentity)context.User.Identity; - var claim = ClaimsHelper.GetValue(identity, requirement.PermissionName); - if (claim == null) - { - return Task.CompletedTask; - } - - context.Succeed(requirement); - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AuthData.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AuthData.cs deleted file mode 100644 index c29501d9..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AuthData.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Microsoft.AspNetCore.Authentication.Cookies; -using OpenIddict.Validation.AspNetCore; - -namespace $safeprojectname$.Definitions.OpenIddict; - -public static class AuthData -{ - public const string AuthSchemes = CookieAuthenticationDefaults.AuthenticationScheme + "," + OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme; -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AuthorizationPolicyProvider.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AuthorizationPolicyProvider.cs deleted file mode 100644 index 47dd81f1..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/AuthorizationPolicyProvider.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.Options; - -namespace $safeprojectname$.Definitions.OpenIddict; - -/// -/// Policy provider -/// -public class AuthorizationPolicyProvider : DefaultAuthorizationPolicyProvider -{ - private readonly AuthorizationOptions _options; - - /// - public AuthorizationPolicyProvider(IOptions options) : base(options) => _options = options.Value; - - /// - public override async Task GetPolicyAsync(string policyName) - { - var policyExists = await base.GetPolicyAsync(policyName); - if (policyExists != null) - { - return policyExists; - } - - policyExists = new AuthorizationPolicyBuilder().AddRequirements(new PermissionRequirement(policyName)).Build(); - _options.AddPolicy(policyName, policyExists); - return policyExists; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/OpenIddictDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/OpenIddictDefinition.cs deleted file mode 100644 index 380521f0..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/OpenIddictDefinition.cs +++ /dev/null @@ -1,126 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using $safeprojectname$.HostedServices; -using OpenIddict.Abstractions; - -namespace $safeprojectname$.Definitions.OpenIddict; - -public class OpenIddictDefinition : AppDefinition -{ - public override void ConfigureServices(WebApplicationBuilder builder) - { - builder.Services.AddOpenIddict() - // Register the OpenIddict core components. - .AddCore(options => - { - // Configure OpenIddict to use the Entity Framework Core stores and models. - // Note: call ReplaceDefaultEntities() to replace the default entities. - options.UseEntityFrameworkCore() - .UseDbContext() - .ReplaceDefaultEntities(); - }) - - // Register the OpenIddict server components. - .AddServer(options => - { - // Note: the sample uses the code and refresh token flows but you can enable - // the other flows if you need to support implicit, password or client credentials. - // Supported flows are: - // => Authorization code flow - // => Client credentials flow - // => Device code flow - // => Implicit flow - // => Password flow - // => Refresh token flow - options - .AllowAuthorizationCodeFlow()//.RequireProofKeyForCodeExchange() - .AllowPasswordFlow() - .AllowClientCredentialsFlow() - .AllowRefreshTokenFlow(); - - // Using reference tokens means the actual access and refresh tokens - // are stored in the database and different tokens, referencing the actual - // tokens (in the db), are used in request headers. The actual tokens are not - // made public. - // => options.UseReferenceAccessTokens(); - // => options.UseReferenceRefreshTokens(); - - // Set the lifetime of your tokens - // => options.SetAccessTokenLifetime(TimeSpan.FromMinutes(30)); - // => options.SetRefreshTokenLifetime(TimeSpan.FromDays(7)); - - // Enable the token endpoint. - options.SetAuthorizationEndpointUris("connect/authorize") - //.RequireProofKeyForCodeExchange() // enable PKCE - //.SetDeviceEndpointUris("connect/device") - //.SetIntrospectionEndpointUris("connect/introspect") - .SetLogoutEndpointUris("connect/logout") - .SetTokenEndpointUris("connect/token") - //.SetVerificationEndpointUris("connect/verify"), - .SetUserinfoEndpointUris("connect/userinfo"); - - // Encryption and signing of tokens - options - .AddEphemeralEncryptionKey() // only for Developing mode - .AddEphemeralSigningKey() // only for Developing mode - .DisableAccessTokenEncryption(); // only for Developing mode - - // Mark the "email", "profile" and "roles" scopes as supported scopes. - options.RegisterScopes( - OpenIddictConstants.Scopes.Email, - OpenIddictConstants.Scopes.Profile, - OpenIddictConstants.Scopes.Roles, - "api", - "custom"); - - // Register the signing and encryption credentials. - options - .AddDevelopmentEncryptionCertificate() - .AddDevelopmentSigningCertificate(); - - // Register the ASP.NET Core host and configure the ASP.NET Core options. - options - .UseAspNetCore() - .EnableTokenEndpointPassthrough() - .EnableAuthorizationEndpointPassthrough(); - - //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); - //JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear(); - - //options.AddEventHandler(builder => - //{ - // builder.SetOrder(OpenIddictServerHandlers.GenerateIdentityModelRefreshToken.Descriptor.Order - 1) - // .AddFilter() - // .SetType(OpenIddictServerHandlerType.Custom) - // .UseInlineHandler(context => - // { - // context.RefreshTokenPrincipal = context.RefreshTokenPrincipal.Clone( - // claim => claim.Type is ( - // OpenIddictConstants.Claims.Private.AuthorizationId or - // OpenIddictConstants.Claims.Private.Presenter or - // OpenIddictConstants.Claims.Private.TokenId or - // OpenIddictConstants.Claims.Private.Scope or - // OpenIddictConstants.Claims.Subject or - // OpenIddictConstants.Claims.ExpiresAt - // ) - // ); - // return default; - // }); - //}); - }) - - // Register the OpenIddict validation components. - .AddValidation(options => - { - // Import the configuration from the local OpenIddict server instance. - options.UseLocalServer(); - - // Register the ASP.NET Core host. - options.UseAspNetCore(); - }); - - // Register the worker responsible for seeding the database. - // Note: in a real world application, this step should be part of a setup script. - builder.Services.AddHostedService(); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/PermissionRequirement.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/PermissionRequirement.cs deleted file mode 100644 index 5c3d40c2..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/OPENIDDICT/PermissionRequirement.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Microsoft.AspNetCore.Authorization; - -namespace $safeprojectname$.Definitions.OpenIddict; - -/// -/// Permission requirement for user or service authorization -/// -public class PermissionRequirement : IAuthorizationRequirement -{ - public PermissionRequirement(string permissionName) => PermissionName = permissionName; - - /// - /// Permission name - /// - public string PermissionName { get; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/SWAGGER/SwaggerDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/SWAGGER/SwaggerDefinition.cs deleted file mode 100644 index a7df7005..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/SWAGGER/SwaggerDefinition.cs +++ /dev/null @@ -1,130 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Domain.Base; -using $safeprojectname$.Application; -using Microsoft.AspNetCore.Mvc; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerUI; - -namespace $safeprojectname$.Definitions.Swagger; - -/// -/// Swagger definition for application -/// -public class SwaggerDefinition : AppDefinition -{ - // ATTENTION! - // If you use are git repository then you can uncomment line with "ThisAssembly" below for versioning by GIT possibilities. - // Otherwise, you can change versions of your API by manually. - // If you are not going to use git-versioning, do not forget install package "GitInfo" - // private const string _appVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - private const string _appVersion = "7.0.6"; - - private const string _swaggerConfig = "/swagger/v1/swagger.json"; - - public override void ConfigureApplication(WebApplication app) - { - if (!app.Environment.IsDevelopment()) - { - return; - } - - var url = app.Services.GetRequiredService().GetValue("AuthServer:Url"); - - app.UseSwagger(); - app.UseSwaggerUI(settings => - { - settings.SwaggerEndpoint(_swaggerConfig, $"{AppData.ServiceName} v.{_appVersion}"); - - // ATTENTION! - // If you use are git repository then you can uncomment line with "ThisAssembly" below for versioning by GIT possibilities. - // settings.HeadContent = $"{ThisAssembly.Git.Branch.ToUpper()} {ThisAssembly.Git.Commit.ToUpper()}"; - - settings.DocumentTitle = $"{AppData.ServiceName}"; - settings.DefaultModelExpandDepth(0); - settings.DefaultModelRendering(ModelRendering.Model); - settings.DefaultModelsExpandDepth(0); - settings.DocExpansion(DocExpansion.None); - settings.OAuthScopeSeparator(" "); - settings.OAuthClientId("client-id-code"); - settings.OAuthClientSecret("client-secret-code"); - settings.DisplayRequestDuration(); - settings.OAuthAppName(AppData.ServiceName); - settings.OAuth2RedirectUrl($"{url}/swagger/oauth2-redirect.html"); - }); - } - - public override void ConfigureServices(WebApplicationBuilder builder) - { - builder.Services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); - builder.Services.AddEndpointsApiExplorer(); - builder.Services.AddSwaggerGen(options => - { - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = AppData.ServiceName, - Version = _appVersion, - Description = AppData.ServiceDescription - }); - - options.ResolveConflictingActions(x => x.First()); - - options.TagActionsBy(api => - { - string tag; - if (api.ActionDescriptor is { } descriptor) - { - var attribute = descriptor.EndpointMetadata.OfType().FirstOrDefault(); - tag = attribute?.GroupName ?? descriptor.RouteValues["controller"] ?? "Untitled"; - } - else - { - tag = api.RelativePath!; - } - - var tags = new List(); - if (!string.IsNullOrEmpty(tag)) - { - tags.Add(tag); - } - return tags; - }); - - var url = builder.Configuration.GetSection("AuthServer").GetValue("Url"); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - AuthorizationCode = new OpenApiOAuthFlow - { - TokenUrl = new Uri($"{url}/connect/token", UriKind.Absolute), - AuthorizationUrl = new Uri($"{url}/connect/authorize", UriKind.Absolute), - Scopes = new Dictionary - { - { "api", "Default scope" } - } - } - } - }); - - options.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "oauth2" - }, - In = ParameterLocation.Cookie, - Type = SecuritySchemeType.OAuth2 - - }, - new List() - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/UOW/UnitOfWorkDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/UOW/UnitOfWorkDefinition.cs deleted file mode 100644 index 19375ce0..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/UOW/UnitOfWorkDefinition.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Definitions.UoW; - -/// -/// Unit of Work registration as application definition -/// -public class UnitOfWorkDefinition : AppDefinition -{ - /// - /// Configure services for current application - /// - /// - public override void ConfigureServices(WebApplicationBuilder builder) - => builder.Services.AddUnitOfWork(); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemEndpoints.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemEndpoints.cs deleted file mode 100644 index aae86bd2..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemEndpoints.cs +++ /dev/null @@ -1,59 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Application; -using $safeprojectname$.Definitions.OpenIddict; -using $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints; - -public class EventItemEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("/api/event-items/{id:guid}", LogGetById); - app.MapGet("/api/event-items/paged", LogGetPaged); - app.MapPost("/api/event-items/", PostLog); - app.MapPut("/api/event-items/{id:guid}", PutLog); - app.MapDelete("/api/event-items/{id:guid}", LogDelete); - } - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogGetById([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new GetEventItemById.Request(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogDelete([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new DeleteEventItem.Request(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task>> LogGetPaged([FromServices] IMediator mediator, int pageIndex, int pageSize, string? search, HttpContext context) - => await mediator.Send(new GetEventItemPaged.Request(pageIndex, pageSize, search), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PostLog([FromServices] IMediator mediator, EventItemCreateViewModel model, HttpContext context) - => await mediator.Send(new PostEventItem.Request(model), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PutLog([FromServices] IMediator mediator, Guid id, EventItemUpdateViewModel model, HttpContext context) - => await mediator.Send(new PutEventItem.Request(id, model), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemMapperConfiguration.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemMapperConfiguration.cs deleted file mode 100644 index 9fa595b9..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemMapperConfiguration.cs +++ /dev/null @@ -1,32 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Definitions.Mapping; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints; - -/// -/// Mapper Configuration for entity EventItem -/// -public class EventItemMapperConfiguration : Profile -{ - /// - public EventItemMapperConfiguration() - { - CreateMap() - .ForMember(x => x.Id, o => o.Ignore()); - - CreateMap(); - - CreateMap(); - - CreateMap() - .ForMember(x => x.CreatedAt, o => o.Ignore()) - .ForMember(x => x.ThreadId, o => o.Ignore()) - .ForMember(x => x.ExceptionMessage, o => o.Ignore()); - - CreateMap, IPagedList>() - .ConvertUsing>(); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemValidator.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemValidator.cs deleted file mode 100644 index a2d3aeb5..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemValidator.cs +++ /dev/null @@ -1,20 +0,0 @@ -using $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; -using FluentValidation; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints; - -/// -/// RegisterViewModel Validator -/// -public class EventItemCreateRequestValidator : AbstractValidator -{ - public EventItemCreateRequestValidator() => RuleSet("default", () => - { - RuleFor(x => x.Model.CreatedAt).NotNull(); - RuleFor(x => x.Model.Message).NotEmpty().MaximumLength(4000); - RuleFor(x => x.Model.Level).NotEmpty().MaximumLength(50); - RuleFor(x => x.Model.Logger).NotEmpty().MaximumLength(255); - RuleFor(x => x.Model.ThreadId).MaximumLength(50); - RuleFor(x => x.Model.ExceptionMessage).MaximumLength(4000); - }); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/DeleteEventItem.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/DeleteEventItem.cs deleted file mode 100644 index 9308ebc0..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/DeleteEventItem.cs +++ /dev/null @@ -1,57 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// EventItem delete -/// -public class DeleteEventItem -{ - public record Request(Guid Id) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(Request request, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.FindAsync(request.Id); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException("Entity not found")); - return operation; - } - - repository.Delete(entity); - await _unitOfWork.SaveChangesAsync(); - if (_unitOfWork.LastSaveChangesResult.IsOk) - { - operation.Result = _mapper.Map(entity); - return operation; - } - - operation.AddError(_unitOfWork.LastSaveChangesResult.Exception); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemById.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemById.cs deleted file mode 100644 index 8373b0a9..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemById.cs +++ /dev/null @@ -1,49 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// EventItem by Identifier -/// -public class GetEventItemById -{ - public record Request(Guid Id) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request getting log by identifier - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(Request request, CancellationToken cancellationToken) - { - var id = request.Id; - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entityWithoutIncludes = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == id); - if (entityWithoutIncludes == null) - { - operation.AddError(new MicroserviceNotFoundException($"Entity with identifier {id} not found")); - return operation; - } - - operation.Result = _mapper.Map(entityWithoutIncludes); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemPaged.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemPaged.cs deleted file mode 100644 index 650c520e..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemPaged.cs +++ /dev/null @@ -1,76 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.PredicatesBuilder; -using Calabonga.UnitOfWork; -using MediatR; -using System.Linq.Expressions; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request for paged list of EventItems -/// -public class GetEventItemPaged -{ - public record Request(int PageIndex, int PageSize, string? Search) : IRequest>>; - - public class Handler : IRequestHandler>> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task>> Handle( - Request request, - CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult>(); - var predicate = GetPredicate(request.Search); - var pagedList = await _unitOfWork.GetRepository() - .GetPagedListAsync( - predicate: predicate, - pageIndex: request.PageIndex, - pageSize: request.PageSize, - cancellationToken: cancellationToken); - - if (pagedList == null) - { - operation.Result = PagedList.Empty(); - operation.AddWarning("Response does not return the result for pagination."); - return operation; - } - - if (pagedList.PageIndex > pagedList.TotalPages) - { - pagedList = await _unitOfWork.GetRepository() - .GetPagedListAsync( - pageIndex: 0, - pageSize: request.PageSize, cancellationToken: cancellationToken); - } - - operation.Result = _mapper.Map>(pagedList); - return operation; - } - - private Expression> GetPredicate(string? search) - { - var predicate = PredicateBuilder.True(); - if (search is null) - { - return predicate; - } - - predicate = predicate.And(x => x.Message.Contains(search)); - predicate = predicate.Or(x => x.Logger.Contains(search)); - predicate = predicate.Or(x => x.Level.Contains(search)); - return predicate; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/PostEventItem.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/PostEventItem.cs deleted file mode 100644 index 8efb61b6..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/PostEventItem.cs +++ /dev/null @@ -1,68 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem creation -/// -public class PostEventItem -{ - public record Request(EventItemCreateViewModel Model) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - private readonly ILogger _logger; - - - public Handler(IUnitOfWork unitOfWork, IMapper mapper, ILogger logger) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - _logger = logger; - } - - public async Task> Handle(Request eventItemRequest, CancellationToken cancellationToken) - { - _logger.LogDebug("Creating new EventItem"); - - var operation = OperationResult.CreateResult(); - - var entity = _mapper.Map(eventItemRequest.Model); - if (entity == null) - { - var exceptionMapper = new MicroserviceUnauthorizedException(AppContracts.Exceptions.MappingException); - operation.AddError(exceptionMapper); - _logger.LogError(exceptionMapper, "Mapper not configured correctly or something went wrong"); - return operation; - } - - await _unitOfWork.GetRepository().InsertAsync(entity, cancellationToken); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("Successfully created"); - _logger.LogInformation("New entity {@EventItem} successfully created", entity); - return operation; - } - - var exception = lastResult.Exception ?? new ApplicationException("Something went wrong"); - operation.AddError(exception); - _logger.LogError(exception, "Error data saving to Database or something went wrong"); - - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/UpdateEventItem.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/UpdateEventItem.cs deleted file mode 100644 index 2bd5d9d9..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/UpdateEventItem.cs +++ /dev/null @@ -1,59 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem edit -/// -public class PutEventItem -{ - public record Request(Guid Id, EventItemUpdateViewModel Model) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task> Handle(Request eventItemRequest, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == eventItemRequest.Id, disableTracking: false); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException(AppContracts.Exceptions.NotFoundException)); - return operation; - } - - _mapper.Map(eventItemRequest.Model, entity); - - repository.Update(entity); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("Successfully updated"); - return operation; - } - - operation.AddError(lastResult.Exception ?? new ApplicationException("Something went wrong")); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemCreateViewModel.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemCreateViewModel.cs deleted file mode 100644 index 054466de..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemCreateViewModel.cs +++ /dev/null @@ -1,36 +0,0 @@ -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemCreateViewModel : IViewModel -{ - /// - /// EventItem Created At - /// - public DateTime CreatedAt { get; set; } - - /// - /// Service name or provider - /// - public string Logger { get; set; } = null!; - - /// - /// EventItem level for logging. See - /// - public string Level { get; set; } = null!; - - /// - /// EventItem Message - /// - public string Message { get; set; } = null!; - - /// - /// Thread identifier - /// - public string? ThreadId { get; set; } - - /// - /// Exception message - /// - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemUpdateViewModel.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemUpdateViewModel.cs deleted file mode 100644 index 6dc45417..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemUpdateViewModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemUpdateViewModel : ViewModelBase -{ - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemViewModel.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemViewModel.cs deleted file mode 100644 index 39211dbc..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemViewModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemViewModel -{ - public Guid Id { get; set; } - - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; - - public string? ThreadId { get; set; } - - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesDefinition.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesDefinition.cs deleted file mode 100644 index b28129cb..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesDefinition.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Application; -using $safeprojectname$.Definitions.OpenIddict; -using $safeprojectname$.Endpoints.ProfileEndpoints.Queries; -using $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.OperationResults; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints; - -public class ProfilesDefinition : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("/api/profiles/get-roles", GetRoles); - app.MapPost("/api/profiles/register", RegisterAccount); - } - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("Profiles")] - private async Task GetRoles([FromServices] IMediator mediator, HttpContext context) - => await mediator.Send(new GetProfile.Request(), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [FeatureGroupName("Profiles")] - private async Task> RegisterAccount([FromServices] IMediator mediator, RegisterViewModel model, HttpContext context) - => await mediator.Send(new RegisterAccount.Request(model), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesMapperConfiguration.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesMapperConfiguration.cs deleted file mode 100644 index 2a7ee133..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesMapperConfiguration.cs +++ /dev/null @@ -1,56 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Infrastructure; -using $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using System.Security.Claims; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints; - -/// -/// Mapper Configuration for entity ApplicationUser -/// -public class ProfilesMapperConfiguration : Profile -{ - /// - public ProfilesMapperConfiguration() - { - CreateMap() - .ForMember(x => x.UserName, o => o.MapFrom(p => p.Email)) - .ForMember(x => x.Email, o => o.MapFrom(p => p.Email)) - .ForMember(x => x.EmailConfirmed, o => o.MapFrom(src => true)) - .ForMember(x => x.FirstName, o => o.MapFrom(p => p.FirstName)) - .ForMember(x => x.LastName, o => o.MapFrom(p => p.LastName)) - .ForMember(x => x.PhoneNumberConfirmed, o => o.MapFrom(src => true)) - .ForMember(x => x.ApplicationUserProfileId, o => o.Ignore()) - .ForMember(x => x.ApplicationUserProfile, o => o.Ignore()) - .ForMember(x => x.Id, o => o.Ignore()) - .ForMember(x => x.NormalizedUserName, o => o.Ignore()) - .ForMember(x => x.NormalizedEmail, o => o.Ignore()) - .ForMember(x => x.PasswordHash, o => o.Ignore()) - .ForMember(x => x.SecurityStamp, o => o.Ignore()) - .ForMember(x => x.ConcurrencyStamp, o => o.Ignore()) - .ForMember(x => x.PhoneNumber, o => o.Ignore()) - .ForMember(x => x.TwoFactorEnabled, o => o.Ignore()) - .ForMember(x => x.LockoutEnd, o => o.Ignore()) - .ForMember(x => x.LockoutEnabled, o => o.Ignore()) - .ForMember(x => x.AccessFailedCount, o => o.Ignore()); - - CreateMap() - .ForMember(x => x.Id, o => o.Ignore()) - .ForMember(x => x.Permissions, o => o.Ignore()) - .ForMember(x => x.ApplicationUser, o => o.Ignore()) - .ForMember(x => x.CreatedAt, o => o.Ignore()) - .ForMember(x => x.CreatedBy, o => o.Ignore()) - .ForMember(x => x.UpdatedAt, o => o.Ignore()) - .ForMember(x => x.UpdatedBy, o => o.Ignore()); - - CreateMap() - .ForMember(x => x.Id, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.NameIdentifier))) - .ForMember(x => x.PositionName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Actor))) - .ForMember(x => x.FirstName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.GivenName))) - .ForMember(x => x.LastName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Surname))) - .ForMember(x => x.Roles, o => o.MapFrom(claims => ClaimsHelper.GetValues(claims, ClaimTypes.Role))) - .ForMember(x => x.Email, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Name))) - .ForMember(x => x.PhoneNumber, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.MobilePhone))); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/GetRoles.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/GetRoles.cs deleted file mode 100644 index e6a4671a..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/GetRoles.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Calabonga.Microservices.Core; -using MediatR; -using System.Security.Claims; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints.Queries; - -/// -/// Request: Returns user roles -/// -public class GetProfile -{ - public record Request : IRequest; - - public class Handler : IRequestHandler - { - private readonly ILogger _logger; - private readonly IHttpContextAccessor _httpContextAccessor; - - public Handler( - ILogger logger, - IHttpContextAccessor httpContextAccessor) - { - _logger = logger; - _httpContextAccessor = httpContextAccessor; - } - - public Task Handle(Request request, CancellationToken cancellationToken) - { - var user = _httpContextAccessor.HttpContext!.User; - var roles = ClaimsHelper.GetValues((ClaimsIdentity)user.Identity!, "role"); - var message = $"Current user ({user.Identity!.Name}) have following roles: {string.Join("|", roles)}"; - _logger.LogInformation(message); - return Task.FromResult(message); - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/RegisterAccount.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/RegisterAccount.cs deleted file mode 100644 index 77f1edba..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/RegisterAccount.cs +++ /dev/null @@ -1,30 +0,0 @@ -using $safeprojectname$.Application.Services; -using $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.OperationResults; -using MediatR; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints.Queries; - -/// -/// Register new account -/// -public class RegisterAccount -{ - public class Request : IRequest> - { - public Request(RegisterViewModel model) => Model = model; - - public RegisterViewModel Model { get; } - } - - public class Handler : IRequestHandler> - { - private readonly IAccountService _accountService; - - public Handler(IAccountService accountService) - => _accountService = accountService; - - public Task> Handle(Request request, CancellationToken cancellationToken) - => _accountService.RegisterAsync(request.Model, cancellationToken); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/RegisterViewModel.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/RegisterViewModel.cs deleted file mode 100644 index eccd056f..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/RegisterViewModel.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; - -/// -/// Data transfer object for user registration -/// -public class RegisterViewModel -{ - /// - /// FirstName - /// - [Required] - [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)] - [Display(Name = "First Name")] - public string FirstName { get; set; } = null!; - - /// - /// LastName - /// - [Required] - [StringLength(50, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 2)] - [Display(Name = "Last Name")] - public string LastName { get; set; } = null!; - - /// - /// Email - /// - [Required] - [EmailAddress] - [Display(Name = "Email")] - public string Email { get; set; } = null!; - - /// - /// Password - /// - [Required] - [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] - [DataType(DataType.Password)] - [Display(Name = "Password")] - public string Password { get; set; } = null!; - - /// - /// Password confirmation - /// - [DataType(DataType.Password)] - [Display(Name = "Confirm password")] - [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] - public string ConfirmPassword { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/UserProfileViewModel.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/UserProfileViewModel.cs deleted file mode 100644 index f54b8bf5..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/UserProfileViewModel.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; - -/// -/// Application User Profile -/// -public class UserProfileViewModel -{ - /// - /// Identifier - /// - public Guid Id { get; set; } - - /// - /// FirstName - /// - public string FirstName { get; set; } = null!; - - /// - /// LastName - /// - public string LastName { get; set; } = null!; - - /// - /// Email - /// - public string Email { get; set; } = null!; - - /// - /// User Roles - /// - public List? Roles { get; set; } - - /// - /// User PhoneNumber - /// - public string? PhoneNumber { get; set; } - - /// - /// Position Name - /// - public string? PositionName { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/SECURITYENDPOINTS/AuthorizeEndpoints.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/SECURITYENDPOINTS/AuthorizeEndpoints.cs deleted file mode 100644 index 704b4927..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/SECURITYENDPOINTS/AuthorizeEndpoints.cs +++ /dev/null @@ -1,146 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Identity; -using OpenIddict.Abstractions; -using OpenIddict.Server.AspNetCore; - -namespace $safeprojectname$.Endpoints.SecurityEndpoints; - -/// -/// Authorize Endpoint for OpenIddict -/// You can test your authorization server with https://oidcdebugger.com/ -/// You can mock your authorization flow with https://oauth.mocklab.io/ -/// -public class AuthorizeEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("~/connect/authorize", AuthorizeAsync).ExcludeFromDescription(); - app.MapPost("~/connect/authorize", AuthorizeAsync).ExcludeFromDescription(); - } - - private async Task AuthorizeAsync( - HttpContext httpContext, - IOpenIddictScopeManager scopeManager, - UserManager userManager, - SignInManager signInManager, - IOpenIddictApplicationManager applicationManager, - IOpenIddictAuthorizationManager authorizationManager) - { - var request = httpContext.Request; - var iddictRequest = httpContext.GetOpenIddictServerRequest() ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); - - // Retrieve the user principal stored in the authentication cookie. - var result = await httpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); - - if (!result.Succeeded) - { - return Results.Challenge(new AuthenticationProperties - { - RedirectUri = request.PathBase + request.Path + QueryString.Create(request.HasFormContentType - ? request.Form.ToList() - : request.Query.ToList()) - }, - new List { CookieAuthenticationDefaults.AuthenticationScheme }); - } - - // ATTENTION: If you use are "IN-Memory" mode, then system cannot track user that recreated every time on start. You should clear cookies (site data) in browser. - var user = await userManager.GetUserAsync(result.Principal) ?? throw new InvalidOperationException("The user details cannot be retrieved."); - - var application = await applicationManager.FindByClientIdAsync(iddictRequest.ClientId!) ?? throw new InvalidOperationException("Details concerning the calling client application cannot be found."); - var applicationId = await applicationManager.GetIdAsync(application); - var userId = await userManager.GetUserIdAsync(user); - - var authorizations = await authorizationManager.FindAsync( - subject: userId, - client: applicationId!, - status: OpenIddictConstants.Statuses.Valid, - type: OpenIddictConstants.AuthorizationTypes.Permanent, - scopes: iddictRequest.GetScopes()).ToListAsync(); - - switch (await applicationManager.GetConsentTypeAsync(application)) - { - // If the consent is external (e.g when authorizations are granted by a sysadmin), - // immediately return an error if no authorization can be found in the database. - case OpenIddictConstants.ConsentTypes.External when !authorizations.Any(): - return Results.Forbid( - authenticationSchemes: new[] { OpenIddictServerAspNetCoreDefaults.AuthenticationScheme }, - properties: new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = OpenIddictConstants.Errors.ConsentRequired, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "The logged in user is not allowed to access this client application." - }!)); - - // If the consent is implicit or if an authorization was found, - // return an authorization response without displaying the consent form. - case OpenIddictConstants.ConsentTypes.Implicit: - case OpenIddictConstants.ConsentTypes.External when authorizations.Any(): - case OpenIddictConstants.ConsentTypes.Explicit when authorizations.Any() && !iddictRequest.HasPrompt(OpenIddictConstants.Prompts.Consent): - - var principal = await signInManager.CreateUserPrincipalAsync(user); - - // Note: in this sample, the granted scopes match the requested scope - // but you may want to allow the user to uncheck specific scopes. - // For that, simply restrict the list of scopes before calling SetScopes. - - principal.SetScopes(iddictRequest.GetScopes()); - principal.SetResources(await scopeManager.ListResourcesAsync(principal.GetScopes()).ToListAsync()); - - // Automatically create a permanent authorization to avoid requiring explicit consent - // for future authorization or token requests containing the same scopes. - var authorization = authorizations.LastOrDefault() ?? await authorizationManager.CreateAsync( - principal: principal, - subject: await userManager.GetUserIdAsync(user), - client: applicationId!, - type: OpenIddictConstants.AuthorizationTypes.Permanent, - scopes: principal.GetScopes()); - - principal.SetAuthorizationId(await authorizationManager.GetIdAsync(authorization)); - - principal.SetDestinations(static claim => claim.Type switch - { - // If the "profile" scope was granted, allow the "name" claim to be - // added to the access and identity tokens derived from the principal. - OpenIddictConstants.Claims.Name when claim.Subject.HasScope(OpenIddictConstants.Scopes.Profile) => new[] - { - OpenIddictConstants.Destinations.AccessToken, OpenIddictConstants.Destinations.IdentityToken - }, - - // Never add the "secret_value" claim to access or identity tokens. - // In this case, it will only be added to authorization codes, - // refresh tokens and user/device codes, that are always encrypted. - "secret_value" => Array.Empty(), - - // Otherwise, add the claim to the access tokens only. - _ => new[] { OpenIddictConstants.Destinations.AccessToken } - }); - - - - return Results.SignIn(principal, null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - - // At this point, no authorization was found in the database and an error must be returned - // if the client application specified prompt=none in the authorization request. - case OpenIddictConstants.ConsentTypes.Explicit when iddictRequest.HasPrompt(OpenIddictConstants.Prompts.None): - case OpenIddictConstants.ConsentTypes.Systematic when iddictRequest.HasPrompt(OpenIddictConstants.Prompts.None): - return Results.Forbid( - authenticationSchemes: new[] { OpenIddictServerAspNetCoreDefaults.AuthenticationScheme }, - properties: new AuthenticationProperties(new Dictionary - { - [OpenIddictServerAspNetCoreConstants.Properties.Error] = OpenIddictConstants.Errors.ConsentRequired, - [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = - "Interactive user consent is required." - }!)); - - // In every other case, render the consent form. - default: - return Results.Challenge( - authenticationSchemes: new[] { OpenIddictServerAspNetCoreDefaults.AuthenticationScheme }, - properties: new AuthenticationProperties { RedirectUri = "/" }); - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/SECURITYENDPOINTS/TokenEndpoints.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/SECURITYENDPOINTS/TokenEndpoints.cs deleted file mode 100644 index 884ccb4b..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/ENDPOINTS/SECURITYENDPOINTS/TokenEndpoints.cs +++ /dev/null @@ -1,108 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using $safeprojectname$.Application.Services; -using Calabonga.Microservices.Core.Extensions; -using Microsoft.AspNetCore; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Identity; -using OpenIddict.Abstractions; -using OpenIddict.Server.AspNetCore; -using System.Security.Claims; - -namespace $safeprojectname$.Endpoints.SecurityEndpoints; - -/// -/// Token Endpoint for OpenIddict -/// -public class TokenEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) => - app.MapPost("~/connect/token", TokenAsync).ExcludeFromDescription(); - - private async Task TokenAsync( - HttpContext httpContext, - IOpenIddictScopeManager manager, - UserManager userManager, - SignInManager signInManager, - IAccountService accountService) - { - var request = httpContext.GetOpenIddictServerRequest() ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); - //if (request.Scope is null) - //{ - // return Results.Problem("The specified grant type is not supported."); - //} - - if (request.IsClientCredentialsGrantType()) - { - var identity = new ClaimsIdentity(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - - // Subject or sub is a required field, we use the client id as the subject identifier here. - identity.AddClaim(OpenIddictConstants.Claims.Subject, request.ClientId!); - identity.AddClaim(OpenIddictConstants.Claims.ClientId, request.ClientId!); - - // Don't forget to add destination otherwise it won't be added to the access token. - if (request.Scope.IsNullOrEmpty()) - { - identity.AddClaim(OpenIddictConstants.Claims.Scope, request.Scope!, OpenIddictConstants.Destinations.AccessToken); - } - - identity.AddClaim("nimble", "framework", OpenIddictConstants.Destinations.AccessToken); - - var claimsPrincipal = new ClaimsPrincipal(identity); - - claimsPrincipal.SetScopes(request.GetScopes()); - return Results.SignIn(claimsPrincipal, new AuthenticationProperties(), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - } - - if (request.IsPasswordGrantType()) - { - var user = await userManager.FindByNameAsync(request.Username); - if (user == null) - { - return Results.Problem("Invalid operation"); - } - - // Ensure the user is allowed to sign in - if (!await signInManager.CanSignInAsync(user)) - { - return Results.Problem("Invalid operation"); - } - - - // Ensure the user is not already locked out - if (userManager.SupportsUserLockout && await userManager.IsLockedOutAsync(user)) - { - return Results.Problem("Invalid operation"); - } - - // Ensure the password is valid - if (!await userManager.CheckPasswordAsync(user, request.Password)) - { - if (userManager.SupportsUserLockout) - { - await userManager.AccessFailedAsync(user); - } - - return Results.Problem("Invalid operation"); - } - - // Reset the lockout count - if (userManager.SupportsUserLockout) - { - await userManager.ResetAccessFailedCountAsync(user); - } - - var principal = await accountService.GetPrincipalForUserAsync(user); - return Results.SignIn(principal, null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - } - - if (request.IsAuthorizationCodeGrantType()) - { - var authenticateResult = await httpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - var claimsPrincipal = authenticateResult.Principal; - return Results.SignIn(claimsPrincipal!, null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); - } - - return Results.Problem("The specified grant type is not supported."); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/HOSTEDSERVICES/OpenIddictWorker.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/HOSTEDSERVICES/OpenIddictWorker.cs deleted file mode 100644 index 64e6ba98..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/HOSTEDSERVICES/OpenIddictWorker.cs +++ /dev/null @@ -1,85 +0,0 @@ -using $ext_projectname$.Infrastructure; -using OpenIddict.Abstractions; - -namespace $safeprojectname$.HostedServices; - -public class OpenIddictWorker : IHostedService -{ - private readonly IServiceProvider _serviceProvider; - - public OpenIddictWorker(IServiceProvider serviceProvider) => _serviceProvider = serviceProvider; - - public async Task StartAsync(CancellationToken cancellationToken) - { - await using var scope = _serviceProvider.CreateAsyncScope(); - - var context = scope.ServiceProvider.GetRequiredService(); - await context.Database.EnsureCreatedAsync(cancellationToken); - - var manager = scope.ServiceProvider.GetRequiredService(); - - // credentials password - const string client_id1 = "client-id-sts"; - if (await manager.FindByClientIdAsync(client_id1, cancellationToken) is null) - { - await manager.CreateAsync(new OpenIddictApplicationDescriptor - { - ClientId = client_id1, - ClientSecret = "client-secret-sts", - DisplayName = "Service-To-Service demonstration", - Permissions = - { - // Endpoint permissions - OpenIddictConstants.Permissions.Endpoints.Token, - - // Grant type permissions - OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, - OpenIddictConstants.Permissions.GrantTypes.Password, - - // Scope permissions - OpenIddictConstants.Permissions.Prefixes.Scope + "api" - } - }, cancellationToken); - } - - const string client_id2 = "client-id-code"; - if (await manager.FindByClientIdAsync(client_id2, cancellationToken) is null) - { - var url = _serviceProvider.GetRequiredService().GetValue("AuthServer:Url"); - - await manager.CreateAsync(new OpenIddictApplicationDescriptor - { - ClientId = client_id2, - ConsentType = OpenIddictConstants.ConsentTypes.Implicit, - ClientSecret = "client-secret-code", - DisplayName = "API testing clients with Authorization Code Flow demonstration", - RedirectUris = { - new Uri("https://www.thunderclient.com/oauth/callback"), // https://www.thunderclient.com/ - new Uri($"{url}/swagger/oauth2-redirect.html"), // https://swagger.io/ - new Uri("https://localhost:20001/swagger/oauth2-redirect.html") // https://swagger.io/ for Module - }, - - Permissions = - { - // Endpoint permissions - OpenIddictConstants.Permissions.Endpoints.Authorization, - OpenIddictConstants.Permissions.Endpoints.Token, - - // Grant type permissions - OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, - OpenIddictConstants.Permissions.GrantTypes.RefreshToken, - - // Scope permissions - OpenIddictConstants.Permissions.Prefixes.Scope + "api", - OpenIddictConstants.Permissions.Prefixes.Scope + "custom", - - // Response types - OpenIddictConstants.Permissions.ResponseTypes.Code, - OpenIddictConstants.Permissions.ResponseTypes.IdToken - } - }, cancellationToken); - } - } - - public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/MyTemplate.vstemplate b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/MyTemplate.vstemplate deleted file mode 100644 index f438a29c..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/MyTemplate.vstemplate +++ /dev/null @@ -1,143 +0,0 @@ - - - Calabonga.Microservice.IdentityModule.Web - Calabonga.Microservice.IdentityModule.Web - CSharp - - - 1000 - true - Calabonga.Microservice.IdentityModule.Web - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - launchSettings.json - - - - AccountService.cs - IAccountService.cs - - FeatureGroupNameAttribute.cs - ValidatorBehavior.cs - - - - CommonDefinition.cs - - - CorsDefinition.cs - - - DataSeedingDefinition.cs - - - DbContextDefinition.cs - - - ContainerDefinition.cs - - - ErrorHandlingDefinition.cs - - - ETagGeneratorDefinition.cs - - - FluentValidationDefinition.cs - - - ApplicationUserClaimsPrincipalFactory.cs - AuthorizationDefinition.cs - UserIdentity.cs - - - AutomapperDefinition.cs - PagedListConverter.cs - - - - UnitOfWorkTransactionBehavior.cs - - EventItemPostTransactionBehavior.cs - MediatorDefinition.cs - - - AppPermissionHandler.cs - AuthData.cs - AuthorizationPolicyProvider.cs - OpenIddictDefinition.cs - PermissionRequirement.cs - - - SwaggerDefinition.cs - - - UnitOfWorkDefinition.cs - - - - - - DeleteEventItem.cs - GetEventItemById.cs - GetEventItemPaged.cs - PostEventItem.cs - UpdateEventItem.cs - - - EventItemCreateViewModel.cs - EventItemUpdateViewModel.cs - EventItemViewModel.cs - - EventItemEndpoints.cs - EventItemMapperConfiguration.cs - EventItemValidator.cs - - - - GetRoles.cs - RegisterAccount.cs - - - RegisterViewModel.cs - UserProfileViewModel.cs - - ProfilesDefinition.cs - ProfilesMapperConfiguration.cs - - - AuthorizeEndpoints.cs - TokenEndpoints.cs - - - - OpenIddictWorker.cs - - - - Login.cshtml - Login.cshtml.cs - LoginViewModel.cs - - - _Layout.cshtml - - _ViewImports.cshtml - _ViewStart.cshtml - - appsettings.json - appsettings.Development.json - Program.cs - readme.md - tempkey.jwk - - - \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/Login.cshtml b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/Login.cshtml deleted file mode 100644 index 19017a63..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/Login.cshtml +++ /dev/null @@ -1,32 +0,0 @@ -@page -@model $safeprojectname$.Pages.Connect.LoginModel - -
- -
- -
- - - -
- -
- - - -
- - -
- - - -
-
- -
- -
-
-
\ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/Login.cshtml.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/Login.cshtml.cs deleted file mode 100644 index a0526147..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/Login.cshtml.cs +++ /dev/null @@ -1,68 +0,0 @@ -using $ext_projectname$.Infrastructure; -using $safeprojectname$.Application.Services; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authentication.Cookies; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.RazorPages; - -namespace $safeprojectname$.Pages.Connect; - -public class LoginModel : PageModel -{ - private readonly IAccountService _accountService; - private readonly SignInManager _signInManager; - private readonly UserManager _userManager; - - public LoginModel( - IAccountService accountService, - SignInManager signInManager, - UserManager userManager) - { - _accountService = accountService; - _signInManager = signInManager; - _userManager = userManager; - } - - [BindProperty(SupportsGet = true)] - public string ReturnUrl { get; set; } - - [BindProperty] - public LoginViewModel Input { get; set; } - - public void OnGet() => Input = new LoginViewModel - { - ReturnUrl = ReturnUrl - }; - - public async Task OnPostAsync() - { - if (!ModelState.IsValid) - { - return Page(); - } - - var user = await _userManager.FindByNameAsync(Input.UserName); - if (user == null) - { - ModelState.AddModelError("UserName", "Пользователь не найден"); - return Page(); - } - - var signInResult = await _signInManager.PasswordSignInAsync(user, Input.Password, true, false); - if (signInResult.Succeeded) - { - var principal = await _accountService.GetPrincipalByIdAsync(user.Id.ToString()); - await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); - - if (Url.IsLocalUrl(ReturnUrl)) - { - return Redirect(ReturnUrl); - } - return RedirectToPage("/swagger"); - } - - ModelState.AddModelError("UserName", "Пользователь не найден"); - return Page(); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/LoginViewModel.cs b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/LoginViewModel.cs deleted file mode 100644 index bffae52e..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/CONNECT/LoginViewModel.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace $safeprojectname$.Pages.Connect; - -public class LoginViewModel -{ - - [Required] - [EmailAddress] - [Display(Name = "Имя для входа")] - public string UserName { get; set; } = null!; - - [Required] - [Display(Name = "Пароль")] - public string Password { get; set; } = null!; - - [Required] - public string ReturnUrl { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/SHARED/_Layout.cshtml b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/SHARED/_Layout.cshtml deleted file mode 100644 index 0e4d68a5..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/SHARED/_Layout.cshtml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - Authorization Server Nimble Framework - - - - -
-
-
- -

- Сервер авторизации -

-

- Version: 7.0.6 -

-
-
-
- @RenderBody() -
-
-
-

- Nimble Framework 2023 © Calabonga SOFT -

-
-
-
- - - - \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/_ViewImports.cshtml b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/_ViewImports.cshtml deleted file mode 100644 index 9018c789..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/_ViewImports.cshtml +++ /dev/null @@ -1 +0,0 @@ -@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/_ViewStart.cshtml b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/_ViewStart.cshtml deleted file mode 100644 index 1af6e494..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/PAGES/_ViewStart.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@{ - Layout = "_Layout"; -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/__PreviewImage.png b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/__PreviewImage.png deleted file mode 100644 index a75ffa16..00000000 Binary files a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/__TemplateIcon.png b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json deleted file mode 100644 index 9e808af8..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "Cors": { - "Origins": "*" - }, - "Serilog": { - "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], - "MinimumLevel": { - "Default": "Debug", - "Override": { - "Microsoft": "Warning", - "System": "Warning", - "OpenIddict": "Warning" - } - }, - "WriteTo": [ - { "Name": "Console" }, - { - "Name": "File", - "Args": { - "path": "/logs/log-.log", - "rollingInterval": "Day", - "rollOnFileSizeLimit": true, - "shared": true, - "formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact" - } - } - ], - "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ] - } -} diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.json b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.json deleted file mode 100644 index 99ddb7b4..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/appsettings.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=;User ID=;Password=" - }, - "Serilog": { - "Using": [ "Serilog.Sinks.Console" ], - "MinimumLevel": { - "Default": "Information", - "Override": { - "Microsoft": "Warning", - "System": "Warning" - } - }, - "WriteTo": [ - { "Name": "Console" } - ], - "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ] - }, - "AuthServer": { - "Url": "https://localhost:10001" - }, - "AllowedHosts": "*" -} diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk b/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk deleted file mode 100644 index 54a03371..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk +++ /dev/null @@ -1 +0,0 @@ -{"alg":"RS256","d":"P7dPY7Wy3wuD_Vls0NBNsrY_j5o70JJk0beTptSFEspyvBlFSpG3wLSqWBqnbZzRmEWJ12Kdn8BgMiB8kzUQk3JjA16o6_USGLCKCnNkWBya4xJ0Yh63YjIVltMNHclsep70NjoTbI8G3UjOUXtKGYyqcC_FSWfmkPugVv7eQwWOasP60sXExfmGHQ5EV8NkVc4VBIkhEGolpVaUbISWg1Gf_CTj_iwm1FzosoUB6dlrQ-CAcYQT0gCRXeP85cnxUrfXQrExyzGC5ablHj9IBMWrUW9KmUqG42gvbuUmkv-0GolHj0DivQjJRMvOhmYzfw-FVly64cSQdYjrdVyiEQ","dp":"vaf7y9sBxE33PlS87g-5besW6OcDYmbL2fHc1Jaqp_tudjk3KE2g608qz18EFNxhduf7n7ACpTCLTLzqYgubGrzvgFWhqJhh2Ts2aEC_EWAnTTyzgq3F6_AwNlpsLYw-FDWU7lLRjgeYu2ZRJcQ1LtrFcBf8lv7EORfGcZ7zeh0","dq":"1mMVHzMx-LnIbaAFht5nce0-8pLj1zf25Jzghlm8Wgi0FAGI8b8V3edbVSJo1V8JdI_we4HjsmC3RA686Z1NsSXIaUxel44GdZXIYAiZA3N30gs5mT07MUPrglPeNm6LMYeYn5fsTk12TSIWTUMTmyW5BNvHTVQjH0dk7maJWzU","e":"AQAB","kid":"72F4E7F8D19F17C0FC47D7CF1FBF61DF","kty":"RSA","n":"sf6uR2CqoZHzcEex5KT54OC6iAd1I-dELjp16-xmkSuqWGOIyyFqqQ5kyxvMlayfSUbdcLTCswaAyomnbu3tUuvccgdhO_7BsFN8eaosYqgUmUP0htI6lirysnFxRxaA-4qozXrNTxMcoxF0hgTtgIg6R8hdKMfpOZi90D1XGZUsNe9GjRLDZZVssM-idookwqTeMmLKLGUZiQwOTc9QOplHYbL52turG3kSTjoOVrrCM1szm9j5VSfmXAug3QJXZe0x0twfBhym8rEljsgr4IopNe8RA4Msg6uZFHCc4rCRXd5xajlSug4g8r_lq0M64Ug4nzIe1kfpMjY8nHnr2Q","p":"0rSFb90z1tu6BxUUQuL3DwJNu6YrSCTunkkgq943YuTV1XO2KXTW1mZbbD_KnvUMRz9CDsnFts-8W6fh7g8-_zFnhnDS7_XoYa7Yf2Aw9hN2VTKGuDNZo9Vidj4jbejXddbY2L3n0qD_iR9PIXuDM_at9zj7xMk88A5NPFY57mM","q":"2EINjDxepSzyh6BPltt3iqExQrtgseUermliIjHc8kSx_j25azscTZC3MYU6hy7AMISqXBoAsc2GCyKfhQpcNlOWXYeRn-QgYzea5kog8OEM1-hneTzhCAbb8IUm7l_JZ11Se423OVKBA9bgg7yj8K94Hid3ayJOTIe4Rzjvo5M","qi":"pst6tRwkUiKMpWSJ2aMp2jsf_14s96c_bzOMoJUgk3T2LjOJ6TTXYW8uyYm76RXJALBbows73rk9sMaohv08MjXT_QCBCDHQGwb1cH07j2aXslkq-pjO7J8vOUvBhc4ZSWzqmyQEqLOC76N_vem1j39w_eu12TbFncQYitmEtBs"} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateIdentityModule/Root.vstemplate b/AspNetCore v7.0/TemplateIdentityModule/Root.vstemplate deleted file mode 100644 index 7095a595..00000000 --- a/AspNetCore v7.0/TemplateIdentityModule/Root.vstemplate +++ /dev/null @@ -1,28 +0,0 @@ - - - Microservice API Template with OpenIddict OAuth 2.0 - Nimble microservice template with Authentication and Authorization. This template gives you a possibility to start developing a microservices system with integrated Swagger, Mediatr, Automapper, OpenIddict and other things. This template is using minimal API feature from .NET 7.0. That's why we implement a Vertical Slice Architecture approach used (Folding by Features) - CSharp - - 1000 - true - Calabonga.Microservice.IdentityModule - true - Enabled - true - __TemplateIcon.png - __PreviewImage.png - - - - - - - Calabonga.Microservice.IdentityModule.Web\MyTemplate.vstemplate - Calabonga.Microservice.IdentityModule.Domain\MyTemplate.vstemplate - Calabonga.Microservice.IdentityModule.Infrastructure\MyTemplate.vstemplate - - - - diff --git a/AspNetCore v7.0/TemplateIdentityModule/__PreviewImage.png b/AspNetCore v7.0/TemplateIdentityModule/__PreviewImage.png deleted file mode 100644 index a75ffa16..00000000 Binary files a/AspNetCore v7.0/TemplateIdentityModule/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateIdentityModule/__TemplateIcon.png b/AspNetCore v7.0/TemplateIdentityModule/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v7.0/TemplateIdentityModule/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/AppData.Common.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/AppData.Common.cs deleted file mode 100644 index b72a2218..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/AppData.Common.cs +++ /dev/null @@ -1,45 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Static data container - /// - public static partial class AppData - { - /// - /// CORS Policy name - /// - public const string PolicyName = "CorsPolicy"; - - /// - /// Current service name - /// - public const string ServiceName = "Microservice Template"; - - /// - /// Nimble Framework Microservice Template with integrated OpenIddict for OpenID Connect server and Token Validation - /// - public const string ServiceDescription = "Nimble Framework Microservice Template with integrated OpenIddict for OpenID Connect server and Token Validation"; - - /// - /// "SystemAdministrator" - /// - public const string SystemAdministratorRoleName = "Administrator"; - - /// - /// "BusinessOwner" - /// - public const string ManagerRoleName = "Manager"; - - /// - /// Roles - /// - public static IEnumerable Roles - { - get - { - yield return SystemAdministratorRoleName; - yield return ManagerRoleName; - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/AppData.Exceptions.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/AppData.Exceptions.cs deleted file mode 100644 index 6f8fad4b..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/AppData.Exceptions.cs +++ /dev/null @@ -1,61 +0,0 @@ -namespace $safeprojectname$.Base -{ - public static partial class AppData - { - /// - /// Exception messages - /// - public static class Exceptions - { - /// - /// "An exception was thrown" - /// - public static string ThrownException => "An exception was thrown"; - - /// - /// "Invalid cast exception" - /// - public static string TypeConverterException => "Invalid cast exception"; - - /// - /// "User not registered in the system" - /// - public static string UserNotFoundException => "User not registered in the system"; - - /// - /// "Object not found" - /// - public static string NotFoundException => "Object not found"; - - /// - /// "Unauthorized access denied" - /// - public static string UnauthorizedException => "Unauthorized access denied"; - - /// - /// "Argument null exception" - /// - public static string ArgumentNullException => "Argument null exception"; - - /// - /// "File already exists" - /// - public static string FileAlreadyExists => "File already exists"; - - /// - /// "Some errors occurred while checking the entity" - /// - public static string EntityValidationException => "Some errors occurred while checking the entity"; - - /// - /// "Invalid operation exception was thrown" - /// - public static string InvalidOperationException => "Invalid operation exception was thrown"; - - /// - /// "Argument out of range" - /// - public static string ArgumentOutOfRangeException => "Argument out of range"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/AppData.Messages.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/AppData.Messages.cs deleted file mode 100644 index 040c5666..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/AppData.Messages.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace $safeprojectname$.Base -{ - public static partial class AppData - { - /// - /// Common messages - /// - public static class Messages - { - /// - /// "User successfully registered" - /// - public static string UserSuccessfullyRegistered => "User successfully registered"; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/Auditable.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/Auditable.cs deleted file mode 100644 index a73d7fb2..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/Auditable.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Represents 'Audit-able' table from the Property Database - /// - public abstract class Auditable : Identity, IAuditable - { - /// - /// DateTime when entity created. - /// It's never changed - /// - public DateTime CreatedAt { get; set; } - - /// - /// User name who created entity. - /// It's never changed - /// - public string CreatedBy { get; set; } - - /// - /// Last date entity updated - /// - public DateTime? UpdatedAt { get; set; } - - /// - /// Author of last updated - /// - public string UpdatedBy { get; set; } - - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/IAuditable.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/IAuditable.cs deleted file mode 100644 index f9d6bbc6..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/IAuditable.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Represent information about creation and last update - /// - public interface IAuditable - { - /// - /// DateTime of creation. This value will never changed - /// - DateTime CreatedAt { get; set; } - - /// - /// Author name. This value never changed - /// - string CreatedBy { get; set; } - - /// - /// DateTime of last value update. Should be updated when entity data updated - /// - DateTime? UpdatedAt { get; set; } - - /// - /// Author of last value update. Should be updated when entity data updated - /// - string UpdatedBy { get; set; } - - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/IHaveId.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/IHaveId.cs deleted file mode 100644 index 44fc68e3..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/IHaveId.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Identifier common interface - /// - public interface IHaveId - { - /// - /// Identifier - /// - Guid Id { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/IViewModel.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/IViewModel.cs deleted file mode 100644 index 73f7b0c7..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/IViewModel.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Represents ViewModel for CRUD controller - /// - public interface IViewModel { } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/Identity.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/Identity.cs deleted file mode 100644 index e5e6d0d1..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/Identity.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Identifier - /// - public abstract class Identity : IHaveId - { - /// - /// Identifier - /// - public Guid Id { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/NamedAuditable.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/NamedAuditable.cs deleted file mode 100644 index 75b37d0b..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/NamedAuditable.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Audit-able with name - /// - public abstract class NamedAuditable : Auditable - { - public string Name { get; set; } - - public string Description { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/NamedIdentity.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/NamedIdentity.cs deleted file mode 100644 index a4af146b..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/NamedIdentity.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// NamedIdentity dictionary for selector - /// - public abstract class NamedIdentity : Identity - { - /// - /// Entity name - /// - public string Name { get; set; } - - /// - /// Entity brief name - /// - public string BriefName { get; set; } - - /// - /// Brief descriptions - /// - public string Description { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/Sortable.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/Sortable.cs deleted file mode 100644 index 4f9dc4c5..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/Sortable.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Order - /// - public class Sortable : Auditable - { - /// - /// Sorting index for entity - /// - public int SortIndex { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/TypeHelper.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/TypeHelper.cs deleted file mode 100644 index 1ddfb335..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/TypeHelper.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// Some helpful methods for Type manipulations - /// - public static class TypeHelper - { - /// - /// Check type before converting - /// - /// - /// - /// - public static bool CanChangeType(object value, Type conversionType) - { - if (conversionType == null) - { - return false; - } - return value is IConvertible; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/ViewModelBase.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/ViewModelBase.cs deleted file mode 100644 index 92228811..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/BASE/ViewModelBase.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace $safeprojectname$.Base -{ - /// - /// ViewModelBase for WritableController - /// - public class ViewModelBase : IViewModel, IHaveId - { - /// - /// Identifier - /// - public Guid Id { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj deleted file mode 100644 index a1ed5b3f..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - - net7.0 - enable - enable - - - diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/EventItem.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/EventItem.cs deleted file mode 100644 index e1c7d3f2..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/EventItem.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace $safeprojectname$ -{ - /// - /// EventItem entity for demo purposes only - /// - public class EventItem : Identity - { - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; - - public string? ThreadId { get; set; } - - public string? ExceptionMessage { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/GlobalUsing.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/GlobalUsing.cs deleted file mode 100644 index e294041c..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/GlobalUsing.cs +++ /dev/null @@ -1 +0,0 @@ -global using $safeprojectname$.Base; \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/MyTemplate.vstemplate b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/MyTemplate.vstemplate deleted file mode 100644 index ddd88cfe..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/MyTemplate.vstemplate +++ /dev/null @@ -1,39 +0,0 @@ - - - Calabonga.Microservice.Module.Domain - Calabonga.Microservice.Module.Domain - CSharp - - - 1000 - true - Calabonga.Microservice.Module.Domain - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - AppData.Common.cs - AppData.Exceptions.cs - AppData.Messages.cs - Auditable.cs - IAuditable.cs - Identity.cs - IHaveId.cs - IViewModel.cs - NamedAuditable.cs - NamedIdentity.cs - Sortable.cs - TypeHelper.cs - ViewModelBase.cs - - EventItem.cs - GlobalUsing.cs - - - \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/__PreviewImage.png b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/__PreviewImage.png deleted file mode 100644 index a75ffa16..00000000 Binary files a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/__TemplateIcon.png b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Domain/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs deleted file mode 100644 index 82153a35..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs +++ /dev/null @@ -1,49 +0,0 @@ -using $safeprojectname$.Base; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Diagnostics; - -namespace $safeprojectname$ -{ - /// - /// Database context for current application - /// - public class ApplicationDbContext : DbContextBase - { - public ApplicationDbContext(DbContextOptions options) - : base(options) { } - - public DbSet EventItems { get; set; } - - public DbSet Profiles { get; set; } - - public DbSet Permissions { get; set; } - - /// - /// - /// Override this method to configure the database (and other options) to be used for this context. - /// This method is called for each instance of the context that is created. - /// The base implementation does nothing. - /// - /// - /// In situations where an instance of may or may not have been passed - /// to the constructor, you can use to determine if - /// the options have already been set, and skip some or all of the logic in - /// . - /// - /// - /// - /// See DbContext lifetime, configuration, and initialization - /// for more information. - /// - /// - /// A builder used to create or modify options for this context. Databases (and other extensions) - /// typically define extension methods on this object that allow you to configure the context. - /// - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)); - - base.OnConfiguring(optionsBuilder); - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationRole.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationRole.cs deleted file mode 100644 index dfcb2a39..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationRole.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace $safeprojectname$ -{ - /// - /// Application role - /// - public class ApplicationRole : IdentityRole - { - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationUser.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationUser.cs deleted file mode 100644 index 1f687374..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationUser.cs +++ /dev/null @@ -1,30 +0,0 @@ - -namespace $safeprojectname$ -{ - /// - /// Default user for application. - /// Add profile data for application users by adding properties to the ApplicationUser class - /// - public class ApplicationUser : IdentityUser - { - /// - /// FirstName - /// - public string FirstName { get; set; } - - /// - /// LastName - /// - public string LastName { get; set; } - - /// - /// Profile identity - /// - public Guid? ApplicationUserProfileId { get; set; } - - /// - /// User Profile - /// - public virtual ApplicationUserProfile ApplicationUserProfile { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationUserProfile.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationUserProfile.cs deleted file mode 100644 index 1ab40401..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationUserProfile.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace $safeprojectname$ -{ - /// - /// Represent person with login information (ApplicationUser) - /// - public class ApplicationUserProfile : Auditable - { - /// - /// Account - /// - public virtual ApplicationUser ApplicationUser { get; set; } - - /// - /// Microservice permission for policy-based authorization - /// - public ICollection Permissions { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationUserStore.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationUserStore.cs deleted file mode 100644 index f8062e23..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/ApplicationUserStore.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; - -namespace $safeprojectname$ -{ - /// - /// Application store for user - /// - public class ApplicationUserStore : UserStore - { - public ApplicationUserStore(ApplicationDbContext context, IdentityErrorDescriber describer = null) - : base(context, describer) - { - - } - - /// - public override Task FindByIdAsync(string userId, CancellationToken cancellationToken = new CancellationToken()) - { - return Users - .Include(x => x.ApplicationUserProfile) - .ThenInclude(x => x.Permissions) - .FirstOrDefaultAsync(u => u.Id.ToString() == userId, cancellationToken: cancellationToken); - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/BASE/DbContextBase.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/BASE/DbContextBase.cs deleted file mode 100644 index ba2c92c1..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/BASE/DbContextBase.cs +++ /dev/null @@ -1,258 +0,0 @@ -using Calabonga.UnitOfWork; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; -using System.Reflection; - -namespace $safeprojectname$.Base -{ - /// - /// Base DbContext with predefined configuration - /// - public abstract class - DbContextBase : IdentityDbContext - { - private const string DefaultUserName = "Anonymous"; - - protected DbContextBase(DbContextOptions options) : base(options) - { - LastSaveChangesResult = new SaveChangesResult(); - } - - public SaveChangesResult LastSaveChangesResult { get; } - - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - /// - /// Saves all changes made in this context to the database. - /// - /// - /// Indicates whether is called after the changes have - /// been sent successfully to the database. - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// The number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override int SaveChanges(bool acceptAllChangesOnSuccess) - { - try - { - DbSaveChanges(); - return base.SaveChanges(acceptAllChangesOnSuccess); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - public override int SaveChanges() - { - try - { - DbSaveChanges(); - return base.SaveChanges(); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return 0; - } - } - - /// - /// Asynchronously saves all changes made in this context to the database. - /// - /// - /// - /// This method will automatically call to discover any - /// changes to entity instances before saving to the underlying database. This can be disabled via - /// . - /// - /// - /// Multiple active operations on the same context instance are not supported. Use 'await' to ensure - /// that any asynchronous operations have completed before calling another method on this context. - /// - /// - /// A to observe while waiting for the task to complete. - /// - /// A task that represents the asynchronous save operation. The task result contains the - /// number of state entries written to the database. - /// - /// - /// An error is encountered while saving to the database. - /// - /// - /// A concurrency violation is encountered while saving to the database. - /// A concurrency violation occurs when an unexpected number of rows are affected during save. - /// This is usually because the data in the database has been modified since it was loaded into memory. - /// - public override Task SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken()) - { - try - { - DbSaveChanges(); - return base.SaveChangesAsync(cancellationToken); - } - catch (Exception exception) - { - LastSaveChangesResult.Exception = exception; - return Task.FromResult(0); - } - } - - private void DbSaveChanges() - { - var createdEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added); - foreach (var entry in createdEntries) - { - if (!(entry.Entity is IAuditable)) - { - continue; - } - - var creationDate = DateTime.Now.ToUniversalTime(); - var userName = entry.Property("CreatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("CreatedBy").CurrentValue; - var updatedAt = entry.Property("UpdatedAt").CurrentValue; - var createdAt = entry.Property("CreatedAt").CurrentValue; - if (createdAt != null) - { - if (DateTime.Parse(createdAt.ToString()).Year > 1970) - { - entry.Property("CreatedAt").CurrentValue = ((DateTime)createdAt).ToUniversalTime(); - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("CreatedAt").CurrentValue = creationDate; - } - - if (updatedAt != null) - { - if (DateTime.Parse(updatedAt.ToString()).Year > 1970) - { - entry.Property("UpdatedAt").CurrentValue = ((DateTime)updatedAt).ToUniversalTime(); - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - } - else - { - entry.Property("UpdatedAt").CurrentValue = creationDate; - } - - entry.Property("CreatedBy").CurrentValue = userName; - entry.Property("UpdatedBy").CurrentValue = userName; - - LastSaveChangesResult.AddMessage($"ChangeTracker has new entities: {entry.Entity.GetType()}"); - } - - var updatedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified); - foreach (var entry in updatedEntries) - { - if (entry.Entity is IAuditable) - { - var userName = entry.Property("UpdatedBy").CurrentValue == null - ? DefaultUserName - : entry.Property("UpdatedBy").CurrentValue; - entry.Property("UpdatedAt").CurrentValue = DateTime.Now.ToUniversalTime(); - entry.Property("UpdatedBy").CurrentValue = userName; - } - - LastSaveChangesResult.AddMessage($"ChangeTracker has modified entities: {entry.Entity.GetType()}"); - } - } - - /// - /// Configures the schema needed for the identity framework. - /// - /// - /// The builder being used to construct the model for this context. - /// - protected override void OnModelCreating(ModelBuilder builder) - { - base.OnModelCreating(builder); - - var applyGenericMethod = typeof(ModelBuilder).GetMethods(BindingFlags.Instance | BindingFlags.Public).First(x => x.Name == "ApplyConfiguration"); - foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters)) - { - foreach (var item in type.GetInterfaces()) - { - if (!item.IsConstructedGenericType || item.GetGenericTypeDefinition() != typeof(IEntityTypeConfiguration<>)) - { - continue; - } - - var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(item.GenericTypeArguments[0]); - applyConcreteMethod.Invoke(builder, new[] { Activator.CreateInstance(type) }); - break; - } - } - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj deleted file mode 100644 index 84ab9a65..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - - net7.0 - enable - enable - - - - - - - - - - - - - - - - - - diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/DATABASEINITIALIZATION/DatabaseInitializer.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/DATABASEINITIALIZATION/DatabaseInitializer.cs deleted file mode 100644 index d364e298..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/DATABASEINITIALIZATION/DatabaseInitializer.cs +++ /dev/null @@ -1,29 +0,0 @@ -namespace $safeprojectname$.DatabaseInitialization -{ - /// - /// Database Initializer - /// - public static class DatabaseInitializer - { - public static async void Seed(IServiceProvider serviceProvider) - { - using var scope = serviceProvider.CreateScope(); - await using var context = scope.ServiceProvider.GetService(); - - // It should be uncomment when using UseSqlServer() settings or any other providers. - // This is should not be used when UseInMemoryDatabase() - // await context!.Database.MigrateAsync(); - - await context!.EventItems.AddAsync(new EventItem - { - CreatedAt = DateTime.UtcNow, - Id = Guid.Parse("1467a5b9-e61f-82b0-425b-7ec75f5c5029"), - Level = "Information", - Logger = "SEED", - Message = "Seed method some entities successfully save to ApplicationDbContext" - }); - - await context.SaveChangesAsync(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/GlobalUsing.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/GlobalUsing.cs deleted file mode 100644 index 1abf8488..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/GlobalUsing.cs +++ /dev/null @@ -1,4 +0,0 @@ -global using $ext_projectname$.Domain; -global using $ext_projectname$.Domain.Base; -global using Microsoft.AspNetCore.Identity; -global using Microsoft.Extensions.DependencyInjection; \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/MicroservicePermission.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/MicroservicePermission.cs deleted file mode 100644 index 2f45dadd..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/MicroservicePermission.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace $safeprojectname$ -{ - /// - /// User permission for microservice - /// - public class MicroservicePermission : Auditable - { - /// - /// Application User profile identifier - /// - public Guid ApplicationUserProfileId { get; set; } - - /// - /// Application User Profile - /// - public virtual ApplicationUserProfile ApplicationUserProfile { get; set; } - - /// - /// Authorize attribute policy name - /// - public string PolicyName { get; set; } - - /// - /// Description for current permission - /// - public string Description { get; set; } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/MyTemplate.vstemplate b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/MyTemplate.vstemplate deleted file mode 100644 index 2643bfce..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/MyTemplate.vstemplate +++ /dev/null @@ -1,35 +0,0 @@ - - - Calabonga.Microservice.Module.Infrastructure - Calabonga.Microservice.Module.Infrastructure - CSharp - - - 1000 - true - Calabonga.Microservice.Module.Infrastructure - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - DbContextBase.cs - - - DatabaseInitializer.cs - - ApplicationDbContext.cs - ApplicationRole.cs - ApplicationUser.cs - ApplicationUserProfile.cs - ApplicationUserStore.cs - GlobalUsing.cs - MicroservicePermission.cs - - - \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/__PreviewImage.png b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/__PreviewImage.png deleted file mode 100644 index a75ffa16..00000000 Binary files a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/__TemplateIcon.png b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Infrastructure/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/.editorconfig b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/.editorconfig deleted file mode 100644 index ad6bdfaf..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/.editorconfig +++ /dev/null @@ -1,228 +0,0 @@ -root = true -# Remove the line below if you want to inherit .editorconfig settings from higher directories - -# C# files -[*.cs] - -#### Core EditorConfig Options #### -charset = utf-8-bom - -# Indentation and spacing -indent_size = 4 -indent_style = space -tab_width = 4 - -# New line preferences -end_of_line = crlf -insert_final_newline = false - -#### .NET Coding Conventions #### - -# Organize usings -dotnet_separate_import_directive_groups = false -dotnet_sort_system_directives_first = false - -# this. and Me. preferences -dotnet_style_qualification_for_event = false:suggestion -dotnet_style_qualification_for_field = false -dotnet_style_qualification_for_method = false:suggestion -dotnet_style_qualification_for_property = false:suggestion - -# Language keywords vs BCL types preferences -dotnet_style_predefined_type_for_locals_parameters_members = true -dotnet_style_predefined_type_for_member_access = true - -# Parentheses preferences -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_operators = never_if_unnecessary -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity - -# Modifier preferences -dotnet_style_require_accessibility_modifiers = for_non_interface_members - -# Expression-level preferences -dotnet_style_coalesce_expression = true -dotnet_style_collection_initializer = true -dotnet_style_explicit_tuple_names = true -dotnet_style_null_propagation = true -dotnet_style_object_initializer = true -dotnet_style_operator_placement_when_wrapping = beginning_of_line -dotnet_style_prefer_auto_properties = true:error -dotnet_style_prefer_compound_assignment = true -dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion -dotnet_style_prefer_conditional_expression_over_return = true:suggestion -dotnet_style_prefer_inferred_anonymous_type_member_names = true:error -dotnet_style_prefer_inferred_tuple_names = true -dotnet_style_prefer_is_null_check_over_reference_equality_method = true -dotnet_style_prefer_simplified_boolean_expressions = true -dotnet_style_prefer_simplified_interpolation = true - -# Field preferences -dotnet_style_readonly_field = true:error - -# Parameter preferences -dotnet_code_quality_unused_parameters = all - -# Suppression preferences -dotnet_remove_unnecessary_suppression_exclusions = none - -#### C# Coding Conventions #### - -# var preferences -csharp_style_var_elsewhere = true:suggestion -csharp_style_var_for_built_in_types = true:suggestion -csharp_style_var_when_type_is_apparent = true:suggestion - -# Expression-bodied members -csharp_style_expression_bodied_accessors = true:suggestion -csharp_style_expression_bodied_constructors = true:suggestion -csharp_style_expression_bodied_indexers = true:suggestion -csharp_style_expression_bodied_lambdas = true -csharp_style_expression_bodied_local_functions = false -csharp_style_expression_bodied_methods = true:suggestion -csharp_style_expression_bodied_operators = true:suggestion -csharp_style_expression_bodied_properties = true:suggestion - -# Pattern matching preferences -csharp_style_pattern_matching_over_as_with_null_check = true -csharp_style_pattern_matching_over_is_with_cast_check = true -csharp_style_prefer_not_pattern = true -csharp_style_prefer_pattern_matching = true -csharp_style_prefer_switch_expression = true - -# Null-checking preferences -csharp_style_conditional_delegate_call = true - -# Modifier preferences -csharp_prefer_static_local_function = true -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async - -# Code-block preferences -csharp_prefer_braces = true:error -csharp_prefer_simple_using_statement = true - -# Expression-level preferences -csharp_prefer_simple_default_expression = true -csharp_style_deconstructed_variable_declaration = true -csharp_style_implicit_object_creation_when_type_is_apparent = true -csharp_style_inlined_variable_declaration = true -csharp_style_pattern_local_over_anonymous_function = true -csharp_style_prefer_index_operator = true -csharp_style_prefer_range_operator = true -csharp_style_throw_expression = true -csharp_style_unused_value_assignment_preference = discard_variable -csharp_style_unused_value_expression_statement_preference = discard_variable - -# 'using' directive preferences -csharp_using_directive_placement = outside_namespace - -#### C# Formatting Rules #### - -# New line preferences -csharp_new_line_before_catch = true -csharp_new_line_before_else = true -csharp_new_line_before_finally = true -csharp_new_line_before_members_in_anonymous_types = true -csharp_new_line_before_members_in_object_initializers = true -csharp_new_line_before_open_brace = all -csharp_new_line_between_query_expression_clauses = true - -# Indentation preferences -csharp_indent_block_contents = true -csharp_indent_braces = false -csharp_indent_case_contents = true -csharp_indent_case_contents_when_block = true -csharp_indent_labels = no_change -csharp_indent_switch_labels = true - -# Space preferences -csharp_space_after_cast = false -csharp_space_after_colon_in_inheritance_clause = true -csharp_space_after_comma = true -csharp_space_after_dot = false -csharp_space_after_keywords_in_control_flow_statements = true -csharp_space_after_semicolon_in_for_statement = true -csharp_space_around_binary_operators = before_and_after -csharp_space_around_declaration_statements = false -csharp_space_before_colon_in_inheritance_clause = true -csharp_space_before_comma = false -csharp_space_before_dot = false -csharp_space_before_open_square_brackets = false -csharp_space_before_semicolon_in_for_statement = false -csharp_space_between_empty_square_brackets = false -csharp_space_between_method_call_empty_parameter_list_parentheses = false -csharp_space_between_method_call_name_and_opening_parenthesis = false -csharp_space_between_method_call_parameter_list_parentheses = false -csharp_space_between_method_declaration_empty_parameter_list_parentheses = false -csharp_space_between_method_declaration_name_and_open_parenthesis = false -csharp_space_between_method_declaration_parameter_list_parentheses = false -csharp_space_between_parentheses = false -csharp_space_between_square_brackets = false - -# Wrapping preferences -csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true - -#### Naming styles #### - -# Naming rules - -dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion -dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface -dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i - -dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.types_should_be_pascal_case.symbols = types -dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case - -dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members -dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case - -# Symbol specifications - -dotnet_naming_symbols.interface.applicable_kinds = interface -dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interface.required_modifiers = - -dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum -dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types.required_modifiers = - -dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method -dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.non_field_members.required_modifiers = - -# Naming styles - -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = -dotnet_naming_style.pascal_case.capitalization = pascal_case - -dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = -dotnet_naming_style.begins_with_i.capitalization = pascal_case - -# Instance fields are camelCase and start with _ -dotnet_naming_rule.instance_fields_should_be_camel_case.severity = hint -dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields -dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style - -dotnet_naming_symbols.instance_fields.applicable_kinds = field - -dotnet_naming_style.instance_field_style.capitalization = camel_case -dotnet_naming_style.instance_field_style.required_prefix = _ - -# ReSharper properties -max_line_length = 200 -resharper_csharp_max_line_length = 200 -resharper_csharp_wrap_after_declaration_lpar = true -resharper_csharp_wrap_extends_list_style = chop_if_long -resharper_csharp_wrap_lines = false -resharper_max_attribute_length_for_same_line = 300 -resharper_place_type_constraints_on_same_line = true -resharper_wrap_before_arrow_with_expressions = true -resharper_wrap_before_extends_colon = false \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/APPLICATION/ValidatorBehavior.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/APPLICATION/ValidatorBehavior.cs deleted file mode 100644 index 6ab3152d..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/APPLICATION/ValidatorBehavior.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Calabonga.OperationResults; -using FluentValidation; -using MediatR; - -namespace $safeprojectname$.Application; - -/// -/// Base validator for requests -/// -/// -/// -public class ValidatorBehavior : IPipelineBehavior - where TRequest : IRequest -{ - private readonly IEnumerable> _validators; - - public ValidatorBehavior(IEnumerable> validators) => _validators = validators; - - /// - /// Pipeline handler. Perform any additional behavior and await the delegate as necessary - /// - /// Incoming request - /// Cancellation token - /// Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler. - /// Awaitable task returning the - public Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) - { - var failures = _validators - .Select(x => x.Validate(new ValidationContext(request))) - .SelectMany(x => x.Errors) - .Where(x => x != null) - .ToList(); - - if (!failures.Any()) - { - return next(); - } - - var type = typeof(TResponse); - if (!type.IsSubclassOf(typeof(OperationResult))) - { - throw new ValidationException(failures); - } - - var result = Activator.CreateInstance(type); - ((OperationResult)result!).AddError(new ValidationException(failures)); - return Task.FromResult((TResponse)result!); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj deleted file mode 100644 index 40189897..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj +++ /dev/null @@ -1,31 +0,0 @@ - - - - net7.0 - enable - enable - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/COMMON/CommonDefinition.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/COMMON/CommonDefinition.cs deleted file mode 100644 index cafd1f2a..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/COMMON/CommonDefinition.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace $safeprojectname$.Definitions.Common; - -/// -/// AspNetCore common configuration -/// -public class CommonDefinition : AppDefinition -{ - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) - => app.UseHttpsRedirection(); - - /// - /// Configure services for current microservice - /// - /// - public override void ConfigureServices(WebApplicationBuilder builder) - { - builder.Services.AddLocalization(); - builder.Services.AddHttpContextAccessor(); - builder.Services.AddResponseCaching(); - builder.Services.AddMemoryCache(); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/CORS/CorsDefinition.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/CORS/CorsDefinition.cs deleted file mode 100644 index 628c1b92..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/CORS/CorsDefinition.cs +++ /dev/null @@ -1,47 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$.Definitions.Cors; - -/// -/// Cors configurations -/// -public class CorsDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices( WebApplicationBuilder builder) - { - var origins = builder.Configuration.GetSection("Cors")?.GetSection("Origins")?.Value?.Split(','); - builder.Services.AddCors(options => - { - options.AddPolicy(AppData.PolicyName, builder => - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - if (origins is not {Length: > 0}) - { - return; - } - - if (origins.Contains("*")) - { - builder.AllowAnyHeader(); - builder.AllowAnyMethod(); - builder.SetIsOriginAllowed(host => true); - builder.AllowCredentials(); - } - else - { - foreach (var origin in origins) - { - builder.WithOrigins(origin); - } - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/DATASEEDING/DataSeedingDefinition.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/DATASEEDING/DataSeedingDefinition.cs deleted file mode 100644 index 8465db60..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/DATASEEDING/DataSeedingDefinition.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure.DatabaseInitialization; - -namespace $safeprojectname$.Definitions.DataSeeding; - -/// -/// Seeding DbContext for default data for EntityFrameworkCore -/// -public class DataSeedingDefinition : AppDefinition -{ - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) - => DatabaseInitializer.Seed(app.Services); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/DBCONTEXT/DbContextDefinition.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/DBCONTEXT/DbContextDefinition.cs deleted file mode 100644 index 0835e665..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/DBCONTEXT/DbContextDefinition.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using Microsoft.EntityFrameworkCore; - -namespace $safeprojectname$.Definitions.DbContext; - -/// -/// ASP.NET Core services registration and configurations -/// -public class DbContextDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices( WebApplicationBuilder builder) - => builder.Services.AddDbContext(config => - { - // UseInMemoryDatabase - This for demo purposes only! - // Should uninstall package "Microsoft.EntityFrameworkCore.InMemory" and install what you need. - // For example: "Microsoft.EntityFrameworkCore.SqlServer" - // uncomment line below to use UseSqlServer(). Don't forget setup connection string in appSettings.json - config.UseInMemoryDatabase("DEMO_PURPOSES_ONLY"); - // config.UseSqlServer(configuration.GetConnectionString(nameof(ApplicationDbContext))); - }); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/ERRORHANDLING/ErrorHandlingDefinition.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/ERRORHANDLING/ErrorHandlingDefinition.cs deleted file mode 100644 index 24ce7a72..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/ERRORHANDLING/ErrorHandlingDefinition.cs +++ /dev/null @@ -1,57 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using FluentValidation; -using Microsoft.AspNetCore.Diagnostics; -using Serilog; -using System.Net; -using System.Security.Authentication; - -namespace $safeprojectname$.Definitions.ErrorHandling; - -/// -/// Custom Error handling -/// -public class ErrorHandlingDefinition : AppDefinition -{ - -#if DEBUG - public override bool Enabled => false; -#else - public override bool Enabled => true; -#endif - - /// - /// Configure application for current application - /// - /// - public override void ConfigureApplication(WebApplication app) => - app.UseExceptionHandler(error => error.Run(async context => - { - - context.Response.ContentType = "application/json"; - var contextFeature = context.Features.Get(); - if (contextFeature is not null) - { - // handling all another errors - Log.Error($"Something went wrong in the {contextFeature.Error}"); - context.Response.StatusCode = StatusCodes.Status500InternalServerError; - - if (app.Environment.IsDevelopment()) - { - await context.Response.WriteAsync($"INTERNAL SERVER ERROR: {contextFeature.Error}"); - } - else - { - await context.Response.WriteAsync("INTERNAL SERVER ERROR. PLEASE TRY AGAIN LATER"); - } - } - })); - - private static HttpStatusCode GetErrorCode(Exception e) - => e switch - { - ValidationException _ => HttpStatusCode.BadRequest, - AuthenticationException _ => HttpStatusCode.Forbidden, - NotImplementedException _ => HttpStatusCode.NotImplemented, - _ => HttpStatusCode.InternalServerError - }; -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/ETAGGENERATOR/ETagGeneratorDefinition.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/ETAGGENERATOR/ETagGeneratorDefinition.cs deleted file mode 100644 index 046c7cbe..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/ETAGGENERATOR/ETagGeneratorDefinition.cs +++ /dev/null @@ -1,75 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using Microsoft.AspNetCore.WebUtilities; -using Microsoft.Net.Http.Headers; -using System.Security.Cryptography; - -namespace $safeprojectname$.Definitions.ETagGenerator; - -/// -/// ETag Generator -/// -public class ETagGeneratorDefinition : AppDefinition -{ -#if DEBUG - public override bool Enabled => false; -#else - public override bool Enabled => true; -#endif - - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) => - app.Use(async (context, next) => - { - var response = context.Response; - var originalStream = response.Body; - - await using var ms = new MemoryStream(); - response.Body = ms; - - await next(context); - - if (IsEtagSupported(response)) - { - var checksum = CalculateChecksum(ms); - - response.Headers[HeaderNames.ETag] = checksum; - - if (context.Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var etag) && checksum == etag) - { - response.StatusCode = StatusCodes.Status304NotModified; - return; - } - } - - ms.Position = 0; - await ms.CopyToAsync(originalStream); - }); - - - private static bool IsEtagSupported(HttpResponse response) - { - if (response.StatusCode != StatusCodes.Status200OK) - { - return false; - } - - // The 100kb length limit is not based in science. Feel free to change - if (response.Body.Length > 100 * 1024) - { - return false; - } - - return !response.Headers.ContainsKey(HeaderNames.ETag); - } - - private static string CalculateChecksum(MemoryStream ms) - { - using var algorithm = SHA1.Create(); - ms.Position = 0; - var bytes = algorithm.ComputeHash(ms); - return $"\"{WebEncoders.Base64UrlEncode(bytes)}\""; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/FLUENTVALIDATING/FluentValidationDefinition.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/FLUENTVALIDATING/FluentValidationDefinition.cs deleted file mode 100644 index 4364a32e..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/FLUENTVALIDATING/FluentValidationDefinition.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using FluentValidation; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Definitions.FluentValidating; - -/// -/// FluentValidation registration as MicroserviceDefinition -/// -public class FluentValidationDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices( WebApplicationBuilder builder) - { - builder.Services.Configure(options => - { - options.SuppressModelStateInvalidFilter = true; - }); - - builder.Services.AddValidatorsFromAssembly(typeof(Program).Assembly); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/AuthData.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/AuthData.cs deleted file mode 100644 index df8dbc5a..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/AuthData.cs +++ /dev/null @@ -1,8 +0,0 @@ -using OpenIddict.Server.AspNetCore; - -namespace $safeprojectname$.Definitions.Identity; - -public static class AuthData -{ - public const string AuthSchemes = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/UserIdentity.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/UserIdentity.cs deleted file mode 100644 index 347c93bf..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/UserIdentity.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Calabonga.Microservices.Core.Exceptions; -using System.Security.Claims; -using System.Security.Principal; - -namespace $safeprojectname$.Definitions.Identity; - -/// -/// Identity helper for Requests operations -/// -public sealed class UserIdentity -{ - private UserIdentity() { } - - public static UserIdentity Instance => _lazy.Value; - - public void Configure(IHttpContextAccessor httpContextAccessor) - { - ContextAccessor = httpContextAccessor ?? throw new MicroserviceArgumentNullException(nameof(IHttpContextAccessor)); - IsInitialized = true; - } - - public IIdentity? User - { - get - { - if (IsInitialized) - { - return ContextAccessor.HttpContext!.User.Identity != null - && ContextAccessor.HttpContext != null - && ContextAccessor.HttpContext.User.Identity.IsAuthenticated - ? ContextAccessor.HttpContext.User.Identity - : null; - } - throw new MicroserviceArgumentNullException($"{nameof(UserIdentity)} has not been initialized. Please use {nameof(UserIdentity)}.Instance.Configure(...) in Configure Application method in Startup.cs"); - } - } - - public IEnumerable Claims - { - get - { - if (User != null) - { - return ContextAccessor.HttpContext!.User.Claims; - } - return Enumerable.Empty(); - } - } - - private static readonly Lazy _lazy = new(() => new UserIdentity()); - - private bool IsInitialized { get; set; } - - private static IHttpContextAccessor ContextAccessor { get; set; } = null!; - -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MAPPING/AutomapperDefinition.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MAPPING/AutomapperDefinition.cs deleted file mode 100644 index b3cf257b..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MAPPING/AutomapperDefinition.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace $safeprojectname$.Definitions.Mapping; - -/// -/// Register Automapper as MicroserviceDefinition -/// -public class AutomapperDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices(WebApplicationBuilder builder) - => builder.Services.AddAutoMapper(typeof(Program)); - - /// - /// Configure application for current microservice - /// - /// - public override void ConfigureApplication(WebApplication app) - { - var mapper = app.Services.GetRequiredService(); - if (app.Environment.IsDevelopment()) - { - // validate Mapper Configuration - mapper.AssertConfigurationIsValid(); - } - else - { - mapper.CompileMappings(); - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/BASE/UnitOfWorkTransactionBehavior.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/BASE/UnitOfWorkTransactionBehavior.cs deleted file mode 100644 index b588a961..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/BASE/UnitOfWorkTransactionBehavior.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Definitions.Mediator.Base; - -/// -/// Transaction Behavior -/// -/// -/// -public class TransactionBehavior : IPipelineBehavior - where TRequest : IRequest -{ - private readonly IUnitOfWork _unitOfWork; - - public TransactionBehavior(IUnitOfWork unitOfWork) => _unitOfWork = unitOfWork; - - - public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) - { - await using var transaction = await _unitOfWork.BeginTransactionAsync(); - try - { - var response = await next(); - await transaction.CommitAsync(cancellationToken); - return response; - } - catch (Exception) - { - await transaction.RollbackAsync(cancellationToken); - throw; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/LogPostTransaction.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/LogPostTransaction.cs deleted file mode 100644 index 071a6126..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/LogPostTransaction.cs +++ /dev/null @@ -1,12 +0,0 @@ -using $safeprojectname$.Definitions.Mediator.Base; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Definitions.Mediator; - -public class LogPostTransactionBehavior : TransactionBehavior>, OperationResult> -{ - public LogPostTransactionBehavior(IUnitOfWork unitOfWork) : base(unitOfWork) { } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/MediatorDefinition.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/MediatorDefinition.cs deleted file mode 100644 index b7ad09f5..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MEDIATOR/MediatorDefinition.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Application; -using MediatR; - -namespace $safeprojectname$.Definitions.Mediator; - -/// -/// Register Mediator as MicroserviceDefinition -/// -public class MediatorDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices( WebApplicationBuilder builder) - { - builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidatorBehavior<,>)); - builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining()); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/AppPermissionHandler.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/AppPermissionHandler.cs deleted file mode 100644 index b550bbe8..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/AppPermissionHandler.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Calabonga.Microservices.Core; -using Microsoft.AspNetCore.Authorization; -using System.Security.Claims; - -namespace $safeprojectname$.Definitions.OpenIddict; - -/// -/// Permission handler for custom authorization implementations -/// -public class AppPermissionHandler : AuthorizationHandler -{ - /// - protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) - { - if (context.User.Identity is null) - { - return Task.CompletedTask; - } - - var identity = (ClaimsIdentity)context.User.Identity; - var claim = ClaimsHelper.GetValue(identity, requirement.PermissionName); - if (claim == null) - { - return Task.CompletedTask; - } - - context.Succeed(requirement); - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/AuthorizationPolicyProvider.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/AuthorizationPolicyProvider.cs deleted file mode 100644 index 47dd81f1..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/AuthorizationPolicyProvider.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.Extensions.Options; - -namespace $safeprojectname$.Definitions.OpenIddict; - -/// -/// Policy provider -/// -public class AuthorizationPolicyProvider : DefaultAuthorizationPolicyProvider -{ - private readonly AuthorizationOptions _options; - - /// - public AuthorizationPolicyProvider(IOptions options) : base(options) => _options = options.Value; - - /// - public override async Task GetPolicyAsync(string policyName) - { - var policyExists = await base.GetPolicyAsync(policyName); - if (policyExists != null) - { - return policyExists; - } - - policyExists = new AuthorizationPolicyBuilder().AddRequirements(new PermissionRequirement(policyName)).Build(); - _options.AddPolicy(policyName, policyExists); - return policyExists; - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/OpenIddictDefinition.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/OpenIddictDefinition.cs deleted file mode 100644 index 2cbc9d65..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/OpenIddictDefinition.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; - -namespace $safeprojectname$.Definitions.OpenIddict; - -public class OpenIddictDefinition : AppDefinition -{ - public override void ConfigureServices(WebApplicationBuilder builder) => - builder.Services - .AddOpenIddict() - .AddValidation(options => - { - // Import the configuration from the local OpenIddict server instance. - options.UseLocalServer(); - - // Register the ASP.NET Core host. - options.UseAspNetCore(); - }); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/PermissionRequirement.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/PermissionRequirement.cs deleted file mode 100644 index 5c3d40c2..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/OPENIDDICT/PermissionRequirement.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Microsoft.AspNetCore.Authorization; - -namespace $safeprojectname$.Definitions.OpenIddict; - -/// -/// Permission requirement for user or service authorization -/// -public class PermissionRequirement : IAuthorizationRequirement -{ - public PermissionRequirement(string permissionName) => PermissionName = permissionName; - - /// - /// Permission name - /// - public string PermissionName { get; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/SWAGGER/SwaggerDefinition.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/SWAGGER/SwaggerDefinition.cs deleted file mode 100644 index 1ccc00eb..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/SWAGGER/SwaggerDefinition.cs +++ /dev/null @@ -1,126 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Domain.Base; -using Microsoft.AspNetCore.Mvc; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerUI; - -namespace $safeprojectname$.Definitions.Swagger; - -/// -/// Swagger definition for application -/// -public class SwaggerDefinition : AppDefinition -{ - // ATTENTION! - // If you use are git repository then you can uncomment line with "ThisAssembly" below for versioning by GIT possibilities. - // Otherwise, you can change versions of your API by manually. - // If you are not going to use git-versioning, do not forget install package "GitInfo" - // private const string _appVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; - private const string _appVersion = "7.0.6"; - - private const string _swaggerConfig = "/swagger/v1/swagger.json"; - - public override void ConfigureApplication(WebApplication app) - { - if (!app.Environment.IsDevelopment()) - { - return; - } - - app.UseSwagger(); - app.UseSwaggerUI(settings => - { - settings.SwaggerEndpoint(_swaggerConfig, $"{AppData.ServiceName} v.{_appVersion}"); - - // ATTENTION! - // If you use are git repository then you can uncomment line with "ThisAssembly" below for versioning by GIT possibilities. - // settings.HeadContent = $"{ThisAssembly.Git.Branch.ToUpper()} {ThisAssembly.Git.Commit.ToUpper()}"; - - settings.DocumentTitle = $"{AppData.ServiceName}"; - settings.DefaultModelExpandDepth(0); - settings.DefaultModelRendering(ModelRendering.Model); - settings.DefaultModelsExpandDepth(0); - settings.DocExpansion(DocExpansion.None); - settings.OAuthScopeSeparator(" "); - settings.OAuthClientId("client-id-code"); - settings.OAuthClientSecret("client-secret-code"); - settings.DisplayRequestDuration(); - settings.OAuthAppName(AppData.ServiceName); - }); - } - - public override void ConfigureServices(WebApplicationBuilder builder) - { - builder.Services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); - builder.Services.AddEndpointsApiExplorer(); - builder.Services.AddSwaggerGen(options => - { - options.SwaggerDoc("v1", new OpenApiInfo - { - Title = AppData.ServiceName, - Version = _appVersion, - Description = AppData.ServiceDescription - }); - - options.ResolveConflictingActions(x => x.First()); - - options.TagActionsBy(api => - { - string tag; - if (api.ActionDescriptor is { } descriptor) - { - var attribute = descriptor.EndpointMetadata.OfType().FirstOrDefault(); - tag = attribute?.GroupName ?? descriptor.RouteValues["controller"] ?? "Untitled"; - } - else - { - tag = api.RelativePath!; - } - - var tags = new List(); - if (!string.IsNullOrEmpty(tag)) - { - tags.Add(tag); - } - return tags; - }); - - var url = builder.Configuration.GetSection("AuthServer").GetValue("Url"); - - options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - AuthorizationCode = new OpenApiOAuthFlow - { - AuthorizationUrl = new Uri($"{url}/connect/authorize", UriKind.Absolute), - TokenUrl = new Uri($"{url}/connect/token", UriKind.Absolute), - Scopes = new Dictionary - { - { "api", "Default scope" } - } - } - } - }); - options.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "oauth2" - }, - Scheme = "oauth2", - Name = "Bearer", - In = ParameterLocation.Header, - - }, - new List() - } - }); - }); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/UOW/UnitOfWorkDefinition.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/UOW/UnitOfWorkDefinition.cs deleted file mode 100644 index ddedba97..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/UOW/UnitOfWorkDefinition.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Infrastructure; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Definitions.UoW; - -/// -/// Unit of Work registration as MicroserviceDefinition -/// -public class UnitOfWorkDefinition : AppDefinition -{ - /// - /// Configure services for current microservice - /// - /// - /// - public override void ConfigureServices( WebApplicationBuilder builder) - => builder.Services.AddUnitOfWork(); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemEndpoints.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemEndpoints.cs deleted file mode 100644 index b821561a..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemEndpoints.cs +++ /dev/null @@ -1,58 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Definitions.Identity; -using $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints; - -public class EventItemEndpoints : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - { - app.MapGet("/api/logs/{id}", LogGetById); - app.MapGet("/api/logs/paged", LogGetPaged); - app.MapPost("/api/logs/", PostLog); - app.MapPut("/api/logs/{id}", PutLog); - app.MapDelete("/api/logs/{id}", LogDelete); - } - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogGetById([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new GetEventItemById.Request(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> LogDelete([FromServices] IMediator mediator, Guid id, HttpContext context) - => await mediator.Send(new DeleteEventItem.Request(id), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task>> LogGetPaged([FromServices] IMediator mediator, int pageIndex, int pageSize, string? search, HttpContext context) - => await mediator.Send(new GetEventItemPaged.Request(pageIndex, pageSize, search), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PostLog([FromServices] IMediator mediator, EventItemCreateViewModel model, HttpContext context) - => await mediator.Send(new PostEventItem.Request(model), context.RequestAborted); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes)] - [FeatureGroupName("EventItems")] - private async Task> PutLog([FromServices] IMediator mediator, Guid id, EventItemUpdateViewModel model, HttpContext context) - => await mediator.Send(new PutEventItem.Request(id, model), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemMapperConfiguration.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemMapperConfiguration.cs deleted file mode 100644 index 9fa595b9..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemMapperConfiguration.cs +++ /dev/null @@ -1,32 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Definitions.Mapping; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.UnitOfWork; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints; - -/// -/// Mapper Configuration for entity EventItem -/// -public class EventItemMapperConfiguration : Profile -{ - /// - public EventItemMapperConfiguration() - { - CreateMap() - .ForMember(x => x.Id, o => o.Ignore()); - - CreateMap(); - - CreateMap(); - - CreateMap() - .ForMember(x => x.CreatedAt, o => o.Ignore()) - .ForMember(x => x.ThreadId, o => o.Ignore()) - .ForMember(x => x.ExceptionMessage, o => o.Ignore()); - - CreateMap, IPagedList>() - .ConvertUsing>(); - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemValidator.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemValidator.cs deleted file mode 100644 index a2d3aeb5..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/EventItemValidator.cs +++ /dev/null @@ -1,20 +0,0 @@ -using $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; -using FluentValidation; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints; - -/// -/// RegisterViewModel Validator -/// -public class EventItemCreateRequestValidator : AbstractValidator -{ - public EventItemCreateRequestValidator() => RuleSet("default", () => - { - RuleFor(x => x.Model.CreatedAt).NotNull(); - RuleFor(x => x.Model.Message).NotEmpty().MaximumLength(4000); - RuleFor(x => x.Model.Level).NotEmpty().MaximumLength(50); - RuleFor(x => x.Model.Logger).NotEmpty().MaximumLength(255); - RuleFor(x => x.Model.ThreadId).MaximumLength(50); - RuleFor(x => x.Model.ExceptionMessage).MaximumLength(4000); - }); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/DeleteEventItem.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/DeleteEventItem.cs deleted file mode 100644 index 4e5c5009..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/DeleteEventItem.cs +++ /dev/null @@ -1,57 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem delete -/// -public class DeleteEventItem -{ - public record Request(Guid Id) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(Request request, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.FindAsync(request.Id); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException("Entity not found")); - return operation; - } - - repository.Delete(entity); - await _unitOfWork.SaveChangesAsync(); - if (_unitOfWork.LastSaveChangesResult.IsOk) - { - operation.Result = _mapper.Map(entity); - return operation; - } - - operation.AddError(_unitOfWork.LastSaveChangesResult.Exception); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemById.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemById.cs deleted file mode 100644 index c91b7c3c..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemById.cs +++ /dev/null @@ -1,49 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request for EventItem by Identifier -/// -public class GetEventItemById -{ - public record Request(Guid Id) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - /// Handles a request getting log by identifier - /// The request - /// Cancellation token - /// Response from the request - public async Task> Handle(Request request, CancellationToken cancellationToken) - { - var id = request.Id; - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entityWithoutIncludes = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == id); - if (entityWithoutIncludes == null) - { - operation.AddError(new MicroserviceNotFoundException($"Entity with identifier {id} not found")); - return operation; - } - - operation.Result = _mapper.Map(entityWithoutIncludes); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemPaged.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemPaged.cs deleted file mode 100644 index 650c520e..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/GetEventItemPaged.cs +++ /dev/null @@ -1,76 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.OperationResults; -using Calabonga.PredicatesBuilder; -using Calabonga.UnitOfWork; -using MediatR; -using System.Linq.Expressions; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request for paged list of EventItems -/// -public class GetEventItemPaged -{ - public record Request(int PageIndex, int PageSize, string? Search) : IRequest>>; - - public class Handler : IRequestHandler>> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task>> Handle( - Request request, - CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult>(); - var predicate = GetPredicate(request.Search); - var pagedList = await _unitOfWork.GetRepository() - .GetPagedListAsync( - predicate: predicate, - pageIndex: request.PageIndex, - pageSize: request.PageSize, - cancellationToken: cancellationToken); - - if (pagedList == null) - { - operation.Result = PagedList.Empty(); - operation.AddWarning("Response does not return the result for pagination."); - return operation; - } - - if (pagedList.PageIndex > pagedList.TotalPages) - { - pagedList = await _unitOfWork.GetRepository() - .GetPagedListAsync( - pageIndex: 0, - pageSize: request.PageSize, cancellationToken: cancellationToken); - } - - operation.Result = _mapper.Map>(pagedList); - return operation; - } - - private Expression> GetPredicate(string? search) - { - var predicate = PredicateBuilder.True(); - if (search is null) - { - return predicate; - } - - predicate = predicate.And(x => x.Message.Contains(search)); - predicate = predicate.Or(x => x.Logger.Contains(search)); - predicate = predicate.Or(x => x.Level.Contains(search)); - return predicate; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/PostEventItem.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/PostEventItem.cs deleted file mode 100644 index 8efb61b6..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/PostEventItem.cs +++ /dev/null @@ -1,68 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem creation -/// -public class PostEventItem -{ - public record Request(EventItemCreateViewModel Model) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - private readonly ILogger _logger; - - - public Handler(IUnitOfWork unitOfWork, IMapper mapper, ILogger logger) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - _logger = logger; - } - - public async Task> Handle(Request eventItemRequest, CancellationToken cancellationToken) - { - _logger.LogDebug("Creating new EventItem"); - - var operation = OperationResult.CreateResult(); - - var entity = _mapper.Map(eventItemRequest.Model); - if (entity == null) - { - var exceptionMapper = new MicroserviceUnauthorizedException(AppContracts.Exceptions.MappingException); - operation.AddError(exceptionMapper); - _logger.LogError(exceptionMapper, "Mapper not configured correctly or something went wrong"); - return operation; - } - - await _unitOfWork.GetRepository().InsertAsync(entity, cancellationToken); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("Successfully created"); - _logger.LogInformation("New entity {@EventItem} successfully created", entity); - return operation; - } - - var exception = lastResult.Exception ?? new ApplicationException("Something went wrong"); - operation.AddError(exception); - _logger.LogError(exception, "Error data saving to Database or something went wrong"); - - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/UpdateEventItem.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/UpdateEventItem.cs deleted file mode 100644 index 2bd5d9d9..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/QUERIES/UpdateEventItem.cs +++ /dev/null @@ -1,59 +0,0 @@ -using AutoMapper; -using $ext_projectname$.Domain; -using $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using Calabonga.Microservices.Core.Exceptions; -using Calabonga.OperationResults; -using Calabonga.UnitOfWork; -using MediatR; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.Queries; - -/// -/// Request: EventItem edit -/// -public class PutEventItem -{ - public record Request(Guid Id, EventItemUpdateViewModel Model) : IRequest>; - - public class Handler : IRequestHandler> - { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task> Handle(Request eventItemRequest, CancellationToken cancellationToken) - { - var operation = OperationResult.CreateResult(); - var repository = _unitOfWork.GetRepository(); - var entity = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == eventItemRequest.Id, disableTracking: false); - if (entity == null) - { - operation.AddError(new MicroserviceNotFoundException(AppContracts.Exceptions.NotFoundException)); - return operation; - } - - _mapper.Map(eventItemRequest.Model, entity); - - repository.Update(entity); - await _unitOfWork.SaveChangesAsync(); - - var lastResult = _unitOfWork.LastSaveChangesResult; - if (lastResult.IsOk) - { - var mapped = _mapper.Map(entity); - operation.Result = mapped; - operation.AddSuccess("Successfully updated"); - return operation; - } - - operation.AddError(lastResult.Exception ?? new ApplicationException("Something went wrong")); - return operation; - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemCreateViewModel.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemCreateViewModel.cs deleted file mode 100644 index 054466de..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemCreateViewModel.cs +++ /dev/null @@ -1,36 +0,0 @@ -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemCreateViewModel : IViewModel -{ - /// - /// EventItem Created At - /// - public DateTime CreatedAt { get; set; } - - /// - /// Service name or provider - /// - public string Logger { get; set; } = null!; - - /// - /// EventItem level for logging. See - /// - public string Level { get; set; } = null!; - - /// - /// EventItem Message - /// - public string Message { get; set; } = null!; - - /// - /// Thread identifier - /// - public string? ThreadId { get; set; } - - /// - /// Exception message - /// - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemUpdateViewModel.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemUpdateViewModel.cs deleted file mode 100644 index 6dc45417..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemUpdateViewModel.cs +++ /dev/null @@ -1,12 +0,0 @@ -using $ext_projectname$.Domain.Base; - -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemUpdateViewModel : ViewModelBase -{ - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemViewModel.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemViewModel.cs deleted file mode 100644 index 39211dbc..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/EVENTITEMSENDPOINTS/VIEWMODELS/EventItemViewModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace $safeprojectname$.Endpoints.EventItemsEndpoints.ViewModels; - -public class EventItemViewModel -{ - public Guid Id { get; set; } - - public DateTime CreatedAt { get; set; } - - public string Logger { get; set; } = null!; - - public string Level { get; set; } = null!; - - public string Message { get; set; } = null!; - - public string? ThreadId { get; set; } - - public string? ExceptionMessage { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesEndpoint.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesEndpoint.cs deleted file mode 100644 index 92b601a8..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesEndpoint.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Calabonga.AspNetCore.AppDefinitions; -using $safeprojectname$.Definitions.Identity; -using $safeprojectname$.Endpoints.ProfileEndpoints.Queries; -using MediatR; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints; - -public class ProfilesEndpointDefinition : AppDefinition -{ - public override void ConfigureApplication(WebApplication app) - => app.MapGet("/api/profiles/get-roles", GetRoles); - - [ProducesResponseType(200)] - [ProducesResponseType(401)] - [Authorize(AuthenticationSchemes = AuthData.AuthSchemes, Policy = "EventItems:UserRoles:View")] - [FeatureGroupName("Profiles")] - private async Task GetRoles([FromServices] IMediator mediator, HttpContext context) - => await mediator.Send(new GetProfile.Request(), context.RequestAborted); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesMapperConfiguration.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesMapperConfiguration.cs deleted file mode 100644 index 7028f518..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/ProfilesMapperConfiguration.cs +++ /dev/null @@ -1,23 +0,0 @@ -using AutoMapper; -using $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; -using Calabonga.Microservices.Core; -using System.Security.Claims; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints; - -/// -/// Mapper Configuration for entity ApplicationUser -/// -public class ProfilesMapperConfiguration : Profile -{ - /// - public ProfilesMapperConfiguration() - => CreateMap() - .ForMember(x => x.Id, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Name))) - .ForMember(x => x.PositionName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Actor))) - .ForMember(x => x.FirstName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.GivenName))) - .ForMember(x => x.LastName, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Surname))) - .ForMember(x => x.Roles, o => o.MapFrom(claims => ClaimsHelper.GetValues(claims, ClaimTypes.Role))) - .ForMember(x => x.Email, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.Name))) - .ForMember(x => x.PhoneNumber, o => o.MapFrom(claims => ClaimsHelper.GetValue(claims, ClaimTypes.MobilePhone))); -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/GetRoles.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/GetRoles.cs deleted file mode 100644 index e6a4671a..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/QUERIES/GetRoles.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Calabonga.Microservices.Core; -using MediatR; -using System.Security.Claims; - -namespace $safeprojectname$.Endpoints.ProfileEndpoints.Queries; - -/// -/// Request: Returns user roles -/// -public class GetProfile -{ - public record Request : IRequest; - - public class Handler : IRequestHandler - { - private readonly ILogger _logger; - private readonly IHttpContextAccessor _httpContextAccessor; - - public Handler( - ILogger logger, - IHttpContextAccessor httpContextAccessor) - { - _logger = logger; - _httpContextAccessor = httpContextAccessor; - } - - public Task Handle(Request request, CancellationToken cancellationToken) - { - var user = _httpContextAccessor.HttpContext!.User; - var roles = ClaimsHelper.GetValues((ClaimsIdentity)user.Identity!, "role"); - var message = $"Current user ({user.Identity!.Name}) have following roles: {string.Join("|", roles)}"; - _logger.LogInformation(message); - return Task.FromResult(message); - } - } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/UserProfileViewModel.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/UserProfileViewModel.cs deleted file mode 100644 index f54b8bf5..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/ENDPOINTS/PROFILEENDPOINTS/VIEWMODELS/UserProfileViewModel.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace $safeprojectname$.Endpoints.ProfileEndpoints.ViewModels; - -/// -/// Application User Profile -/// -public class UserProfileViewModel -{ - /// - /// Identifier - /// - public Guid Id { get; set; } - - /// - /// FirstName - /// - public string FirstName { get; set; } = null!; - - /// - /// LastName - /// - public string LastName { get; set; } = null!; - - /// - /// Email - /// - public string Email { get; set; } = null!; - - /// - /// User Roles - /// - public List? Roles { get; set; } - - /// - /// User PhoneNumber - /// - public string? PhoneNumber { get; set; } - - /// - /// Position Name - /// - public string? PositionName { get; set; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/FeatureGroupNameAttribute.cs b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/FeatureGroupNameAttribute.cs deleted file mode 100644 index ff3f2d42..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/FeatureGroupNameAttribute.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace $safeprojectname$; - -/// -/// Swagger controller group attribute -/// -/// -[AttributeUsage(AttributeTargets.Method)] -public class FeatureGroupNameAttribute : Attribute -{ - /// - public FeatureGroupNameAttribute(string groupName) => GroupName = groupName; - - /// - /// Group name - /// - public string GroupName { get; } -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/MyTemplate.vstemplate b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/MyTemplate.vstemplate deleted file mode 100644 index 651e0059..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/MyTemplate.vstemplate +++ /dev/null @@ -1,116 +0,0 @@ - - - Calabonga.Microservice.Module.Web - Calabonga.Microservice.Module.Web - CSharp - - - 1000 - true - Calabonga.Microservice.Module.Web - true - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - launchSettings.json - - - ValidatorBehavior.cs - - - - CommonDefinition.cs - - - CorsDefinition.cs - - - DataSeedingDefinition.cs - - - DbContextDefinition.cs - - - ErrorHandlingDefinition.cs - - - ETagGeneratorDefinition.cs - - - FluentValidationDefinition.cs - - - AuthData.cs - AuthorizationDefinition.cs - UserIdentity.cs - - - AutomapperDefinition.cs - PagedListConverter.cs - - - - UnitOfWorkTransactionBehavior.cs - - LogPostTransaction.cs - MediatorDefinition.cs - - - AppPermissionHandler.cs - AuthorizationPolicyProvider.cs - OpenIddictDefinition.cs - PermissionRequirement.cs - - - SwaggerDefinition.cs - - - UnitOfWorkDefinition.cs - - - - - - DeleteEventItem.cs - GetEventItemById.cs - GetEventItemPaged.cs - PostEventItem.cs - UpdateEventItem.cs - - - EventItemCreateViewModel.cs - EventItemUpdateViewModel.cs - EventItemViewModel.cs - - EventItemEndpoints.cs - EventItemMapperConfiguration.cs - EventItemValidator.cs - - - - GetRoles.cs - - - UserProfileViewModel.cs - - ProfilesEndpoint.cs - ProfilesMapperConfiguration.cs - - - .editorconfig - vstg0001.editorconfig - appsettings.json - appsettings.Development.json - FeatureGroupNameAttribute.cs - Program.cs - readme.md - tempkey.jwk - - - \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/__PreviewImage.png b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/__PreviewImage.png deleted file mode 100644 index a75ffa16..00000000 Binary files a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/__TemplateIcon.png b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/appsettings.Development.json b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/appsettings.Development.json deleted file mode 100644 index df234793..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/appsettings.Development.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "ConnectionStrings": { - "ApplicationDbContext": "Server=;Database=;User ID=;Password=" - }, - "Cors": { - "Origins": "*" - }, - "Serilog": { - "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], - "MinimumLevel": { - "Default": "Debug", - "Override": { - "Microsoft": "Warning", - "System": "Warning", - "OpenIddict": "Warning" - } - }, - "WriteTo": [ - { "Name": "Console" }, - { - "Name": "File", - "Args": { - "path": "/logs/log-.log", - "rollingInterval": "Day", - "rollOnFileSizeLimit": true, - "shared": true, - "formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact" - } - } - ], - "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ] - } -} diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/appsettings.json b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/appsettings.json deleted file mode 100644 index 8156fca3..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/appsettings.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "Serilog": { - "Using": [ "Serilog.Sinks.Console" ], - "MinimumLevel": { - "Default": "Information", - "Override": { - "Microsoft": "Warning", - "System": "Warning" - } - }, - "WriteTo": [ - { "Name": "Console" } - ], - "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ] - }, - "AuthServer": { - "Url": "https://localhost:10001" - }, - "AllowedHosts": "*" -} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/readme.md b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/readme.md deleted file mode 100644 index 68a16080..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/readme.md +++ /dev/null @@ -1,29 +0,0 @@ -# Attentions - -Please find out all comments with 'ATTENTION!' because that is required some decisions from you - -# About - -| Name | Description | -| ------------ | ------------------------------------------ | -| Name | Microservice Template for ASP.NET Core API | -| Author | Calabonga SOFT © 2005-2023 Calabonga SOFT | -| Created Date | 2019-04-19 | - -# Versions - -Nimble Framework Templates build on .NET 7.0. That`s why it have the same major version. But the all improvements will increment minor versions. - -# Contacts - -You can contact me by using the next opportunities: - -* Donate: https://boosty.to/calabonga/donate -* Blog: https://www.calabonga.net -* GitHub: https://github.com/Calabonga -* Zen: https://dzen.ru/calabonga -* YouTube: https://youtube.com/sergeicalabonga - -# Description: - -This template implements Web API functionality using minmal API feature from NET 7.0 \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/tempkey.jwk b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/tempkey.jwk deleted file mode 100644 index 54a03371..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/tempkey.jwk +++ /dev/null @@ -1 +0,0 @@ -{"alg":"RS256","d":"P7dPY7Wy3wuD_Vls0NBNsrY_j5o70JJk0beTptSFEspyvBlFSpG3wLSqWBqnbZzRmEWJ12Kdn8BgMiB8kzUQk3JjA16o6_USGLCKCnNkWBya4xJ0Yh63YjIVltMNHclsep70NjoTbI8G3UjOUXtKGYyqcC_FSWfmkPugVv7eQwWOasP60sXExfmGHQ5EV8NkVc4VBIkhEGolpVaUbISWg1Gf_CTj_iwm1FzosoUB6dlrQ-CAcYQT0gCRXeP85cnxUrfXQrExyzGC5ablHj9IBMWrUW9KmUqG42gvbuUmkv-0GolHj0DivQjJRMvOhmYzfw-FVly64cSQdYjrdVyiEQ","dp":"vaf7y9sBxE33PlS87g-5besW6OcDYmbL2fHc1Jaqp_tudjk3KE2g608qz18EFNxhduf7n7ACpTCLTLzqYgubGrzvgFWhqJhh2Ts2aEC_EWAnTTyzgq3F6_AwNlpsLYw-FDWU7lLRjgeYu2ZRJcQ1LtrFcBf8lv7EORfGcZ7zeh0","dq":"1mMVHzMx-LnIbaAFht5nce0-8pLj1zf25Jzghlm8Wgi0FAGI8b8V3edbVSJo1V8JdI_we4HjsmC3RA686Z1NsSXIaUxel44GdZXIYAiZA3N30gs5mT07MUPrglPeNm6LMYeYn5fsTk12TSIWTUMTmyW5BNvHTVQjH0dk7maJWzU","e":"AQAB","kid":"72F4E7F8D19F17C0FC47D7CF1FBF61DF","kty":"RSA","n":"sf6uR2CqoZHzcEex5KT54OC6iAd1I-dELjp16-xmkSuqWGOIyyFqqQ5kyxvMlayfSUbdcLTCswaAyomnbu3tUuvccgdhO_7BsFN8eaosYqgUmUP0htI6lirysnFxRxaA-4qozXrNTxMcoxF0hgTtgIg6R8hdKMfpOZi90D1XGZUsNe9GjRLDZZVssM-idookwqTeMmLKLGUZiQwOTc9QOplHYbL52turG3kSTjoOVrrCM1szm9j5VSfmXAug3QJXZe0x0twfBhym8rEljsgr4IopNe8RA4Msg6uZFHCc4rCRXd5xajlSug4g8r_lq0M64Ug4nzIe1kfpMjY8nHnr2Q","p":"0rSFb90z1tu6BxUUQuL3DwJNu6YrSCTunkkgq943YuTV1XO2KXTW1mZbbD_KnvUMRz9CDsnFts-8W6fh7g8-_zFnhnDS7_XoYa7Yf2Aw9hN2VTKGuDNZo9Vidj4jbejXddbY2L3n0qD_iR9PIXuDM_at9zj7xMk88A5NPFY57mM","q":"2EINjDxepSzyh6BPltt3iqExQrtgseUermliIjHc8kSx_j25azscTZC3MYU6hy7AMISqXBoAsc2GCyKfhQpcNlOWXYeRn-QgYzea5kog8OEM1-hneTzhCAbb8IUm7l_JZ11Se423OVKBA9bgg7yj8K94Hid3ayJOTIe4Rzjvo5M","qi":"pst6tRwkUiKMpWSJ2aMp2jsf_14s96c_bzOMoJUgk3T2LjOJ6TTXYW8uyYm76RXJALBbows73rk9sMaohv08MjXT_QCBCDHQGwb1cH07j2aXslkq-pjO7J8vOUvBhc4ZSWzqmyQEqLOC76N_vem1j39w_eu12TbFncQYitmEtBs"} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/vstg0001.editorconfig b/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/vstg0001.editorconfig deleted file mode 100644 index ad6bdfaf..00000000 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/vstg0001.editorconfig +++ /dev/null @@ -1,228 +0,0 @@ -root = true -# Remove the line below if you want to inherit .editorconfig settings from higher directories - -# C# files -[*.cs] - -#### Core EditorConfig Options #### -charset = utf-8-bom - -# Indentation and spacing -indent_size = 4 -indent_style = space -tab_width = 4 - -# New line preferences -end_of_line = crlf -insert_final_newline = false - -#### .NET Coding Conventions #### - -# Organize usings -dotnet_separate_import_directive_groups = false -dotnet_sort_system_directives_first = false - -# this. and Me. preferences -dotnet_style_qualification_for_event = false:suggestion -dotnet_style_qualification_for_field = false -dotnet_style_qualification_for_method = false:suggestion -dotnet_style_qualification_for_property = false:suggestion - -# Language keywords vs BCL types preferences -dotnet_style_predefined_type_for_locals_parameters_members = true -dotnet_style_predefined_type_for_member_access = true - -# Parentheses preferences -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity -dotnet_style_parentheses_in_other_operators = never_if_unnecessary -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity - -# Modifier preferences -dotnet_style_require_accessibility_modifiers = for_non_interface_members - -# Expression-level preferences -dotnet_style_coalesce_expression = true -dotnet_style_collection_initializer = true -dotnet_style_explicit_tuple_names = true -dotnet_style_null_propagation = true -dotnet_style_object_initializer = true -dotnet_style_operator_placement_when_wrapping = beginning_of_line -dotnet_style_prefer_auto_properties = true:error -dotnet_style_prefer_compound_assignment = true -dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion -dotnet_style_prefer_conditional_expression_over_return = true:suggestion -dotnet_style_prefer_inferred_anonymous_type_member_names = true:error -dotnet_style_prefer_inferred_tuple_names = true -dotnet_style_prefer_is_null_check_over_reference_equality_method = true -dotnet_style_prefer_simplified_boolean_expressions = true -dotnet_style_prefer_simplified_interpolation = true - -# Field preferences -dotnet_style_readonly_field = true:error - -# Parameter preferences -dotnet_code_quality_unused_parameters = all - -# Suppression preferences -dotnet_remove_unnecessary_suppression_exclusions = none - -#### C# Coding Conventions #### - -# var preferences -csharp_style_var_elsewhere = true:suggestion -csharp_style_var_for_built_in_types = true:suggestion -csharp_style_var_when_type_is_apparent = true:suggestion - -# Expression-bodied members -csharp_style_expression_bodied_accessors = true:suggestion -csharp_style_expression_bodied_constructors = true:suggestion -csharp_style_expression_bodied_indexers = true:suggestion -csharp_style_expression_bodied_lambdas = true -csharp_style_expression_bodied_local_functions = false -csharp_style_expression_bodied_methods = true:suggestion -csharp_style_expression_bodied_operators = true:suggestion -csharp_style_expression_bodied_properties = true:suggestion - -# Pattern matching preferences -csharp_style_pattern_matching_over_as_with_null_check = true -csharp_style_pattern_matching_over_is_with_cast_check = true -csharp_style_prefer_not_pattern = true -csharp_style_prefer_pattern_matching = true -csharp_style_prefer_switch_expression = true - -# Null-checking preferences -csharp_style_conditional_delegate_call = true - -# Modifier preferences -csharp_prefer_static_local_function = true -csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async - -# Code-block preferences -csharp_prefer_braces = true:error -csharp_prefer_simple_using_statement = true - -# Expression-level preferences -csharp_prefer_simple_default_expression = true -csharp_style_deconstructed_variable_declaration = true -csharp_style_implicit_object_creation_when_type_is_apparent = true -csharp_style_inlined_variable_declaration = true -csharp_style_pattern_local_over_anonymous_function = true -csharp_style_prefer_index_operator = true -csharp_style_prefer_range_operator = true -csharp_style_throw_expression = true -csharp_style_unused_value_assignment_preference = discard_variable -csharp_style_unused_value_expression_statement_preference = discard_variable - -# 'using' directive preferences -csharp_using_directive_placement = outside_namespace - -#### C# Formatting Rules #### - -# New line preferences -csharp_new_line_before_catch = true -csharp_new_line_before_else = true -csharp_new_line_before_finally = true -csharp_new_line_before_members_in_anonymous_types = true -csharp_new_line_before_members_in_object_initializers = true -csharp_new_line_before_open_brace = all -csharp_new_line_between_query_expression_clauses = true - -# Indentation preferences -csharp_indent_block_contents = true -csharp_indent_braces = false -csharp_indent_case_contents = true -csharp_indent_case_contents_when_block = true -csharp_indent_labels = no_change -csharp_indent_switch_labels = true - -# Space preferences -csharp_space_after_cast = false -csharp_space_after_colon_in_inheritance_clause = true -csharp_space_after_comma = true -csharp_space_after_dot = false -csharp_space_after_keywords_in_control_flow_statements = true -csharp_space_after_semicolon_in_for_statement = true -csharp_space_around_binary_operators = before_and_after -csharp_space_around_declaration_statements = false -csharp_space_before_colon_in_inheritance_clause = true -csharp_space_before_comma = false -csharp_space_before_dot = false -csharp_space_before_open_square_brackets = false -csharp_space_before_semicolon_in_for_statement = false -csharp_space_between_empty_square_brackets = false -csharp_space_between_method_call_empty_parameter_list_parentheses = false -csharp_space_between_method_call_name_and_opening_parenthesis = false -csharp_space_between_method_call_parameter_list_parentheses = false -csharp_space_between_method_declaration_empty_parameter_list_parentheses = false -csharp_space_between_method_declaration_name_and_open_parenthesis = false -csharp_space_between_method_declaration_parameter_list_parentheses = false -csharp_space_between_parentheses = false -csharp_space_between_square_brackets = false - -# Wrapping preferences -csharp_preserve_single_line_blocks = true -csharp_preserve_single_line_statements = true - -#### Naming styles #### - -# Naming rules - -dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion -dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface -dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i - -dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.types_should_be_pascal_case.symbols = types -dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case - -dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion -dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members -dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case - -# Symbol specifications - -dotnet_naming_symbols.interface.applicable_kinds = interface -dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.interface.required_modifiers = - -dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum -dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.types.required_modifiers = - -dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method -dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected -dotnet_naming_symbols.non_field_members.required_modifiers = - -# Naming styles - -dotnet_naming_style.pascal_case.required_prefix = -dotnet_naming_style.pascal_case.required_suffix = -dotnet_naming_style.pascal_case.word_separator = -dotnet_naming_style.pascal_case.capitalization = pascal_case - -dotnet_naming_style.begins_with_i.required_prefix = I -dotnet_naming_style.begins_with_i.required_suffix = -dotnet_naming_style.begins_with_i.word_separator = -dotnet_naming_style.begins_with_i.capitalization = pascal_case - -# Instance fields are camelCase and start with _ -dotnet_naming_rule.instance_fields_should_be_camel_case.severity = hint -dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields -dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style - -dotnet_naming_symbols.instance_fields.applicable_kinds = field - -dotnet_naming_style.instance_field_style.capitalization = camel_case -dotnet_naming_style.instance_field_style.required_prefix = _ - -# ReSharper properties -max_line_length = 200 -resharper_csharp_max_line_length = 200 -resharper_csharp_wrap_after_declaration_lpar = true -resharper_csharp_wrap_extends_list_style = chop_if_long -resharper_csharp_wrap_lines = false -resharper_max_attribute_length_for_same_line = 300 -resharper_place_type_constraints_on_same_line = true -resharper_wrap_before_arrow_with_expressions = true -resharper_wrap_before_extends_colon = false \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Root.vstemplate b/AspNetCore v7.0/TemplateModule/Root.vstemplate deleted file mode 100644 index d4fedaf7..00000000 --- a/AspNetCore v7.0/TemplateModule/Root.vstemplate +++ /dev/null @@ -1,25 +0,0 @@ - - - Microservice API Template - Nimble microservice template. This template gives you a possibility to start developing a microservices system with integrated Swagger, Mediatr, Automapper and other things. This template is using minimal API feature from .NET 7.0. That's why we implement a Vertical Slice Architecture approach used (Folding by Features) - CSharp - true - Calabonga.Microservice.Module - Enabled - true - true - __TemplateIcon.png - __PreviewImage.png - - - - - - - Calabonga.Microservice.Module.Web\MyTemplate.vstemplate - Calabonga.Microservice.Module.Domain\MyTemplate.vstemplate - Calabonga.Microservice.Module.Infrastructure\MyTemplate.vstemplate - - - \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/__PreviewImage.png b/AspNetCore v7.0/TemplateModule/__PreviewImage.png deleted file mode 100644 index a75ffa16..00000000 Binary files a/AspNetCore v7.0/TemplateModule/__PreviewImage.png and /dev/null differ diff --git a/AspNetCore v7.0/TemplateModule/__TemplateIcon.png b/AspNetCore v7.0/TemplateModule/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/AspNetCore v7.0/TemplateModule/__TemplateIcon.png and /dev/null differ diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.csproj b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.csproj similarity index 83% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.csproj rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.csproj index a22e7955..2a3da2a4 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.csproj +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.csproj @@ -4,20 +4,20 @@ Calabonga.Microservice.IdentityModule.Template - 7.0.8 + 8.0.6 Microservice template with OpenIddict Calabonga - Calabonga © 2016-2023 + Calabonga SOFT © 2001 - $([System.DateTime]::Now.ToString(yyyy)) logo.png - Microservice template with OpenIddict implementation for OAuth2.0 and also with Automapper, FluentValidation and other helpful thing - template, microservice, oauth2, calabonga, nimble, framework + Microservice template on Minimal API with OpenIddict implementation for OAuth2.0 and also with Automapper, FluentValidation and other helpful thing + template, microservice, oauth2, calabonga, nimble, framework, minimal, api https://github.com/Calabonga/Microservice-Template MIT - Big nullable supporting added + Nugets versions bumped Template - net7.0 + net8.0 true false content diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.sln b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.sln similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.sln rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/Calabonga.Microservice.IdentityModule.Template.sln diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/README.md b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/README.md similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/README.md rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/README.md diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/.editorconfig b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/.editorconfig similarity index 99% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/.editorconfig rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/.editorconfig index a6b70db4..ba57c383 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/.editorconfig +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/.editorconfig @@ -19,7 +19,7 @@ tab_width = 4 # New line preferences end_of_line = crlf -insert_final_newline = false +insert_final_newline = true #### .NET Coding Conventions #### diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/.template.config/template.json b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/.template.config/template.json similarity index 71% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/.template.config/template.json rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/.template.config/template.json index b8aea5a9..1abe1bff 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/.template.config/template.json +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/.template.config/template.json @@ -4,15 +4,15 @@ "classifications": [ "Common", "Web", - "WebAPI" + "Web API" ], "name": "Microservice template with OpenIddict", - "description": "Nimble Microservice Framework. This template gives you a possibility to start developing a microservice architecture with integrated UI (Swagger), Mediatr, Automapper and Authorization Server (OpenIddict OAuth 2.0). Template developed for .NET 7.0.x.", + "description": "Microservice Template. Nimble Framework based on Minimal API (.NET9). This template gives you a possibility to start developing a microservice architecture with OpenIddict (OAuth2.0) and integrated other helpful things like a UI (Scalar), Mediatr, Automapper, Serilog, etc.", "identity": "Calabonga.Microservice.IdentityModule", "shortName": "microservice-oidd", "tags": { "language": "C#", - "type": "project" + "type": "solution" }, "sourceName": "Calabonga.Microservice.IdentityModule", "preferNameDirectory": true, @@ -23,10 +23,10 @@ "datatype": "choice", "choices": [ { - "choice": "net7.0" + "choice": "net9.0" } ], - "defaultValue": "net7.0" + "defaultValue": "net9.0" } }, "sources": [ diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule..sln b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule..sln similarity index 91% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule..sln rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule..sln index 750ebbf6..0e62f944 100644 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule..sln +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule..sln @@ -9,11 +9,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.Iden EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.IdentityModule.Infrastructure", "Calabonga.Microservice.IdentityModule.Infrastructure\Calabonga.Microservice.IdentityModule.Infrastructure.csproj", "{6B046F2A-2EE0-413D-859E-1D4CD30D066A}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{6FB183A6-17FD-4AF0-B653-09A8FD1F6765}" - ProjectSection(SolutionItems) = preProject - .editorconfig = .editorconfig - EndProjectSection -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Common.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Common.cs similarity index 83% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Common.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Common.cs index a88a590b..85075880 100644 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Common.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Common.cs @@ -17,9 +17,14 @@ public static partial class AppData public const string ServiceDescription = "Nimble Framework Microservice Template with integrated OpenIddict for OpenID Connect server and Token Validation"; /// - /// Default policy name + /// Default policy name for CORS /// - public const string PolicyName = "CorsPolicy"; + public const string PolicyCorsName = "CorsPolicy"; + + /// + /// Default policy name for API + /// + public const string PolicyDefaultName = "DefaultPolicy"; /// /// "SystemAdministrator" diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Exceptions.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Exceptions.cs similarity index 86% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Exceptions.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Exceptions.cs index 325bc88a..f8e4f7fc 100644 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Exceptions.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Exceptions.cs @@ -56,5 +56,15 @@ public static class Exceptions /// "Argument out of range" /// public static string ArgumentOutOfRangeException => "Argument out of range"; + + /// + /// "Mapping failed" + /// + public static string MappingException => "Mapping failed"; + + /// + /// "Something went wrong" + /// + public static string SomethingWrong => "Something went wrong"; } } \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Messages.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Messages.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Messages.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/AppData.Messages.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Auditable.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Auditable.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Auditable.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Auditable.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IAuditable.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IAuditable.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IAuditable.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IAuditable.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/IHaveId.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IHaveId.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/IHaveId.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IHaveId.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/IViewModel.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IViewModel.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/IViewModel.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/IViewModel.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/Identity.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Identity.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/Identity.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Identity.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/NamedAuditable.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/NamedAuditable.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/NamedAuditable.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/NamedAuditable.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/NamedIdentity.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/NamedIdentity.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/NamedIdentity.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/NamedIdentity.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/Sortable.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Sortable.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/Sortable.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/Sortable.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/TypeHelper.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/TypeHelper.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/TypeHelper.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/TypeHelper.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/ViewModelBase.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/ViewModelBase.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/Base/ViewModelBase.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Base/ViewModelBase.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj similarity index 52% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj index 5a6d1162..b9b3d6b3 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/Calabonga.Microservice.IdentityModule.Domain.csproj @@ -1,11 +1,10 @@  - net7.0 + net9.0 enable enable - true - enable + false diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/EventItem.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/EventItem.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Domain/EventItem.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Domain/EventItem.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/AppPermission.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/AppPermission.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/AppPermission.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/AppPermission.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs similarity index 88% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs index 4133ecd4..d8a04d26 100644 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationDbContext.cs @@ -1,11 +1,11 @@ -using Calabonga.Microservice.IdentityModule.Domain; +#nullable disable + +using Calabonga.Microservice.IdentityModule.Domain; using Calabonga.Microservice.IdentityModule.Infrastructure.Base; using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Design; using Microsoft.EntityFrameworkCore.Diagnostics; namespace Calabonga.Microservice.IdentityModule.Infrastructure; - /// /// Database context for current application /// @@ -43,7 +43,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) // public ApplicationDbContext CreateDbContext(string[] args) // { // var optionsBuilder = new DbContextOptionsBuilder(); -// optionsBuilder.UseSqlServer("Server=;Database=;User ID=;Password="); +// optionsBuilder.UseNpgsql("Server=;Database=;User ID=;Password="); // return new ApplicationDbContext(optionsBuilder.Options); // } -//} \ No newline at end of file +//} + +#nullable restore \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRole.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRole.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRole.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRole.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRoleStore.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRoleStore.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRoleStore.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationRoleStore.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUser.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUser.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUser.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUser.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserProfile.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserProfile.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserProfile.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserProfile.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserStore.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserStore.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserStore.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/ApplicationUserStore.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/Base/DbContextBase.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/Base/DbContextBase.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/Base/DbContextBase.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/Base/DbContextBase.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj similarity index 66% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj index a8730db9..dd017515 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/Calabonga.Microservice.IdentityModule.Infrastructure.csproj @@ -1,26 +1,24 @@  - net7.0 + net9.0 enable enable - true - enable + false - - - + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + - - - + + diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs similarity index 96% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs index ab546d7e..7e7bf8db 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs @@ -72,8 +72,8 @@ public static async void SeedUsers(IServiceProvider serviceProvider) { CreatedAt = DateTime.Now, CreatedBy = "SEED", - PolicyName = "EventItems:UserRoles:View", - Description = "Access policy for EventItems controller user view" + PolicyName = "Profiles:Roles:Get", + Description = "Access policy for view Roles in user Profiles" } } } @@ -141,5 +141,7 @@ await context.EventItems.AddAsync(new EventItem Logger = "SEED", Message = "Seed method some entities successfully save to ApplicationDbContext" }); + + await context.SaveChangesAsync(); } } \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/EventItemMapperConfiguration.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/EventItemMapperConfiguration.cs similarity index 91% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/EventItemMapperConfiguration.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/EventItemMapperConfiguration.cs index 63a50ccb..263ba83d 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/EventItemMapperConfiguration.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/EventItemMapperConfiguration.cs @@ -1,10 +1,10 @@ using AutoMapper; using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.ViewModels; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.ViewModels; using Calabonga.Microservice.IdentityModule.Web.Definitions.Mapping; -using Calabonga.UnitOfWork; +using Calabonga.PagedListCore; -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages; +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages; /// /// Mapper Configuration for entity EventItem diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/EventItemValidator.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/EventItemValidator.cs similarity index 92% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/EventItemValidator.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/EventItemValidator.cs index ddef9051..f828fb88 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/EventItemValidator.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/EventItemValidator.cs @@ -1,7 +1,7 @@ -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.Queries; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.Queries; using FluentValidation; -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages; +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages; /// /// RegisterViewModel Validator diff --git a/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/DeleteEventItem.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/DeleteEventItem.cs new file mode 100644 index 00000000..751b73c6 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/DeleteEventItem.cs @@ -0,0 +1,51 @@ +using AutoMapper; +using Calabonga.Microservice.IdentityModule.Domain; +using Calabonga.Microservice.IdentityModule.Domain.Base; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.ViewModels; +using Calabonga.OperationResults; +using Calabonga.UnitOfWork; +using MediatR; + +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.Queries; + +/// +/// EventItem delete +/// +public sealed class DeleteEventItem +{ + public record Request(Guid Id) : IRequest>; + + public class Handler(IUnitOfWork unitOfWork, IMapper mapper) + : IRequestHandler> + { + /// Handles a request + /// The request + /// Cancellation token + /// Response from the request + public async Task> Handle(Request request, CancellationToken cancellationToken) + { + var repository = unitOfWork.GetRepository(); + var entity = await repository.FindAsync(request.Id); + if (entity == null) + { + return Operation.Error("Entity not found"); + } + + repository.Delete(entity); + await unitOfWork.SaveChangesAsync(); + if (!unitOfWork.LastSaveChangesResult.IsOk) + { + return Operation.Error(unitOfWork.LastSaveChangesResult.Exception?.Message ?? AppData.Exceptions.SomethingWrong); + } + + var mapped = mapper.Map(entity); + if (mapped is not null) + { + return Operation.Result(mapped); + } + + return Operation.Error(AppData.Exceptions.MappingException); + + } + } +} \ No newline at end of file diff --git a/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemById.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemById.cs new file mode 100644 index 00000000..d140acdb --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemById.cs @@ -0,0 +1,44 @@ +using AutoMapper; +using Calabonga.Microservice.IdentityModule.Domain; +using Calabonga.Microservice.IdentityModule.Domain.Base; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.ViewModels; +using Calabonga.OperationResults; +using Calabonga.UnitOfWork; +using MediatR; + +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.Queries; + +/// +/// EventItem by Identifier +/// +public sealed class GetEventItemById +{ + public record Request(Guid Id) : IRequest>; + + public class Handler(IUnitOfWork unitOfWork, IMapper mapper) + : IRequestHandler> + { + /// Handles a request getting log by identifier + /// The request + /// Cancellation token + /// Response from the request + public async Task> Handle(Request request, CancellationToken cancellationToken) + { + var id = request.Id; + var repository = unitOfWork.GetRepository(); + var entityWithoutIncludes = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == id, trackingType: TrackingType.NoTracking); + if (entityWithoutIncludes == null) + { + return Operation.Error($"Entity with identifier {id} not found"); + } + + var mapped = mapper.Map(entityWithoutIncludes); + if (mapped is not null) + { + return Operation.Result(mapped); + } + + return Operation.Error(AppData.Exceptions.MappingException); + } + } +} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemPaged.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemPaged.cs similarity index 55% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemPaged.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemPaged.cs index ad26306b..36010a99 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemPaged.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemPaged.cs @@ -1,62 +1,56 @@ using AutoMapper; using Calabonga.Microservice.IdentityModule.Domain; -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.ViewModels; +using Calabonga.Microservice.IdentityModule.Domain.Base; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.ViewModels; using Calabonga.OperationResults; +using Calabonga.PagedListCore; using Calabonga.PredicatesBuilder; using Calabonga.UnitOfWork; using MediatR; using System.Linq.Expressions; -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.Queries; +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.Queries; /// /// Request for paged list of EventItems /// -public class GetEventItemPaged +public sealed class GetEventItemPaged { - public record Request(int PageIndex, int PageSize, string? Search) : IRequest>>; + public record Request(int PageIndex, int PageSize, string? Search) : IRequest, string>>; - public class Handler : IRequestHandler>> + public class Handler(IUnitOfWork unitOfWork, IMapper mapper) + : IRequestHandler, string>> { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task>> Handle( + public async Task, string>> Handle( Request request, CancellationToken cancellationToken) { - var operation = OperationResult.CreateResult>(); var predicate = GetPredicate(request.Search); - var pagedList = await _unitOfWork.GetRepository() + var pagedList = await unitOfWork.GetRepository() .GetPagedListAsync( predicate: predicate, pageIndex: request.PageIndex, pageSize: request.PageSize, + trackingType: TrackingType.NoTracking, cancellationToken: cancellationToken); - if (pagedList == null) - { - operation.Result = PagedList.Empty(); - operation.AddWarning("Response does not return the result for pagination."); - return operation; - } - if (pagedList.PageIndex > pagedList.TotalPages) { - pagedList = await _unitOfWork.GetRepository() + pagedList = await unitOfWork.GetRepository() .GetPagedListAsync( pageIndex: 0, - pageSize: request.PageSize, cancellationToken: cancellationToken); + pageSize: request.PageSize, + trackingType: TrackingType.NoTracking, + cancellationToken: cancellationToken); + } + + var mapped = mapper.Map>(pagedList); + if (mapped is not null) + { + return Operation.Result(mapped); } - operation.Result = _mapper.Map>(pagedList); - return operation; + return Operation.Error(AppData.Exceptions.MappingException); } private Expression> GetPredicate(string? search) diff --git a/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/PostEventItem.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/PostEventItem.cs new file mode 100644 index 00000000..a35f727f --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/PostEventItem.cs @@ -0,0 +1,54 @@ +using AutoMapper; +using Calabonga.Microservice.IdentityModule.Domain; +using Calabonga.Microservice.IdentityModule.Domain.Base; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.ViewModels; +using Calabonga.Microservices.Core; +using Calabonga.OperationResults; +using Calabonga.UnitOfWork; +using MediatR; + +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.Queries; + +/// +/// Request: EventItem creation +/// +public sealed class PostEventItem +{ + public record Request(EventItemCreateViewModel Model) : IRequest>; + + public class Handler(IUnitOfWork unitOfWork, IMapper mapper, ILogger logger) + : IRequestHandler> + { + public async Task> Handle(Request eventItemRequest, CancellationToken cancellationToken) + { + logger.LogDebug("Creating new EventItem"); + + var entity = mapper.Map(eventItemRequest.Model); + if (entity == null) + { + logger.LogError("Mapper not configured correctly or something went wrong"); + return Operation.Error(AppContracts.Exceptions.MappingException); + } + + await unitOfWork.GetRepository().InsertAsync(entity, cancellationToken); + await unitOfWork.SaveChangesAsync(); + + var lastResult = unitOfWork.LastSaveChangesResult; + if (lastResult.IsOk) + { + var mapped = mapper.Map(entity); + if (mapped is not null) + { + logger.LogInformation("New entity {@EventItem} successfully created", entity); + return Operation.Result(mapped); + } + + return Operation.Error(AppData.Exceptions.MappingException); + } + + var errorMessage = lastResult.Exception?.Message ?? "Something went wrong"; + logger.LogError(errorMessage); + return Operation.Error(errorMessage); + } + } +} \ No newline at end of file diff --git a/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/UpdateEventItem.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/UpdateEventItem.cs new file mode 100644 index 00000000..bfc05828 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/Queries/UpdateEventItem.cs @@ -0,0 +1,52 @@ +using AutoMapper; +using Calabonga.Microservice.IdentityModule.Domain; +using Calabonga.Microservice.IdentityModule.Domain.Base; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.ViewModels; +using Calabonga.Microservices.Core; +using Calabonga.OperationResults; +using Calabonga.UnitOfWork; +using MediatR; + +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.Queries; + +/// +/// Request: EventItem edit +/// +public sealed class PutEventItem +{ + public record Request(Guid Id, EventItemUpdateViewModel Model) : IRequest>; + + public class Handler(IUnitOfWork unitOfWork, IMapper mapper) + : IRequestHandler> + { + public async Task> Handle(Request eventItemRequest, CancellationToken cancellationToken) + { + var repository = unitOfWork.GetRepository(); + var entity = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == eventItemRequest.Id, disableTracking: false); + if (entity == null) + { + return Operation.Error(AppContracts.Exceptions.NotFoundException); + } + + mapper.Map(eventItemRequest.Model, entity); + + repository.Update(entity); + await unitOfWork.SaveChangesAsync(); + + var lastResult = unitOfWork.LastSaveChangesResult; + if (lastResult.IsOk) + { + var mapped = mapper.Map(entity); + if (mapped is not null) + { + return Operation.Result(mapped); + } + + return Operation.Error(AppData.Exceptions.MappingException); + } + + var errorMessage = lastResult.Exception?.Message ?? "Something went wrong"; + return Operation.Error(errorMessage); + } + } +} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemCreateViewModel.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemCreateViewModel.cs similarity index 95% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemCreateViewModel.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemCreateViewModel.cs index 3b2dcd7f..e295d8d7 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemCreateViewModel.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemCreateViewModel.cs @@ -1,7 +1,6 @@ using Calabonga.Microservice.IdentityModule.Domain.Base; -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.ViewModels; - +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.ViewModels; public class EventItemCreateViewModel : IViewModel { diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemUpdateViewModel.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemUpdateViewModel.cs similarity index 88% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemUpdateViewModel.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemUpdateViewModel.cs index 844a73bf..c99dd794 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemUpdateViewModel.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemUpdateViewModel.cs @@ -1,6 +1,6 @@ using Calabonga.Microservice.IdentityModule.Domain.Base; -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.ViewModels; +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.ViewModels; public class EventItemUpdateViewModel : ViewModelBase { diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemViewModel.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemViewModel.cs similarity index 90% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemViewModel.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemViewModel.cs index 49fa45ba..0b412393 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemViewModel.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemViewModel.cs @@ -1,4 +1,4 @@ -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.ViewModels; +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.ViewModels; public class EventItemViewModel { diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ProfilesMapperConfiguration.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ProfilesMapperConfiguration.cs similarity index 95% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ProfilesMapperConfiguration.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ProfilesMapperConfiguration.cs index a995b0c0..5f7335ec 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ProfilesMapperConfiguration.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ProfilesMapperConfiguration.cs @@ -1,15 +1,15 @@ using AutoMapper; using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileEndpoints.ViewModels; -using Calabonga.Microservices.Core; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileMessages.ViewModels; +using Calabonga.Utils.Extensions; using System.Security.Claims; -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileEndpoints; +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileMessages; /// /// Mapper Configuration for entity ApplicationUser /// -public class ProfilesMapperConfiguration : Profile +public sealed class ProfilesMapperConfiguration : Profile { /// public ProfilesMapperConfiguration() diff --git a/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/Queries/GetRoles.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/Queries/GetRoles.cs new file mode 100644 index 00000000..fe1fb6fa --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/Queries/GetRoles.cs @@ -0,0 +1,27 @@ +using Calabonga.Utils.Extensions; +using MediatR; +using System.Security.Claims; + +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileMessages.Queries; + +/// +/// Request: Returns user roles +/// +public sealed class GetProfile +{ + public record Request : IRequest; + + public class Handler(ILogger logger, IHttpContextAccessor httpContextAccessor) + : IRequestHandler + { + public Task Handle(Request request, CancellationToken cancellationToken) + { + var user = httpContextAccessor.HttpContext!.User; + var claims = user.FindAll(x => x.Type == ClaimTypes.Role); + var roles = ClaimsHelper.GetValues(new ClaimsIdentity(claims), ClaimTypes.Role); + var message = $"Current user ({user.Identity!.Name}) have following roles: {string.Join('|', roles)}"; + logger.LogInformation(message); + return Task.FromResult(message); + } + } +} \ No newline at end of file diff --git a/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/Queries/RegisterAccount.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/Queries/RegisterAccount.cs new file mode 100644 index 00000000..f6e9025c --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/Queries/RegisterAccount.cs @@ -0,0 +1,24 @@ +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileMessages.ViewModels; +using Calabonga.Microservice.IdentityModule.Web.Application.Services; +using Calabonga.OperationResults; +using MediatR; + +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileMessages.Queries; + +/// +/// Register new account +/// +public sealed class RegisterAccount +{ + public class Request(RegisterViewModel model) : IRequest> + { + public RegisterViewModel Model { get; } = model; + } + + public class Handler(IAccountService accountService) + : IRequestHandler> + { + public Task> Handle(Request request, CancellationToken cancellationToken) + => accountService.RegisterAsync(request.Model, cancellationToken); + } +} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ViewModels/RegisterViewModel.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ViewModels/RegisterViewModel.cs similarity index 97% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ViewModels/RegisterViewModel.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ViewModels/RegisterViewModel.cs index 281e62fd..c1331847 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ViewModels/RegisterViewModel.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ViewModels/RegisterViewModel.cs @@ -1,6 +1,6 @@ using System.ComponentModel.DataAnnotations; -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileEndpoints.ViewModels; +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileMessages.ViewModels; /// /// Data transfer object for user registration diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ViewModels/UserProfileViewModel.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ViewModels/UserProfileViewModel.cs similarity index 95% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ViewModels/UserProfileViewModel.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ViewModels/UserProfileViewModel.cs index b7134ac4..a2fdc7d2 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ViewModels/UserProfileViewModel.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Messaging/ProfileMessages/ViewModels/UserProfileViewModel.cs @@ -1,4 +1,4 @@ -namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileEndpoints.ViewModels; +namespace Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileMessages.ViewModels; /// /// Application User Profile diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Services/AccountService.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Services/AccountService.cs similarity index 86% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Services/AccountService.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Services/AccountService.cs index 16d955c6..04515266 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Services/AccountService.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Services/AccountService.cs @@ -1,13 +1,13 @@ using AutoMapper; using Calabonga.Microservice.IdentityModule.Domain.Base; using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileEndpoints.ViewModels; -using Calabonga.Microservice.IdentityModule.Web.Definitions.Identity; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileMessages.ViewModels; +using Calabonga.Microservice.IdentityModule.Web.Definitions.Authorizations; using Calabonga.Microservices.Core.Exceptions; -using Calabonga.Microservices.Core.Extensions; using Calabonga.Microservices.Core.Validators; using Calabonga.OperationResults; using Calabonga.UnitOfWork; +using Calabonga.Utils.Extensions; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.Extensions.Options; @@ -74,47 +74,46 @@ public Guid GetCurrentUserId() /// /// - public async Task> RegisterAsync(RegisterViewModel model, CancellationToken cancellationToken) + public async Task> RegisterAsync(RegisterViewModel model, CancellationToken cancellationToken) { - var operation = OperationResult.CreateResult(); var user = _mapper.Map(model); await using var transaction = await _unitOfWork.BeginTransactionAsync(); - var result = await _userManager.CreateAsync(user, model.Password); + var result = await _userManager.CreateAsync(user!, model.Password); const string role = AppData.ManagerRoleName; if (result.Succeeded) { if (await _roleManager.FindByNameAsync(role) == null) { - operation.Exception = new MicroserviceUserNotFoundException(); - operation.AddError(AppData.Exceptions.UserNotFoundException); - return await Task.FromResult(operation); + return await Task.FromResult(Operation.Error(AppData.Exceptions.UserNotFoundException)); } - await _userManager.AddToRoleAsync(user, role); + await _userManager.AddToRoleAsync(user!, role); var profile = _mapper.Map(model); var profileRepository = _unitOfWork.GetRepository(); - await profileRepository.InsertAsync(profile, cancellationToken); + await profileRepository.InsertAsync(profile!, cancellationToken); await _unitOfWork.SaveChangesAsync(); if (_unitOfWork.LastSaveChangesResult.IsOk) { - var principal = await _claimsFactory.CreateAsync(user); - operation.Result = _mapper.Map(principal.Identity); - operation.AddSuccess(AppData.Messages.UserSuccessfullyRegistered); - _logger.LogInformation(operation.GetMetadataMessages()); + var principal = await _claimsFactory.CreateAsync(user!); + var mapped = _mapper.Map(principal.Identity); await transaction.CommitAsync(cancellationToken); _logger.LogInformation("User {@User} successfully created with {@Role}", model, role); - return await Task.FromResult(operation); + if (mapped is not null) + { + return Operation.Result(mapped); + } + + return Operation.Error(AppData.Exceptions.MappingException); } } var errors = result.Errors.Select(x => $"{x.Code}: {x.Description}"); - operation.AddError(string.Join(", ", errors)); - operation.Exception = _unitOfWork.LastSaveChangesResult.Exception; + var errorMessage = string.Join(", ", errors); await transaction.RollbackAsync(cancellationToken); - _logger.LogError(operation.Exception, "User {@User} creation failed", model); - return await Task.FromResult(operation); + _logger.LogError("User {User} creation failed with {Errors}", model.Email, errorMessage); + return await Task.FromResult(Operation.Error(errorMessage)); } /// diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Services/IAccountService.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Services/IAccountService.cs similarity index 92% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Services/IAccountService.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Services/IAccountService.cs index e62c21e4..bc40d1a5 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Services/IAccountService.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Application/Services/IAccountService.cs @@ -1,5 +1,5 @@ using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileEndpoints.ViewModels; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileMessages.ViewModels; using Calabonga.Microservices.Core.Validators; using Calabonga.OperationResults; using System.Security.Claims; @@ -30,7 +30,7 @@ public interface IAccountService /// /// - Task> RegisterAsync(RegisterViewModel model, CancellationToken cancellationToken); + Task> RegisterAsync(RegisterViewModel model, CancellationToken cancellationToken); /// /// Returns User by user identifier diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj similarity index 56% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj index 5aca8efb..70fb2d08 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Calabonga.Microservice.IdentityModule.Web.csproj @@ -1,11 +1,10 @@  - net7.0 + net9.0 enable enable - true - enable + false @@ -16,24 +15,24 @@ - - - - - - - - - + + + + + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - + + + + + + diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/ApplicationUserClaimsPrincipalFactory.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Authorizations/ApplicationUserClaimsPrincipalFactory.cs similarity index 99% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/ApplicationUserClaimsPrincipalFactory.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Authorizations/ApplicationUserClaimsPrincipalFactory.cs index b188f1c0..d1e630c5 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/ApplicationUserClaimsPrincipalFactory.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Authorizations/ApplicationUserClaimsPrincipalFactory.cs @@ -3,7 +3,7 @@ using Microsoft.Extensions.Options; using System.Security.Claims; -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Identity; +namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Authorizations; /// /// User Claims Principal Factory override from Microsoft Identity framework diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/AuthorizationDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Authorizations/AuthorizationDefinition.cs similarity index 69% rename from AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/AuthorizationDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Authorizations/AuthorizationDefinition.cs index 199be974..5956f748 100644 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/IDENTITY/AuthorizationDefinition.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Authorizations/AuthorizationDefinition.cs @@ -1,13 +1,13 @@ using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Domain.Base; -using $safeprojectname$.Definitions.OpenIddict; +using Calabonga.Microservice.IdentityModule.Domain.Base; +using Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; +using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.IdentityModel.Tokens; -using OpenIddict.Server.AspNetCore; using System.Text.Json; -namespace $safeprojectname$.Definitions.Identity; +namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Authorizations; /// /// Authorization Policy registration @@ -15,22 +15,26 @@ namespace $safeprojectname$.Definitions.Identity; public class AuthorizationDefinition : AppDefinition { /// - /// Configure services for current microservice + /// Configure services for current application /// /// public override void ConfigureServices(WebApplicationBuilder builder) { - var url = builder.Configuration.GetSection("AuthServer").GetValue("Url"); - builder.Services .AddAuthentication(options => { - options.DefaultScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; - options.DefaultAuthenticateScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; + options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; + }) + .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => + { + options.LoginPath = "/connect/login"; }) - .AddJwtBearer(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme, "Bearer", options => + .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, "Bearer", options => { + var url = builder.Configuration.GetSection("AuthServer").GetValue("Url"); + options.SaveToken = true; options.Audience = "client-id-code"; options.Authority = url; @@ -63,7 +67,7 @@ public override void ConfigureServices(WebApplicationBuilder builder) if (context.AuthenticateFailure != null && context.AuthenticateFailure.GetType() == typeof(SecurityTokenExpiredException)) { var authenticationException = context.AuthenticateFailure as SecurityTokenExpiredException; - context.Response.Headers.Add("x-token-expired", authenticationException?.Expires.ToString("o")); + context.Response.Headers.Append("x-token-expired", authenticationException?.Expires.ToString("o")); context.ErrorDescription = $"The token expired on {authenticationException?.Expires:o}"; } @@ -78,11 +82,11 @@ public override void ConfigureServices(WebApplicationBuilder builder) builder.Services.AddAuthorization(options => { - options.AddPolicy(AuthData.AuthSchemes, policy => - { - policy.RequireAuthenticatedUser(); - policy.RequireClaim("scope", "api"); - }); + options.AddPolicy(AppData.PolicyDefaultName, x => + { + x.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, CookieAuthenticationDefaults.AuthenticationScheme); + x.RequireAuthenticatedUser(); + }); }); builder.Services.AddSingleton(); @@ -90,18 +94,19 @@ public override void ConfigureServices(WebApplicationBuilder builder) } /// - /// Configure application for current microservice + /// Configure application for current application /// /// - /// public override void ConfigureApplication(WebApplication app) { + app.UseHttpsRedirection(); app.UseRouting(); - app.UseCors(AppData.PolicyName); + app.UseCors(AppData.PolicyDefaultName); + app.UseCors(AppData.PolicyCorsName); app.UseAuthentication(); app.UseAuthorization(); // registering UserIdentity helper as singleton UserIdentity.Instance.Configure(app.Services.GetService()!); } -} \ No newline at end of file +} diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/UserIdentity.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Authorizations/UserIdentity.cs similarity index 87% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/UserIdentity.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Authorizations/UserIdentity.cs index dde93011..cbbf66d0 100644 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/Identity/UserIdentity.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Authorizations/UserIdentity.cs @@ -2,7 +2,7 @@ using System.Security.Claims; using System.Security.Principal; -namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Identity; +namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Authorizations; /// /// Identity helper for Requests operations @@ -36,16 +36,9 @@ public IIdentity? User } public IEnumerable Claims - { - get - { - if (User != null) - { - return ContextAccessor.HttpContext!.User.Claims; - } - return Enumerable.Empty(); - } - } + => User != null + ? ContextAccessor.HttpContext!.User.Claims + : Enumerable.Empty(); private static readonly Lazy Lazy = new Lazy(() => new UserIdentity()); diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Common/CommonDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Common/CommonDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Common/CommonDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Common/CommonDefinition.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Cors/CorsDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Cors/CorsDefinition.cs similarity index 88% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Cors/CorsDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Cors/CorsDefinition.cs index 14533c3f..715af8da 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Cors/CorsDefinition.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Cors/CorsDefinition.cs @@ -14,13 +14,14 @@ public class CorsDefinition : AppDefinition /// public override void ConfigureServices(WebApplicationBuilder builder) { - var origins = builder.Configuration.GetSection("Cors")?.GetSection("Origins")?.Value?.Split(','); + var origins = builder.Configuration.GetSection("Cors").GetSection("Origins").Value?.Split(','); builder.Services.AddCors(options => { - options.AddPolicy(AppData.PolicyName, policyBuilder => + options.AddPolicy(AppData.PolicyCorsName, policyBuilder => { policyBuilder.AllowAnyHeader(); policyBuilder.AllowAnyMethod(); + if (origins is not { Length: > 0 }) { return; @@ -43,4 +44,4 @@ public override void ConfigureServices(WebApplicationBuilder builder) }); }); } -} \ No newline at end of file +} diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/DataSeeding/DataSeedingDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DataSeeding/DataSeedingDefinition.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/DataSeeding/DataSeedingDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DataSeeding/DataSeedingDefinition.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DbContext/DbContextDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DbContext/DbContextDefinition.cs similarity index 89% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DbContext/DbContextDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DbContext/DbContextDefinition.cs index c6bfa0c6..8e9172f5 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DbContext/DbContextDefinition.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DbContext/DbContextDefinition.cs @@ -1,6 +1,6 @@ using Calabonga.AspNetCore.AppDefinitions; using Calabonga.Microservice.IdentityModule.Infrastructure; -using Calabonga.Microservice.IdentityModule.Web.Definitions.Identity; +using Calabonga.Microservice.IdentityModule.Web.Definitions.Authorizations; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using OpenIddict.Abstractions; @@ -25,8 +25,8 @@ public override void ConfigureServices(WebApplicationBuilder builder) // For example: "Microsoft.EntityFrameworkCore.SqlServer" config.UseInMemoryDatabase("DEMO-PURPOSES-ONLY"); - // uncomment line below to use UseSqlServer(). Don't forget setup connection string in appSettings.json - //config.UseSqlServer(configuration.GetConnectionString(nameof(ApplicationDbContext))); + // uncomment line below to use UseNpgsql() or UseSqlServer(). Don't forget setup connection string in appSettings.json + //config.UseNpgsql(builder.Configuration.GetConnectionString(nameof(ApplicationDbContext))); // Register the entity sets needed by OpenIddict. // Note: use the generic overload if you need to replace the default OpenIddict entities. diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DependencyContainer/ContainerDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DependencyContainer/ContainerDefinition.cs similarity index 88% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DependencyContainer/ContainerDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DependencyContainer/ContainerDefinition.cs index 6e22a329..97e95441 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DependencyContainer/ContainerDefinition.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/DependencyContainer/ContainerDefinition.cs @@ -1,6 +1,6 @@ using Calabonga.AspNetCore.AppDefinitions; using Calabonga.Microservice.IdentityModule.Web.Application.Services; -using Calabonga.Microservice.IdentityModule.Web.Definitions.Identity; +using Calabonga.Microservice.IdentityModule.Web.Definitions.Authorizations; namespace Calabonga.Microservice.IdentityModule.Web.Definitions.DependencyContainer; diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs similarity index 98% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs index 803eff8b..607d6c91 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs @@ -1,7 +1,6 @@ using Calabonga.AspNetCore.AppDefinitions; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Net.Http.Headers; -using System.Diagnostics; using System.Security.Cryptography; namespace Calabonga.Microservice.IdentityModule.Web.Definitions.ETagGenerator; diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/FluentValidating/FluentValidationDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/FluentValidating/FluentValidationDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/FluentValidating/FluentValidationDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/FluentValidating/FluentValidationDefinition.cs diff --git a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/ValidatorBehavior.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/FluentValidating/ValidatorBehavior.cs similarity index 67% rename from AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/ValidatorBehavior.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/FluentValidating/ValidatorBehavior.cs index c134f2e7..b66bf553 100644 --- a/AspNetCore v6.0/TemplateMicroserviceIdentityModuleMinV6/Calabonga.Microservice.IdentityModule.Web/APPLICATION/ValidatorBehavior.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/FluentValidating/ValidatorBehavior.cs @@ -1,20 +1,16 @@ using FluentValidation; using MediatR; -namespace $safeprojectname$.Application; +namespace Calabonga.Microservice.IdentityModule.Web.Definitions.FluentValidating; /// /// Base validator for requests /// /// /// -public class ValidatorBehavior : IPipelineBehavior +public class ValidatorBehavior(IEnumerable> validators) : IPipelineBehavior where TRequest : IRequest { - private readonly IEnumerable> _validators; - - public ValidatorBehavior(IEnumerable> validators) => _validators = validators; - /// /// Pipeline handler. Perform any additional behavior and await the delegate as necessary /// @@ -24,18 +20,14 @@ public class ValidatorBehavior : IPipelineBehaviorAwaitable task returning the public Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) { - var failures = _validators + var failures = validators .Select(x => x.Validate(new ValidationContext(request))) .SelectMany(x => x.Errors) .Where(x => x != null) .ToList(); - if (!failures.Any()) - { - return next(); - } - - // return new ProblemDetails(); - throw new ValidationException(failures); + return failures.Any() + ? throw new ValidationException(failures) + : next(); } } \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/AutomapperDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/AutomapperDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/AutomapperDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/AutomapperDefinition.cs diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MAPPING/PagedListConverter.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/PagedListConverter.cs similarity index 83% rename from AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MAPPING/PagedListConverter.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/PagedListConverter.cs index c66df094..c62192d6 100644 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/DEFINITIONS/MAPPING/PagedListConverter.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mapping/PagedListConverter.cs @@ -1,7 +1,7 @@ using AutoMapper; -using Calabonga.UnitOfWork; +using Calabonga.PagedListCore; -namespace $safeprojectname$.Definitions.Mapping; +namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Mapping; /// /// Generic converter for IPagedList collections @@ -16,8 +16,7 @@ public class PagedListConverter : ITypeConverterResolution context /// Destination object public IPagedList Convert(IPagedList? source, IPagedList destination, ResolutionContext context) => - // ReSharper disable once ConditionIsAlwaysTrueOrFalse source == null ? PagedList.Empty() - : PagedList.From(source, items => context.Mapper.Map>(items)); + : PagedList.From(source, items => context.Mapper.Map>(items)!); } \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs similarity index 70% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs index 7fcb03d5..e0f42de7 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs @@ -8,17 +8,12 @@ namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Mediator.Base; /// /// /// -public class TransactionBehavior : IPipelineBehavior +public class TransactionBehavior(IUnitOfWork unitOfWork) : IPipelineBehavior where TRequest : IRequest { - private readonly IUnitOfWork _unitOfWork; - - public TransactionBehavior(IUnitOfWork unitOfWork) => _unitOfWork = unitOfWork; - - public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) { - await using var transaction = await _unitOfWork.BeginTransactionAsync(); + await using var transaction = await unitOfWork.BeginTransactionAsync(); try { var response = await next(); diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/EventItemPostTransactionBehavior.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/EventItemPostTransactionBehavior.cs similarity index 50% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/EventItemPostTransactionBehavior.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/EventItemPostTransactionBehavior.cs index bb602d48..4e8ca74b 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/EventItemPostTransactionBehavior.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/EventItemPostTransactionBehavior.cs @@ -1,4 +1,4 @@ -using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemsMessages.ViewModels; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.ViewModels; using Calabonga.Microservice.IdentityModule.Web.Definitions.Mediator.Base; using Calabonga.OperationResults; using Calabonga.UnitOfWork; @@ -6,7 +6,5 @@ namespace Calabonga.Microservice.IdentityModule.Web.Definitions.Mediator; -public class EventItemPostTransactionBehavior : TransactionBehavior>, OperationResult> -{ - public EventItemPostTransactionBehavior(IUnitOfWork unitOfWork) : base(unitOfWork) { } -} \ No newline at end of file +public class EventItemPostTransactionBehavior(IUnitOfWork unitOfWork) + : TransactionBehavior>, Operation>(unitOfWork); \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/MediatorDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/MediatorDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/MediatorDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/Mediator/MediatorDefinition.cs diff --git a/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenApi/OAuth2SecuritySchemeTransformer.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenApi/OAuth2SecuritySchemeTransformer.cs new file mode 100644 index 00000000..546bea77 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenApi/OAuth2SecuritySchemeTransformer.cs @@ -0,0 +1,66 @@ +using Calabonga.Microservice.IdentityModule.Domain.Base; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.OpenApi; +using Microsoft.OpenApi.Models; +using OpenIddict.Server.AspNetCore; + +namespace Calabonga.Microservice.IdentityModule.Web.Definitions.OpenApi; + +/// +/// Swagger security configuration scheme +/// +public sealed class OAuth2SecuritySchemeTransformer : IOpenApiDocumentTransformer +{ + private readonly IAuthenticationSchemeProvider _authenticationSchemeProvider; + private readonly string? _authServerUrl; + + public OAuth2SecuritySchemeTransformer(IAuthenticationSchemeProvider authenticationSchemeProvider, IConfiguration configuration) + { + _authenticationSchemeProvider = authenticationSchemeProvider; + _authServerUrl = configuration.GetSection("AuthServer").GetValue("Url"); + + ArgumentNullException.ThrowIfNull(_authServerUrl); + } + + public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken) + { + var authenticationSchemes = await _authenticationSchemeProvider.GetAllSchemesAsync(); + if (authenticationSchemes.Any(authScheme => authScheme.Name == OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)) + { + + var reference = new OpenApiReference() { Id = "oauth2", Type = ReferenceType.SecurityScheme }; + var scheme = new OpenApiSecurityScheme + { + Reference = reference, + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows + { + AuthorizationCode = new OpenApiOAuthFlow + { + TokenUrl = new Uri($"{_authServerUrl}/connect/token", UriKind.Absolute), + AuthorizationUrl = new Uri($"{_authServerUrl}/connect/authorize", UriKind.Absolute), + Scopes = new Dictionary { { "api", "Default scope" } } + } + } + }; + + var requirement = new OpenApiSecurityRequirement + { + { new OpenApiSecurityScheme { Reference = reference, In = ParameterLocation.Cookie, Type = SecuritySchemeType.OAuth2 }, new List() } + }; + + document.Components ??= new OpenApiComponents(); + document.Components.SecuritySchemes ??= new Dictionary(); + document.SecurityRequirements = [requirement]; + document.Components.SecuritySchemes[scheme.Reference.Id] = scheme; + document.Info = new() + { + License = new OpenApiLicense() { Name = "MIT", Url = new Uri("https://mit-license.org/") }, + Title = AppData.ServiceName, + Version = OpenApiDefinition.AppVersion, + Description = AppData.ServiceDescription, + Contact = new() { Name = "Sergei Calabonga", Url = new("https://www.calabonga.net"), } + }; + } + } +} \ No newline at end of file diff --git a/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenApi/OpenApiDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenApi/OpenApiDefinition.cs new file mode 100644 index 00000000..393977d3 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenApi/OpenApiDefinition.cs @@ -0,0 +1,63 @@ +using Calabonga.AspNetCore.AppDefinitions; +using Calabonga.Microservice.IdentityModule.Domain.Base; +using Microsoft.AspNetCore.Mvc; +using Swashbuckle.AspNetCore.SwaggerUI; + +namespace Calabonga.Microservice.IdentityModule.Web.Definitions.OpenApi; + +/// +/// Swagger definition for application +/// +public class OpenApiDefinition : AppDefinition +{ + // ATTENTION! + // If you use are git repository then you can uncomment line with "ThisAssembly" below for versioning by GIT possibilities. + // Otherwise, you can change versions of your API by manually. + // If you are not going to use git-versioning, do not forget install package "GitInfo" + // private const string AppVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; + public const string AppVersion = "9.0.0"; + + private const string _openApiConfig = "/openapi/v1.json"; + + public override void ConfigureServices(WebApplicationBuilder builder) + { + builder.Services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); + builder.Services.AddEndpointsApiExplorer(); + builder.Services.AddOpenApi(options => + { + options.AddDocumentTransformer(); + }); + } + + public override void ConfigureApplication(WebApplication app) + { + if (!app.Environment.IsDevelopment()) + { + return; + } + + var url = app.Services.GetRequiredService().GetValue("AuthServer:Url"); + + app.MapOpenApi(); + + app.UseSwaggerUI(settings => + { + settings.SwaggerEndpoint(_openApiConfig, $"{AppData.ServiceName} v.{AppVersion}"); + + // ATTENTION! + // If you use are git repository then you can uncomment line with "ThisAssembly" below for versioning by GIT possibilities. + // settings.HeadContent = $"{ThisAssembly.Git.Branch.ToUpper()} {ThisAssembly.Git.Commit.ToUpper()}"; + + settings.DocumentTitle = $"{AppData.ServiceName}"; + settings.DefaultModelExpandDepth(0); + settings.DefaultModelRendering(ModelRendering.Model); + settings.DefaultModelsExpandDepth(0); + settings.DocExpansion(DocExpansion.None); + settings.OAuthScopeSeparator(" "); + settings.OAuthClientId("client-id-code"); + settings.OAuthClientSecret("client-secret-code"); + settings.DisplayRequestDuration(); + settings.OAuthAppName(AppData.ServiceName); + }); + } +} diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AppPermissionHandler.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AppPermissionHandler.cs similarity index 95% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AppPermissionHandler.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AppPermissionHandler.cs index 327ed020..6ed76149 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AppPermissionHandler.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AppPermissionHandler.cs @@ -1,4 +1,4 @@ -using Calabonga.Microservices.Core; +using Calabonga.Utils.Extensions; using Microsoft.AspNetCore.Authorization; using System.Security.Claims; diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/OpenIddictDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/OpenIddictDefinition.cs similarity index 98% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/OpenIddictDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/OpenIddictDefinition.cs index cc2811ca..728f316a 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/OpenIddictDefinition.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/OpenIddictDefinition.cs @@ -81,6 +81,7 @@ public override void ConfigureServices(WebApplicationBuilder builder) // Register the ASP.NET Core host and configure the ASP.NET Core options. options .UseAspNetCore() + //.DisableTransportSecurityRequirement() // disable HTTPS .EnableTokenEndpointPassthrough() .EnableAuthorizationEndpointPassthrough(); @@ -123,4 +124,4 @@ public override void ConfigureServices(WebApplicationBuilder builder) // Note: in a real world application, this step should be part of a setup script. builder.Services.AddHostedService(); } -} \ No newline at end of file +} diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/PermissionRequirement.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/PermissionRequirement.cs similarity index 58% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/PermissionRequirement.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/PermissionRequirement.cs index 5817cc5e..e5a40eb4 100644 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/PermissionRequirement.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/OpenIddict/PermissionRequirement.cs @@ -5,12 +5,10 @@ namespace Calabonga.Microservice.IdentityModule.Web.Definitions.OpenIddict; /// /// Permission requirement for user or service authorization /// -public class PermissionRequirement : IAuthorizationRequirement +public class PermissionRequirement(string permissionName) : IAuthorizationRequirement { - public PermissionRequirement(string permissionName) => PermissionName = permissionName; - /// /// Permission name /// - public string PermissionName { get; } + public string PermissionName { get; } = permissionName; } \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/UoW/UnitOfWorkDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/UoW/UnitOfWorkDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/UoW/UnitOfWorkDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Definitions/UoW/UnitOfWorkDefinition.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/AuthorizeEndpoints.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/AuthorizeEndpoints.cs similarity index 97% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/AuthorizeEndpoints.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/AuthorizeEndpoints.cs index 8836329e..d7afad90 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/AuthorizeEndpoints.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/AuthorizeEndpoints.cs @@ -6,7 +6,6 @@ using Microsoft.AspNetCore.Identity; using OpenIddict.Abstractions; using OpenIddict.Server.AspNetCore; - namespace Calabonga.Microservice.IdentityModule.Web.Endpoints; /// @@ -14,12 +13,12 @@ namespace Calabonga.Microservice.IdentityModule.Web.Endpoints; /// You can test your authorization server with https://oidcdebugger.com/ /// You can mock your authorization flow with https://oauth.mocklab.io/ /// -public class AuthorizeEndpoints : AppDefinition +public sealed class AuthorizeEndpoints : AppDefinition { public override void ConfigureApplication(WebApplication app) { - app.MapGet("~/connect/authorize", AuthorizeAsync).ExcludeFromDescription(); - app.MapPost("~/connect/authorize", AuthorizeAsync).ExcludeFromDescription(); + app.MapGet("~/connect/authorize", AuthorizeAsync).ExcludeFromDescription().AllowAnonymous(); + app.MapPost("~/connect/authorize", AuthorizeAsync).ExcludeFromDescription().AllowAnonymous(); } private async Task AuthorizeAsync( @@ -63,7 +62,7 @@ private async Task AuthorizeAsync( switch (await applicationManager.GetConsentTypeAsync(application)) { - // If the consent is external (e.g when authorizations are granted by a sysadmin), + // If the consent is external (e.g. when authorizations are granted by a sysadmin), // immediately return an error if no authorization can be found in the database. case OpenIddictConstants.ConsentTypes.External when !authorizations.Any(): return Results.Forbid( diff --git a/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemEndpoints.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemEndpoints.cs new file mode 100644 index 00000000..2c4be9d5 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/EventItemEndpoints.cs @@ -0,0 +1,57 @@ +using Calabonga.AspNetCore.AppDefinitions; +using Calabonga.Microservice.IdentityModule.Domain; +using Calabonga.Microservice.IdentityModule.Domain.Base; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.Queries; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.EventItemMessages.ViewModels; +using MediatR; +using Microsoft.AspNetCore.Mvc; + +namespace Calabonga.Microservice.IdentityModule.Web.Endpoints; + +public sealed class EventItemEndpoints : AppDefinition +{ + public override void ConfigureApplication(WebApplication app) + { + var group = app.MapGroup("/api/event-items/").WithTags(nameof(EventItem)); + + group.MapGet("paged/{pageIndex:int}", async ([FromServices] IMediator mediator, string? search, HttpContext context, int pageIndex = 0, int pageSize = 10) + => await mediator.Send(new GetEventItemPaged.Request(pageIndex, pageSize, search), context.RequestAborted)) + .RequireAuthorization(AppData.PolicyDefaultName) + .Produces(200) + .ProducesProblem(401) + .ProducesProblem(404) + .WithOpenApi(); + + group.MapGet("{id:guid}", async ([FromServices] IMediator mediator, Guid id, HttpContext context) + => await mediator.Send(new GetEventItemById.Request(id), context.RequestAborted)) + .RequireAuthorization(AppData.PolicyDefaultName) + .Produces(200) + .ProducesProblem(401) + .ProducesProblem(404) + .WithOpenApi(); + + group.MapDelete("{id:guid}", async ([FromServices] IMediator mediator, Guid id, HttpContext context) + => await mediator.Send(new DeleteEventItem.Request(id), context.RequestAborted)) + .RequireAuthorization(AppData.PolicyDefaultName) + .Produces(200) + .ProducesProblem(401) + .ProducesProblem(404) + .WithOpenApi(); + + group.MapPost("", async ([FromServices] IMediator mediator, EventItemCreateViewModel model, HttpContext context) + => await mediator.Send(new PostEventItem.Request(model), context.RequestAborted)) + .RequireAuthorization(AppData.PolicyDefaultName) + .Produces(200) + .ProducesProblem(401) + .ProducesProblem(404) + .WithOpenApi(); + + group.MapPut("{id:guid}", async ([FromServices] IMediator mediator, Guid id, EventItemUpdateViewModel model, HttpContext context) + => await mediator.Send(new PutEventItem.Request(id, model), context.RequestAborted)) + .RequireAuthorization(AppData.PolicyDefaultName) + .Produces(200) + .ProducesProblem(401) + .ProducesProblem(404) + .WithOpenApi(); + } +} \ No newline at end of file diff --git a/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfilesEndpoints.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfilesEndpoints.cs new file mode 100644 index 00000000..7438097a --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/ProfilesEndpoints.cs @@ -0,0 +1,33 @@ +using Calabonga.AspNetCore.AppDefinitions; +using Calabonga.Microservice.IdentityModule.Domain.Base; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileMessages.Queries; +using Calabonga.Microservice.IdentityModule.Web.Application.Messaging.ProfileMessages.ViewModels; +using MediatR; +using Microsoft.AspNetCore.Mvc; + +namespace Calabonga.Microservice.IdentityModule.Web.Endpoints; + +public sealed class ProfilesEndpointDefinition : AppDefinition +{ + public override void ConfigureApplication(WebApplication app) + { + var group = app.MapGroup("/api/profiles").WithTags("Profiles"); + + group.MapGet("roles", async ([FromServices] IMediator mediator, HttpContext context) + => await mediator.Send(new GetProfile.Request(), context.RequestAborted)) + .RequireAuthorization(AppData.PolicyDefaultName) + .RequireAuthorization(x => + { + x.RequireClaim("Profiles:Roles:Get"); + }) + .Produces(200) + .ProducesProblem(401) + .WithOpenApi(); + + group.MapPost("register", async ([FromServices] IMediator mediator, RegisterViewModel model, HttpContext context) + => await mediator.Send(new RegisterAccount.Request(model), context.RequestAborted)) + .Produces(200) + .WithOpenApi() + .AllowAnonymous(); + } +} \ No newline at end of file diff --git a/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/TokenEndpoints.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/TokenEndpoints.cs new file mode 100644 index 00000000..869b9095 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Endpoints/TokenEndpoints.cs @@ -0,0 +1,107 @@ +using Calabonga.AspNetCore.AppDefinitions; +using Calabonga.Microservice.IdentityModule.Infrastructure; +using Calabonga.Microservice.IdentityModule.Web.Application.Services; +using Calabonga.Utils.Extensions; +using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Identity; +using OpenIddict.Abstractions; +using OpenIddict.Server.AspNetCore; +using System.Security.Claims; + +namespace Calabonga.Microservice.IdentityModule.Web.Endpoints; + +/// +/// Token Endpoint for OpenIddict +/// +public sealed class TokenEndpoints : AppDefinition +{ + public override void ConfigureApplication(WebApplication app) => + app.MapPost("~/connect/token", async ( + HttpContext httpContext, + UserManager userManager, + SignInManager signInManager, + IAccountService accountService) => + { + var request = httpContext.GetOpenIddictServerRequest() ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved."); + + if (request.IsClientCredentialsGrantType()) + { + var identity = new ClaimsIdentity(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + + // Subject or sub is a required field, we use the client id as the subject identifier here. + identity.AddClaim(OpenIddictConstants.Claims.Subject, request.ClientId!); + identity.AddClaim(OpenIddictConstants.Claims.ClientId, request.ClientId!); + + // Don't forget to add destination otherwise it won't be added to the access token. + if (request.Scope.IsNullOrEmpty()) + { + identity.AddClaim(OpenIddictConstants.Claims.Scope, request.Scope!, OpenIddictConstants.Destinations.AccessToken); + } + + identity.AddClaim("nimble", "framework", OpenIddictConstants.Destinations.AccessToken); + + var claimsPrincipal = new ClaimsPrincipal(identity); + + claimsPrincipal.SetScopes(request.GetScopes()); + return Results.SignIn(claimsPrincipal, new AuthenticationProperties(), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + } + + if (request.IsPasswordGrantType()) + { + if (request.Username != null) + { + var user = await userManager.FindByNameAsync(request.Username); + if (user == null) + { + return Results.Problem("Invalid operation"); + } + + // Ensure the user is allowed to sign in + if (!await signInManager.CanSignInAsync(user)) + { + return Results.Problem("Invalid operation"); + } + + + // Ensure the user is not already locked out + if (userManager.SupportsUserLockout && await userManager.IsLockedOutAsync(user)) + { + return Results.Problem("Invalid operation"); + } + + // Ensure the password is valid + if (request.Password != null && !await userManager.CheckPasswordAsync(user, request.Password)) + { + if (userManager.SupportsUserLockout) + { + await userManager.AccessFailedAsync(user); + } + + return Results.Problem("Invalid operation"); + } + + // Reset the lockout count + if (userManager.SupportsUserLockout) + { + await userManager.ResetAccessFailedCountAsync(user); + } + + var principal = await accountService.GetPrincipalForUserAsync(user); + + return Results.SignIn(principal, null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + } + } + + if (request.IsAuthorizationCodeGrantType()) + { + var authenticateResult = await httpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + var claimsPrincipal = authenticateResult.Principal; + return Results.SignIn(claimsPrincipal!, null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme); + } + + return Results.Problem("The specified grant type is not supported."); + }) + .ExcludeFromDescription() + .AllowAnonymous(); +} diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/HostedServices/OpenIddictWorker.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/HostedServices/OpenIddictWorker.cs similarity index 88% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/HostedServices/OpenIddictWorker.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/HostedServices/OpenIddictWorker.cs index d3234d44..2bb5de35 100644 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/HostedServices/OpenIddictWorker.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/HostedServices/OpenIddictWorker.cs @@ -3,15 +3,11 @@ namespace Calabonga.Microservice.IdentityModule.Web.HostedServices; -public class OpenIddictWorker : IHostedService +public sealed class OpenIddictWorker(IServiceProvider serviceProvider) : IHostedService { - private readonly IServiceProvider _serviceProvider; - - public OpenIddictWorker(IServiceProvider serviceProvider) => _serviceProvider = serviceProvider; - public async Task StartAsync(CancellationToken cancellationToken) { - await using var scope = _serviceProvider.CreateAsyncScope(); + await using var scope = serviceProvider.CreateAsyncScope(); var context = scope.ServiceProvider.GetRequiredService(); await context.Database.EnsureCreatedAsync(cancellationToken); @@ -45,7 +41,7 @@ await manager.CreateAsync(new OpenIddictApplicationDescriptor const string client_id2 = "client-id-code"; if (await manager.FindByClientIdAsync(client_id2, cancellationToken) is null) { - var url = _serviceProvider.GetRequiredService().GetValue("AuthServer:Url"); + var url = serviceProvider.GetRequiredService().GetValue("AuthServer:Url"); await manager.CreateAsync(new OpenIddictApplicationDescriptor { @@ -56,7 +52,7 @@ await manager.CreateAsync(new OpenIddictApplicationDescriptor RedirectUris = { new Uri("https://www.thunderclient.com/oauth/callback"), // https://www.thunderclient.com/ new Uri($"{url}/swagger/oauth2-redirect.html"), // https://swagger.io/ - new Uri("https://localhost:20001/swagger/oauth2-redirect.html") // https://swagger.io/ for Module + new Uri("https://localhost:20001/swagger/oauth2-redirect.html") // https://swagger.io/ for Module as Example }, Permissions = diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml similarity index 75% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml index 459a7373..0d4af5e0 100644 --- a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml @@ -1,32 +1,33 @@ @page @model Calabonga.Microservice.IdentityModule.Web.Pages.Connect.LoginModel +@{ + ViewData["Title"] = "Log in"; +} -
- -
- +
+ @if (Model.Input != null) + {
- - + +
- -
+
- +
-
- +
+
-
-
\ No newline at end of file + } +
diff --git a/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml.cs new file mode 100644 index 00000000..36547a71 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/Login.cshtml.cs @@ -0,0 +1,71 @@ +using Calabonga.Microservice.IdentityModule.Infrastructure; +using Calabonga.Microservice.IdentityModule.Web.Application.Services; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.RazorPages; + +namespace Calabonga.Microservice.IdentityModule.Web.Pages.Connect +{ + [AllowAnonymous] + public class LoginModel : PageModel + { + private readonly IAccountService _accountService; + private readonly SignInManager _signInManager; + private readonly UserManager _userManager; + + public LoginModel(IAccountService accountService, + SignInManager signInManager, + UserManager userManager) + { + _accountService = accountService; + _signInManager = signInManager; + _userManager = userManager; + } + + [BindProperty(SupportsGet = true)] public string ReturnUrl { get; set; } = null!; + + [BindProperty] public LoginViewModel? Input { get; set; } + + public void OnGet() => Input = new LoginViewModel { ReturnUrl = ReturnUrl }; + + public async Task OnPostAsync() + { + if (!ModelState.IsValid) + { + return Page(); + } + + if (Input != null) + { + var user = await _userManager.FindByNameAsync(Input.UserName); + if (user == null) + { + ModelState.AddModelError("UserName", "User not found"); + + return Page(); + } + + var signInResult = await _signInManager.PasswordSignInAsync(user, Input.Password, true, false); + if (signInResult.Succeeded) + { + var principal = await _accountService.GetPrincipalByIdAsync(user.Id.ToString()); + await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); + + if (Url.IsLocalUrl(ReturnUrl)) + { + return Redirect(ReturnUrl); + } + + return RedirectToPage("/swagger"); + } + } + + ModelState.AddModelError("UserName", "User not found"); + + return Page(); + } + } +} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/LoginViewModel.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/LoginViewModel.cs similarity index 77% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/LoginViewModel.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/LoginViewModel.cs index 09acde97..22411d03 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/LoginViewModel.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Connect/LoginViewModel.cs @@ -5,13 +5,13 @@ namespace Calabonga.Microservice.IdentityModule.Web.Pages.Connect; public class LoginViewModel { - [Required] + [Required] [EmailAddress] - [Display(Name = "Имя для входа")] + [Display(Name = "User name")] public string UserName { get; set; } = null!; [Required] - [Display(Name = "Пароль")] + [Display(Name = "Password")] public string Password { get; set; } = null!; [Required] diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Shared/_Layout.cshtml b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Shared/_Layout.cshtml similarity index 92% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Shared/_Layout.cshtml rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Shared/_Layout.cshtml index ed9249da..d6c2bd72 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Shared/_Layout.cshtml +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/Shared/_Layout.cshtml @@ -1,4 +1,4 @@ -@using Calabonga.Microservice.IdentityModule.Web.Definitions.Swagger +@using Calabonga.Microservice.IdentityModule.Web.Definitions.OpenApi @@ -17,7 +17,7 @@ Сервер авторизации

- Version: @SwaggerDefinition.AppVersion + Version: @OpenApiDefinition.AppVersion

@@ -27,7 +27,7 @@

- Nimble Framework 2023 © Calabonga SOFT + Nimble Framework 2019-@DateTime.Today.Year © Calabonga SOFT

diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewImports.cshtml b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewImports.cshtml similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewImports.cshtml rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewImports.cshtml diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewStart.cshtml b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewStart.cshtml similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewStart.cshtml rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Pages/_ViewStart.cshtml diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/Program.cs b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Program.cs similarity index 86% rename from AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/Program.cs rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Program.cs index 70521778..a2a0b703 100644 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/Program.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Program.cs @@ -1,24 +1,24 @@ // -------------------------------------------------------------------- // Name: Template for Micro service on ASP.NET Core API with // OpenIddict (OAuth2.0) -// Author: Calabonga © 2005-2023 Calabonga SOFT -// Version: 7.0.6 -// Based on: .NET 7.0.x -// Created Date: 2022-11-12 09:29 -// Updated Date: 2023-08-04 09:48 +// Author: Calabonga © 2005-2024 Calabonga SOFT +// Version: 8.0.6 +// Based on: .NET 8.0.x +// Created Date: 2023-11-19 +// Updated Date: 2024-07-23 // -------------------------------------------------------------------- // Contacts // -------------------------------------------------------------------- // Donate: https://boosty.to/calabonga/donate -// Blog: https://www.calabonga.net/blog/post/nimble-framework-7 +// Blog: https://www.calabonga.net // GitHub: https://github.com/Calabonga/Microservice-Template -// BoostyTo: https://boosty.to/calabonga +// Boosty: https://boosty.to/calabonga // YouTube: https://youtube.com/sergeicalabonga // DZen: https://dzen.ru/calabonga // -------------------------------------------------------------------- // Description: // -------------------------------------------------------------------- -// Minimal API for NET7 used with Definitions. +// Minimal API for NET8 used with Definitions. // This template implements Web API and OpenIddict (OAuth2.0). // functionality. Also, support two type of Authentication: // Cookie and Bearer @@ -69,7 +69,7 @@ } Log.Fatal(ex, "Unhandled exception"); - return 1; + throw; } finally { diff --git a/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Properties/launchSettings.json b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Properties/launchSettings.json new file mode 100644 index 00000000..94880a17 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/Properties/launchSettings.json @@ -0,0 +1,13 @@ +{ + "profiles": { + "Kestrel": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "https://localhost:10001" + } + } +} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json similarity index 95% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json index f8299029..ec6c2967 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.Development.json @@ -17,7 +17,7 @@ { "Name": "File", "Args": { - "path": "/logs/log-.log", + "path": "logs/log-.log", "rollingInterval": "Day", "rollOnFileSizeLimit": true, "shared": true, diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.Production.json b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.Production.json similarity index 95% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.Production.json rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.Production.json index 200d96aa..03ac98a0 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.Production.json +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.Production.json @@ -17,7 +17,7 @@ { "Name": "File", "Args": { - "path": "/logs/log-.log", + "path": "logs/log-.log", "rollingInterval": "Day", "rollOnFileSizeLimit": true, "shared": true, diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.json b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.json similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.json rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/appsettings.json diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/readme.md b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/readme.md similarity index 70% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/readme.md rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/readme.md index 6020f1a2..441230f0 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/readme.md +++ b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/readme.md @@ -1,18 +1,19 @@ # Attentions -Please find out all comments with 'ATTENTION!' because that is required some decisions from you +Please find out all comments with 'ATTENTION!' because that is required some decisions from you. # About | Name | Description | | ------------ | ------------------------------------------ | | Name | Microservice Template for ASP.NET Core API | -| Author | Calabonga SOFT © 2005-2023 Calabonga SOFT | -| Created Date | 2019-04-13 3:28:39 PM | +| Author | Calabonga SOFT © 2005-2024 Calabonga SOFT | +| Created Date | 2024-11-26 | +| Create From | Microservice-Template NET8.0 | # Versions -Nimble Framework Templates build on .NET 7.0. That`s why it have the same major version. But the all improvements will increment minor versions. +Nimble Framework Templates build on .NET 9.0. That`s why it have the same major version. But the all improvements will increment minor versions. # Contacts @@ -26,4 +27,4 @@ You can contact me by using the next opportunities: # Description: -This template implements Web API functionality using minimal API feature from NET 7.0 \ No newline at end of file +This template implements Web API functionality using minimal API feature from NET 9.0 \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.IdentityModule/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/content/Calabonga.Microservice.IdentityModule.Web/tempkey.jwk diff --git a/AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/logo.png b/AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/logo.png similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.IdentityModule.Template/logo.png rename to AspNetCore v9.0/Calabonga.Microservice.IdentityModule.Template/logo.png diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.csproj b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.csproj similarity index 82% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.csproj rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.csproj index 5f91f06a..4adbf3ef 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.csproj +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.csproj @@ -4,25 +4,25 @@ Calabonga.Microservice.Module.Template - 7.0.8 + 8.0.6 Microservice template Calabonga - Calabonga © 2016-2023 + Calabonga SOFT © 2001 - $([System.DateTime]::Now.ToString(yyyy)) logo.png - Microservice template with Automapper, FluentValidation and other helpful thing - template, microservice, calabonga, nimble, framework + Microservice template on Minimal API with Automapper, FluentValidation and other helpful thing + template, microservice, oauth2, calabonga, nimble, framework, minimal, api https://github.com/Calabonga/Microservice-Template MIT - + Nugets versions bumped + Template - net7.0 + net8.0 true false content $(NoWarn);NU5128 true - Big nullable supporting added diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.sln b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.sln similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.sln rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/Calabonga.Microservice.Module.Template.sln diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/README.md b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/README.md similarity index 78% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/README.md rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/README.md index 7718d859..192609d6 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/README.md +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/README.md @@ -2,8 +2,9 @@ Справочная информация по фреймворку есть в [Wiki](https://github.com/Calabonga/Microservice-Template/wiki) и на [сайте разработчика](https://www.calabonga.net/blog/post/microservice-templates). ->Внимание (Attention)! Пожалуйста, ознакомьтесь со всеми комментариями с надписью "ATTENTION!", потому что эти места потребуют от вас некоторых решений и/или действий. -Please find out all comments with 'ATTENTION!' because that is required some decisions or actions from you. +> Внимание! Пожалуйста, ознакомьтесь со всеми комментариями с надписью "ATTENTION!", потому что эти места потребуют от вас некоторых решений и/или действий. + +> Attention! Please find out all comments with 'ATTENTION!' because that is required some decisions or actions from you. ## Как установить (How to install) diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/.editorconfig b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/.editorconfig similarity index 99% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/.editorconfig rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/.editorconfig index a6b70db4..ba57c383 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/.editorconfig +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/.editorconfig @@ -19,7 +19,7 @@ tab_width = 4 # New line preferences end_of_line = crlf -insert_final_newline = false +insert_final_newline = true #### .NET Coding Conventions #### diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/.template.config/template.json b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/.template.config/template.json similarity index 71% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/.template.config/template.json rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/.template.config/template.json index 78638dba..a2656d6f 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/.template.config/template.json +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/.template.config/template.json @@ -4,15 +4,15 @@ "classifications": [ "Common", "Web", - "WebAPI" + "Web API" ], "name": "Microservice template", - "description": "Nimble Microservice Framework. This template gives you a possibility to start developing a microservice architecture with integrated UI (Swagger), Mediatr, Automapper. Template developed for .NET 7.0.x.", + "description": "Microservice Template. Nimble Framework based on Minimal API (.NET9). This template gives you a possibility to start developing a microservice architecture with and integrated other helpful things like a UI (Scalar), Mediatr, Automapper, Serilog, etc.", "identity": "Calabonga.Microservice.Module", "shortName": "microservice", "tags": { "language": "C#", - "type": "project" + "type": "solution" }, "sourceName": "Calabonga.Microservice.Module", "preferNameDirectory": true, @@ -23,10 +23,10 @@ "datatype": "choice", "choices": [ { - "choice": "net7.0" + "choice": "net9.0" } ], - "defaultValue": "net7.0" + "defaultValue": "net9.0" } }, "sources": [ diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/AppData.Common.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Common.cs similarity index 95% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/AppData.Common.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Common.cs index fadb6aa2..ec5115e4 100644 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/AppData.Common.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Common.cs @@ -8,7 +8,7 @@ public static partial class AppData /// /// CORS Policy name /// - public const string PolicyName = "CorsPolicy"; + public const string CorsPolicyName = "CorsPolicy"; /// /// Current service name @@ -42,4 +42,4 @@ public static IEnumerable Roles } } } -} \ No newline at end of file +} diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Exceptions.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Exceptions.cs similarity index 86% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Exceptions.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Exceptions.cs index ea15c31f..d8194b3c 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Exceptions.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Exceptions.cs @@ -56,6 +56,16 @@ public static class Exceptions /// "Argument out of range" /// public static string ArgumentOutOfRangeException => "Argument out of range"; + + /// + /// "Mapping failed" + /// + public static string MappingException => "Mapping failed"; + + /// + /// "Something went wrong" + /// + public static string SomethingWrong => "Something went wrong"; } } } \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/AppData.Messages.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Messages.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/AppData.Messages.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/AppData.Messages.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Auditable.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Auditable.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Auditable.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Auditable.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IAuditable.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IAuditable.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IAuditable.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IAuditable.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/IHaveId.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IHaveId.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/IHaveId.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IHaveId.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/IViewModel.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IViewModel.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/IViewModel.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/IViewModel.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/Identity.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Identity.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/Identity.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Identity.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/NamedAuditable.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/NamedAuditable.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/NamedAuditable.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/NamedAuditable.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/NamedIdentity.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/NamedIdentity.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/NamedIdentity.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/NamedIdentity.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/Sortable.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Sortable.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/Sortable.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/Sortable.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/TypeHelper.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/TypeHelper.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/TypeHelper.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/TypeHelper.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/ViewModelBase.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/ViewModelBase.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/Base/ViewModelBase.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Base/ViewModelBase.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj similarity index 52% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj index 5a6d1162..b9b3d6b3 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/Calabonga.Microservice.Module.Domain.csproj @@ -1,11 +1,10 @@  - net7.0 + net9.0 enable enable - true - enable + false diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/EventItem.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/EventItem.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/EventItem.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/EventItem.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/GlobalUsing.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/GlobalUsing.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Domain/GlobalUsing.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Domain/GlobalUsing.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs similarity index 75% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs index 8eae06cf..dfe708c9 100644 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationDbContext.cs @@ -1,4 +1,6 @@ -using Calabonga.Microservice.Module.Infrastructure.Base; +#nullable disable + +using Calabonga.Microservice.Module.Infrastructure.Base; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -46,4 +48,20 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) base.OnConfiguring(optionsBuilder); } } -} \ No newline at end of file +} + +///// +///// ATTENTION! +///// It should uncomment two line below when using real Database (not in memory mode). Don't forget update connection string. +///// +//public class ApplicationDbContextFactory : IDesignTimeDbContextFactory +//{ +// public ApplicationDbContext CreateDbContext(string[] args) +// { +// var optionsBuilder = new DbContextOptionsBuilder(); +// optionsBuilder.UseSqlServer("Server=;Database=;User ID=;Password="); +// return new ApplicationDbContext(optionsBuilder.Options); +// } +//} + +#nullable restore \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationRole.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationRole.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/ApplicationRole.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationRole.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationUser.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationUser.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationUser.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationUser.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationUserProfile.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationUserProfile.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationUserProfile.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationUserProfile.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationUserStore.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationUserStore.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationUserStore.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/ApplicationUserStore.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/Base/DbContextBase.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/Base/DbContextBase.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/Base/DbContextBase.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/Base/DbContextBase.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj similarity index 64% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj index 89dbc06c..22524623 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/Calabonga.Microservice.Module.Infrastructure.csproj @@ -1,21 +1,20 @@  - net7.0 + net9.0 enable enable - true - enable + false - - + + - - - - + + + + diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/DatabaseInitialization/DatabaseInitializer.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/GlobalUsing.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/GlobalUsing.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Infrastructure/GlobalUsing.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/GlobalUsing.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/MicroservicePermission.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/MicroservicePermission.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/MicroservicePermission.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Infrastructure/MicroservicePermission.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/EventItemMapperConfiguration.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/EventItemMapperConfiguration.cs similarity index 97% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/EventItemMapperConfiguration.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/EventItemMapperConfiguration.cs index c47f959f..c5989e0d 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/EventItemMapperConfiguration.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/EventItemMapperConfiguration.cs @@ -2,7 +2,7 @@ using Calabonga.Microservice.Module.Domain; using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.ViewModels; using Calabonga.Microservice.Module.Web.Definitions.Mapping; -using Calabonga.UnitOfWork; +using Calabonga.PagedListCore; namespace Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages; diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/EventItemValidator.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/EventItemValidator.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/EventItemValidator.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/EventItemValidator.cs diff --git a/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/DeleteEventItem.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/DeleteEventItem.cs new file mode 100644 index 00000000..6f46c7d1 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/DeleteEventItem.cs @@ -0,0 +1,48 @@ +using AutoMapper; +using Calabonga.Microservice.Module.Domain; +using Calabonga.Microservice.Module.Domain.Base; +using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.ViewModels; +using Calabonga.OperationResults; +using Calabonga.UnitOfWork; +using MediatR; + +namespace Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.Queries; + +/// +/// Request: EventItem delete +/// +public sealed class DeleteEventItem +{ + public record Request(Guid Id) : IRequest>; + + public class Handler(IUnitOfWork unitOfWork, IMapper mapper) + : IRequestHandler> + { + /// Handles a request + /// The request + /// Cancellation token + /// Response from the request + public async Task> Handle(Request request, CancellationToken cancellationToken) + { + var repository = unitOfWork.GetRepository(); + var entity = await repository.FindAsync(request.Id); + if (entity == null) + { + return Operation.Error(AppData.Exceptions.NotFoundException); + } + + repository.Delete(entity); + await unitOfWork.SaveChangesAsync(); + if (!unitOfWork.LastSaveChangesResult.IsOk) + { + return Operation.Error(unitOfWork.LastSaveChangesResult.Exception?.Message ?? AppData.Exceptions.SomethingWrong); + } + + var mapped = mapper.Map(entity); + + return mapped is not null + ? Operation.Result(mapped) + : Operation.Error(AppData.Exceptions.MappingException); + } + } +} \ No newline at end of file diff --git a/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemById.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemById.cs new file mode 100644 index 00000000..eae51bb2 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemById.cs @@ -0,0 +1,42 @@ +using AutoMapper; +using Calabonga.Microservice.Module.Domain; +using Calabonga.Microservice.Module.Domain.Base; +using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.ViewModels; +using Calabonga.OperationResults; +using Calabonga.UnitOfWork; +using MediatR; + +namespace Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.Queries; + +/// +/// Request for EventItem by Identifier +/// +public sealed class GetEventItemById +{ + public record Request(Guid Id) : IRequest>; + + public class Handler(IUnitOfWork unitOfWork, IMapper mapper) + : IRequestHandler> + { + /// Handles a request getting log by identifier + /// The request + /// Cancellation token + /// Response from the request + public async Task> Handle(Request request, CancellationToken cancellationToken) + { + var id = request.Id; + var repository = unitOfWork.GetRepository(); + var entityWithoutIncludes = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == id, trackingType: TrackingType.NoTracking); + if (entityWithoutIncludes == null) + { + return Operation.Error($"Entity with identifier {id} not found"); + } + + var mapped = mapper.Map(entityWithoutIncludes); + + return mapped is not null + ? Operation.Result(mapped) + : Operation.Error(AppData.Exceptions.MappingException); + } + } +} diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemPaged.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemPaged.cs similarity index 56% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemPaged.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemPaged.cs index fd80829e..f22fb5d9 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemPaged.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/GetEventItemPaged.cs @@ -1,7 +1,9 @@ using AutoMapper; using Calabonga.Microservice.Module.Domain; +using Calabonga.Microservice.Module.Domain.Base; using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.ViewModels; using Calabonga.OperationResults; +using Calabonga.PagedListCore; using Calabonga.PredicatesBuilder; using Calabonga.UnitOfWork; using MediatR; @@ -12,51 +14,40 @@ namespace Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessa /// /// Request for paged list of EventItems /// -public class GetEventItemPaged +public sealed class GetEventItemPaged { - public record Request(int PageIndex, int PageSize, string? Search) : IRequest>>; + public record Request(int PageIndex, int PageSize, string? Search) : IRequest, string>>; - public class Handler : IRequestHandler>> + public class Handler(IUnitOfWork unitOfWork, IMapper mapper) + : IRequestHandler, string>> { - private readonly IUnitOfWork _unitOfWork; - private readonly IMapper _mapper; - - public Handler(IUnitOfWork unitOfWork, IMapper mapper) - { - _unitOfWork = unitOfWork; - _mapper = mapper; - } - - public async Task>> Handle( + public async Task, string>> Handle( Request request, CancellationToken cancellationToken) { - var operation = OperationResult.CreateResult>(); var predicate = GetPredicate(request.Search); - var pagedList = await _unitOfWork.GetRepository() + var pagedList = await unitOfWork.GetRepository() .GetPagedListAsync( predicate: predicate, pageIndex: request.PageIndex, pageSize: request.PageSize, + trackingType: TrackingType.NoTracking, cancellationToken: cancellationToken); - if (pagedList == null) - { - operation.Result = PagedList.Empty(); - operation.AddWarning("Response does not return the result for pagination."); - return operation; - } - if (pagedList.PageIndex > pagedList.TotalPages) { - pagedList = await _unitOfWork.GetRepository() + pagedList = await unitOfWork.GetRepository() .GetPagedListAsync( pageIndex: 0, - pageSize: request.PageSize, cancellationToken: cancellationToken); + pageSize: request.PageSize, + trackingType: TrackingType.NoTracking, + cancellationToken: cancellationToken); } - operation.Result = _mapper.Map>(pagedList); - return operation; + var mapped = mapper.Map>(pagedList); + return mapped is not null + ? Operation.Result(mapped) + : Operation.Error(AppData.Exceptions.MappingException); } private Expression> GetPredicate(string? search) diff --git a/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/PostEventItem.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/PostEventItem.cs new file mode 100644 index 00000000..7096bfcc --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/PostEventItem.cs @@ -0,0 +1,55 @@ +using AutoMapper; +using Calabonga.Microservice.Module.Domain; +using Calabonga.Microservice.Module.Domain.Base; +using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.ViewModels; +using Calabonga.Microservices.Core; +using Calabonga.Microservices.Core.Exceptions; +using Calabonga.OperationResults; +using Calabonga.UnitOfWork; +using MediatR; + +namespace Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.Queries; + +/// +/// Request: EventItem creation +/// +public sealed class PostEventItem +{ + public record Request(EventItemCreateViewModel Model) : IRequest>; + + public class Handler(IUnitOfWork unitOfWork, IMapper mapper, ILogger logger) + : IRequestHandler> + { + public async Task> Handle(Request eventItemRequest, CancellationToken cancellationToken) + { + logger.LogDebug("Creating new EventItem"); + + var entity = mapper.Map(eventItemRequest.Model); + if (entity == null) + { + var exceptionMapper = new MicroserviceUnauthorizedException(AppContracts.Exceptions.MappingException); + logger.LogError(exceptionMapper, "Mapper not configured correctly or something went wrong"); + + return Operation.Error(exceptionMapper.Message); + } + + await unitOfWork.GetRepository().InsertAsync(entity, cancellationToken); + await unitOfWork.SaveChangesAsync(); + + var lastResult = unitOfWork.LastSaveChangesResult; + if (lastResult.IsOk) + { + var mapped = mapper.Map(entity); + logger.LogInformation("New entity {EventItem} successfully created", entity); + return mapped is not null + ? Operation.Result(mapped) + : Operation.Error(AppData.Exceptions.MappingException); + } + + var errorMessage = lastResult.Exception?.Message ?? AppData.Exceptions.SomethingWrong; + logger.LogError(errorMessage, "Error data saving to Database or something went wrong"); + + return Operation.Error(errorMessage); + } + } +} \ No newline at end of file diff --git a/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/UpdateEventItem.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/UpdateEventItem.cs new file mode 100644 index 00000000..eaa79d83 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/Queries/UpdateEventItem.cs @@ -0,0 +1,50 @@ +using AutoMapper; +using Calabonga.Microservice.Module.Domain; +using Calabonga.Microservice.Module.Domain.Base; +using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.ViewModels; +using Calabonga.Microservices.Core; +using Calabonga.OperationResults; +using Calabonga.UnitOfWork; +using MediatR; + +namespace Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.Queries; + +/// +/// Request: EventItem edit +/// +public sealed class PutEventItem +{ + public record Request(Guid Id, EventItemUpdateViewModel Model) : IRequest>; + + public class Handler(IUnitOfWork unitOfWork, IMapper mapper) + : IRequestHandler> + { + public async Task> Handle(Request eventItemRequest, CancellationToken cancellationToken) + { + var repository = unitOfWork.GetRepository(); + var entity = await repository.GetFirstOrDefaultAsync(predicate: x => x.Id == eventItemRequest.Id, disableTracking: false); + if (entity == null) + { + return Operation.Error(AppContracts.Exceptions.NotFoundException); + } + + mapper.Map(eventItemRequest.Model, entity); + + repository.Update(entity); + await unitOfWork.SaveChangesAsync(); + + var lastResult = unitOfWork.LastSaveChangesResult; + if (lastResult.IsOk) + { + var mapped = mapper.Map(entity); + return mapped is not null + ? Operation.Result(mapped) + : Operation.Error(AppData.Exceptions.MappingException); + } + + var errorMessage = lastResult.Exception?.Message ?? AppData.Exceptions.SomethingWrong; + + return Operation.Error(errorMessage); + } + } +} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemCreateViewModel.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemCreateViewModel.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemCreateViewModel.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemCreateViewModel.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemUpdateViewModel.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemUpdateViewModel.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemUpdateViewModel.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemUpdateViewModel.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemViewModel.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemViewModel.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemViewModel.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/EventItemMessages/ViewModels/EventItemViewModel.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/ProfilesMapperConfiguration.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/ProfilesMapperConfiguration.cs similarity index 97% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/ProfilesMapperConfiguration.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/ProfilesMapperConfiguration.cs index e4109799..8dbd30a3 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/ProfilesMapperConfiguration.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/ProfilesMapperConfiguration.cs @@ -1,6 +1,6 @@ using AutoMapper; using Calabonga.Microservice.Module.Web.Application.Messaging.ProfileMessages.ViewModels; -using Calabonga.Microservices.Core; +using Calabonga.Utils.Extensions; using System.Security.Claims; namespace Calabonga.Microservice.Module.Web.Application.Messaging.ProfileMessages; diff --git a/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/Queries/GetRoles.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/Queries/GetRoles.cs new file mode 100644 index 00000000..e93f91c2 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/Queries/GetRoles.cs @@ -0,0 +1,27 @@ +using Calabonga.Utils.Extensions; +using MediatR; +using System.Security.Claims; + +namespace Calabonga.Microservice.Module.Web.Application.Messaging.ProfileMessages.Queries; + +/// +/// Request: Returns user roles +/// +public sealed class GetProfile +{ + public record Request : IRequest; + + public class Handler(ILogger logger, IHttpContextAccessor httpContextAccessor) + : IRequestHandler + { + public Task Handle(Request request, CancellationToken cancellationToken) + { + var user = httpContextAccessor.HttpContext!.User; + var claims = user.FindAll(x => x.Type == ClaimTypes.Role); + var roles = ClaimsHelper.GetValues(new ClaimsIdentity(claims), ClaimTypes.Role); + var message = $"Current user ({user.Identity!.Name}) have following roles: {string.Join('|', roles)}"; + logger.LogInformation(message); + return Task.FromResult(message); + } + } +} diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/ViewModels/UserProfileViewModel.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/ViewModels/UserProfileViewModel.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/ViewModels/UserProfileViewModel.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Application/Messaging/ProfileMessages/ViewModels/UserProfileViewModel.cs diff --git a/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj new file mode 100644 index 00000000..626d6147 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Calabonga.Microservice.Module.Web.csproj @@ -0,0 +1,38 @@ + + + + net9.0 + enable + enable + false + + + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Identity/AuthData.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Authorizations/AuthData.cs similarity index 70% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Identity/AuthData.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Authorizations/AuthData.cs index e250920a..99b477af 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Identity/AuthData.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Authorizations/AuthData.cs @@ -1,6 +1,6 @@ using OpenIddict.Server.AspNetCore; -namespace Calabonga.Microservice.Module.Web.Definitions.Identity; +namespace Calabonga.Microservice.Module.Web.Definitions.Authorizations; public static class AuthData { diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Identity/AuthorizationDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Authorizations/AuthorizationDefinition.cs similarity index 88% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Identity/AuthorizationDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Authorizations/AuthorizationDefinition.cs index f81e0fd4..03343b0b 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Identity/AuthorizationDefinition.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Authorizations/AuthorizationDefinition.cs @@ -7,7 +7,7 @@ using OpenIddict.Server.AspNetCore; using System.Text.Json; -namespace Calabonga.Microservice.Module.Web.Definitions.Identity; +namespace Calabonga.Microservice.Module.Web.Definitions.Authorizations; /// /// Authorization Policy registration @@ -63,7 +63,7 @@ public override void ConfigureServices(WebApplicationBuilder builder) if (context.AuthenticateFailure != null && context.AuthenticateFailure.GetType() == typeof(SecurityTokenExpiredException)) { var authenticationException = context.AuthenticateFailure as SecurityTokenExpiredException; - context.Response.Headers.Add("x-token-expired", authenticationException?.Expires.ToString("o")); + context.Response.Headers.Append("x-token-expired", authenticationException?.Expires.ToString("o")); context.ErrorDescription = $"The token expired on {authenticationException?.Expires:o}"; } @@ -76,14 +76,7 @@ public override void ConfigureServices(WebApplicationBuilder builder) }; }); - builder.Services.AddAuthorization(options => - { - options.AddPolicy(AuthData.AuthSchemes, policy => - { - policy.RequireAuthenticatedUser(); - policy.RequireClaim("scope", "api"); - }); - }); + builder.Services.AddAuthorization(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); @@ -93,15 +86,14 @@ public override void ConfigureServices(WebApplicationBuilder builder) /// Configure application for current microservice /// /// - /// public override void ConfigureApplication(WebApplication app) { app.UseRouting(); - app.UseCors(AppData.PolicyName); + app.UseCors(AppData.CorsPolicyName); app.UseAuthentication(); app.UseAuthorization(); // registering UserIdentity helper as singleton UserIdentity.Instance.Configure(app.Services.GetService()!); } -} \ No newline at end of file +} diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Identity/UserIdentity.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Authorizations/UserIdentity.cs similarity index 95% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Identity/UserIdentity.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Authorizations/UserIdentity.cs index fc8650d0..1a455bff 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Identity/UserIdentity.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Authorizations/UserIdentity.cs @@ -2,7 +2,7 @@ using System.Security.Claims; using System.Security.Principal; -namespace Calabonga.Microservice.Module.Web.Definitions.Identity; +namespace Calabonga.Microservice.Module.Web.Definitions.Authorizations; /// /// Identity helper for Requests operations diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Common/CommonDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Common/CommonDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Common/CommonDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Common/CommonDefinition.cs diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/CORS/CorsDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Cors/CorsDefinition.cs similarity index 80% rename from AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/CORS/CorsDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Cors/CorsDefinition.cs index 26c480b3..ac3f3026 100644 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/DEFINITIONS/CORS/CorsDefinition.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Cors/CorsDefinition.cs @@ -1,7 +1,7 @@ using Calabonga.AspNetCore.AppDefinitions; -using $ext_projectname$.Domain.Base; +using Calabonga.Microservice.Module.Domain.Base; -namespace $safeprojectname$.Definitions.Cors; +namespace Calabonga.Microservice.Module.Web.Definitions.Cors; /// /// Cors configurations @@ -14,13 +14,14 @@ public class CorsDefinition : AppDefinition /// public override void ConfigureServices(WebApplicationBuilder builder) { - var origins = builder.Configuration.GetSection("Cors")?.GetSection("Origins")?.Value?.Split(','); + var origins = builder.Configuration.GetSection("Cors").GetSection("Origins").Value?.Split(','); builder.Services.AddCors(options => { - options.AddPolicy(AppData.PolicyName, policyBuilder => + options.AddPolicy(AppData.CorsPolicyName, policyBuilder => { policyBuilder.AllowAnyHeader(); policyBuilder.AllowAnyMethod(); + if (origins is not { Length: > 0 }) { return; @@ -43,4 +44,4 @@ public override void ConfigureServices(WebApplicationBuilder builder) }); }); } -} \ No newline at end of file +} diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/DataSeeding/DataSeedingDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/DataSeeding/DataSeedingDefinition.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/DataSeeding/DataSeedingDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/DataSeeding/DataSeedingDefinition.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/DbContext/DbContextDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/DbContext/DbContextDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/DbContext/DbContextDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/DbContext/DbContextDefinition.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/ETagGenerator/ETagGeneratorDefinition.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/ErrorHandling/ErrorHandlingDefinition.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/FluentValidating/FluentValidationDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/FluentValidating/FluentValidationDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/FluentValidating/FluentValidationDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/FluentValidating/FluentValidationDefinition.cs diff --git a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/APPLICATION/ValidatorBehavior.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/FluentValidating/ValidatorBehavior.cs similarity index 86% rename from AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/APPLICATION/ValidatorBehavior.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/FluentValidating/ValidatorBehavior.cs index c134f2e7..be2f7fcf 100644 --- a/AspNetCore v6.0/TemplateMicroserviceModuleMinV6/Calabonga.Microservice.Module.Web/APPLICATION/ValidatorBehavior.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/FluentValidating/ValidatorBehavior.cs @@ -1,7 +1,7 @@ using FluentValidation; using MediatR; -namespace $safeprojectname$.Application; +namespace Calabonga.Microservice.Module.Web.Definitions.FluentValidating; /// /// Base validator for requests @@ -30,12 +30,8 @@ public Task Handle(TRequest request, RequestHandlerDelegate x != null) .ToList(); - if (!failures.Any()) - { - return next(); - } - - // return new ProblemDetails(); - throw new ValidationException(failures); + return failures.Any() + ? throw new ValidationException(failures) + : next(); } } \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mapping/AutomapperDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mapping/AutomapperDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mapping/AutomapperDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mapping/AutomapperDefinition.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mapping/PagedListConverter.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mapping/PagedListConverter.cs similarity index 93% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mapping/PagedListConverter.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mapping/PagedListConverter.cs index 1850b889..c37b6a38 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mapping/PagedListConverter.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mapping/PagedListConverter.cs @@ -1,5 +1,5 @@ using AutoMapper; -using Calabonga.UnitOfWork; +using Calabonga.PagedListCore; namespace Calabonga.Microservice.Module.Web.Definitions.Mapping; @@ -19,5 +19,5 @@ public IPagedList Convert(IPagedList? source, IPagedList() - : PagedList.From(source, items => context.Mapper.Map>(items)); + : PagedList.From(source, items => context.Mapper.Map>(items)!); } \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/Base/UnitOfWorkTransactionBehavior.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/LogPostTransaction.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/LogPostTransaction.cs similarity index 84% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/LogPostTransaction.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/LogPostTransaction.cs index d7c804a7..790b9019 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/LogPostTransaction.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/LogPostTransaction.cs @@ -6,7 +6,7 @@ namespace Calabonga.Microservice.Module.Web.Definitions.Mediator; -public class LogPostTransactionBehavior : TransactionBehavior>, OperationResult> +public class LogPostTransactionBehavior : TransactionBehavior>, Operation> { public LogPostTransactionBehavior(IUnitOfWork unitOfWork) : base(unitOfWork) { } } \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/MediatorDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/MediatorDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/MediatorDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/Mediator/MediatorDefinition.cs diff --git a/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenApi/OAuth2SecuritySchemeTransformer.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenApi/OAuth2SecuritySchemeTransformer.cs new file mode 100644 index 00000000..da29f55b --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenApi/OAuth2SecuritySchemeTransformer.cs @@ -0,0 +1,65 @@ +using Calabonga.Microservice.Module.Domain.Base; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.OpenApi; +using Microsoft.OpenApi.Models; +using OpenIddict.Server.AspNetCore; + +namespace Calabonga.Microservice.Module.Web.Definitions.OpenApi; + +/// +/// Swagger security configuration scheme +/// +public sealed class OAuth2SecuritySchemeTransformer : IOpenApiDocumentTransformer +{ + private readonly IAuthenticationSchemeProvider _authenticationSchemeProvider; + private readonly string? _authServerUrl; + + public OAuth2SecuritySchemeTransformer(IAuthenticationSchemeProvider authenticationSchemeProvider, IConfiguration configuration) + { + _authenticationSchemeProvider = authenticationSchemeProvider; + _authServerUrl = configuration.GetSection("AuthServer").GetValue("Url"); + + ArgumentNullException.ThrowIfNull(_authServerUrl); + } + + public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken) + { + var authenticationSchemes = await _authenticationSchemeProvider.GetAllSchemesAsync(); + if (authenticationSchemes.Any(authScheme => authScheme.Name == OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)) + { + var reference = new OpenApiReference() { Id = "oauth2", Type = ReferenceType.SecurityScheme }; + var scheme = new OpenApiSecurityScheme + { + Reference = reference, + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows + { + AuthorizationCode = new OpenApiOAuthFlow + { + TokenUrl = new Uri($"{_authServerUrl}/connect/token", UriKind.Absolute), + AuthorizationUrl = new Uri($"{_authServerUrl}/connect/authorize", UriKind.Absolute), + Scopes = new Dictionary { { "api", "Default scope" } } + } + } + }; + + var requirement = new OpenApiSecurityRequirement + { + { new OpenApiSecurityScheme { Reference = reference, In = ParameterLocation.Cookie, Type = SecuritySchemeType.OAuth2 }, new List() } + }; + + document.Components ??= new OpenApiComponents(); + document.Components.SecuritySchemes ??= new Dictionary(); + document.SecurityRequirements = [requirement]; + document.Components.SecuritySchemes[scheme.Reference.Id] = scheme; + document.Info = new() + { + License = new OpenApiLicense() { Name = "MIT", Url = new Uri("https://mit-license.org/") }, + Title = AppData.ServiceName, + Version = OpenApiDefinition.AppVersion, + Description = AppData.ServiceDescription, + Contact = new() { Name = "Sergei Calabonga", Url = new("https://www.calabonga.net"), } + }; + } + } +} diff --git a/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenApi/OpenApiDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenApi/OpenApiDefinition.cs new file mode 100644 index 00000000..1d36d7c9 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenApi/OpenApiDefinition.cs @@ -0,0 +1,63 @@ +using Calabonga.AspNetCore.AppDefinitions; +using Calabonga.Microservice.Module.Domain.Base; +using Microsoft.AspNetCore.Mvc; +using Swashbuckle.AspNetCore.SwaggerUI; + +namespace Calabonga.Microservice.Module.Web.Definitions.OpenApi; + +/// +/// Swagger definition for application +/// +public class OpenApiDefinition : AppDefinition +{ + // ATTENTION! + // If you use are git repository then you can uncomment line with "ThisAssembly" below for versioning by GIT possibilities. + // Otherwise, you can change versions of your API by manually. + // If you are not going to use git-versioning, do not forget install package "GitInfo" + // private const string AppVersion = $"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"; + public const string AppVersion = "9.0.0"; + + private const string _openApiConfig = "/openapi/v1.json"; + + public override void ConfigureServices(WebApplicationBuilder builder) + { + builder.Services.Configure(options => { options.SuppressModelStateInvalidFilter = true; }); + builder.Services.AddEndpointsApiExplorer(); + builder.Services.AddOpenApi(options => + { + options.AddDocumentTransformer(); + }); + } + + public override void ConfigureApplication(WebApplication app) + { + if (!app.Environment.IsDevelopment()) + { + return; + } + + var url = app.Services.GetRequiredService().GetValue("AuthServer:Url"); + + app.MapOpenApi(); + + app.UseSwaggerUI(settings => + { + settings.SwaggerEndpoint(_openApiConfig, $"{AppData.ServiceName} v.{AppVersion}"); + + // ATTENTION! + // If you use are git repository then you can uncomment line with "ThisAssembly" below for versioning by GIT possibilities. + // settings.HeadContent = $"{ThisAssembly.Git.Branch.ToUpper()} {ThisAssembly.Git.Commit.ToUpper()}"; + + settings.DocumentTitle = $"{AppData.ServiceName}"; + settings.DefaultModelExpandDepth(0); + settings.DefaultModelRendering(ModelRendering.Model); + settings.DefaultModelsExpandDepth(0); + settings.DocExpansion(DocExpansion.None); + settings.OAuthScopeSeparator(" "); + settings.OAuthClientId("client-id-code"); + settings.OAuthClientSecret("client-secret-code"); + settings.DisplayRequestDuration(); + settings.OAuthAppName(AppData.ServiceName); + }); + } +} diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AppPermissionHandler.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AppPermissionHandler.cs similarity index 95% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AppPermissionHandler.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AppPermissionHandler.cs index afb91ae1..f258fad2 100644 --- a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AppPermissionHandler.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AppPermissionHandler.cs @@ -1,4 +1,4 @@ -using Calabonga.Microservices.Core; +using Calabonga.Utils.Extensions; using Microsoft.AspNetCore.Authorization; using System.Security.Claims; diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/AuthorizationPolicyProvider.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/OpenIddictDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/OpenIddictDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/OpenIddictDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/OpenIddictDefinition.cs diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/PermissionRequirement.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/PermissionRequirement.cs similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/PermissionRequirement.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/OpenIddict/PermissionRequirement.cs diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/UoW/UnitOfWorkDefinition.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/UoW/UnitOfWorkDefinition.cs similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/UoW/UnitOfWorkDefinition.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Definitions/UoW/UnitOfWorkDefinition.cs diff --git a/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Endpoints/EventItemEndpoints.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Endpoints/EventItemEndpoints.cs new file mode 100644 index 00000000..1748708e --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Endpoints/EventItemEndpoints.cs @@ -0,0 +1,61 @@ +using Calabonga.AspNetCore.AppDefinitions; +using Calabonga.Microservice.Module.Domain; +using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.Queries; +using Calabonga.Microservice.Module.Web.Application.Messaging.EventItemMessages.ViewModels; +using Calabonga.Microservice.Module.Web.Definitions.Authorizations; +using MediatR; +using Microsoft.AspNetCore.Mvc; + +namespace Calabonga.Microservice.Module.Web.Endpoints; + +public sealed class EventItemEndpoints : AppDefinition +{ + public override void ConfigureApplication(WebApplication app) => app.MapEventItemEndpoints(); +} + +internal static class EventItemEndpointsExtensions +{ + public static void MapEventItemEndpoints(this IEndpointRouteBuilder routes) + { + var group = routes.MapGroup("/api/event-items/").WithTags(nameof(EventItem)); + + group.MapGet("paged/{pageIndex:int}", async ([FromServices] IMediator mediator, string? search, HttpContext context, int pageIndex = 0, int pageSize = 10) + => await mediator.Send(new GetEventItemPaged.Request(pageIndex, pageSize, search), context.RequestAborted)) + .RequireAuthorization(x => x.AddAuthenticationSchemes(AuthData.AuthSchemes).RequireAuthenticatedUser()) + .Produces(200) + .ProducesProblem(401) + .ProducesProblem(404) + .WithOpenApi(); + + group.MapGet("{id:guid}", async ([FromServices] IMediator mediator, Guid id, HttpContext context) + => await mediator.Send(new GetEventItemById.Request(id), context.RequestAborted)) + .RequireAuthorization(x => x.AddAuthenticationSchemes(AuthData.AuthSchemes).RequireAuthenticatedUser()) + .Produces(200) + .ProducesProblem(401) + .ProducesProblem(404) + .WithOpenApi(); + + group.MapDelete("{id:guid}", async ([FromServices] IMediator mediator, Guid id, HttpContext context) + => await mediator.Send(new DeleteEventItem.Request(id), context.RequestAborted)) + .RequireAuthorization(x => x.AddAuthenticationSchemes(AuthData.AuthSchemes).RequireAuthenticatedUser()) + .Produces(200) + .ProducesProblem(401) + .ProducesProblem(404) + .WithOpenApi(); + + group.MapPost("", async ([FromServices] IMediator mediator, EventItemCreateViewModel model, HttpContext context) + => await mediator.Send(new PostEventItem.Request(model), context.RequestAborted)) + .RequireAuthorization(x => x.AddAuthenticationSchemes(AuthData.AuthSchemes).RequireAuthenticatedUser()) + .Produces(200) + .ProducesProblem(401) + .ProducesProblem(404) + .WithOpenApi(); + + group.MapPut("{id:guid}", async ([FromServices] IMediator mediator, Guid id, EventItemUpdateViewModel model, HttpContext context) + => await mediator.Send(new PutEventItem.Request(id, model), context.RequestAborted)) + .Produces(200) + .ProducesProblem(401) + .ProducesProblem(404) + .WithOpenApi(); + } +} diff --git a/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Endpoints/ProfilesEndpoint.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Endpoints/ProfilesEndpoint.cs new file mode 100644 index 00000000..96699f63 --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Endpoints/ProfilesEndpoint.cs @@ -0,0 +1,31 @@ +using Calabonga.AspNetCore.AppDefinitions; +using Calabonga.Microservice.Module.Web.Application.Messaging.ProfileMessages.Queries; +using Calabonga.Microservice.Module.Web.Definitions.Authorizations; +using MediatR; +using Microsoft.AspNetCore.Mvc; + +namespace Calabonga.Microservice.Module.Web.Endpoints; + +public sealed class ProfilesEndpointDefinition : AppDefinition +{ + public override void ConfigureApplication(WebApplication app) + => app.MapProfilesEndpoints(); +} + +internal static class ProfilesEndpointDefinitionExtensions +{ + public static void MapProfilesEndpoints(this IEndpointRouteBuilder routes) + { + var group = routes.MapGroup("/api/profiles").WithTags("Profiles"); + + group.MapGet("roles", async ([FromServices] IMediator mediator, HttpContext context) + => await mediator.Send(new GetProfile.Request(), context.RequestAborted)) + .RequireAuthorization(x => + x.AddAuthenticationSchemes(AuthData.AuthSchemes) + .RequireAuthenticatedUser() + .RequireClaim("Profiles:Roles:Get")) + .Produces(200) + .ProducesProblem(401) + .WithOpenApi(); + } +} \ No newline at end of file diff --git a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/Program.cs b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Program.cs similarity index 88% rename from AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/Program.cs rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Program.cs index 9f871736..a931a1d8 100644 --- a/AspNetCore v7.0/TemplateModule/Calabonga.Microservice.Module.Web/Program.cs +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Program.cs @@ -2,23 +2,23 @@ // Name: Template for Micro service on ASP.NET Core API with // OpenIddict (OAuth2.0) // Author: Calabonga © 2005-2023 Calabonga SOFT -// Version: 7.0.6 -// Based on: .NET 7.0.x -// Created Date: 2022-11-12 09:29 -// Updated Date: 2023-08-04 09:58 +// Version: 8.0.6 +// Based on: .NET 8.0.x +// Created Date: 2023-11-19 +// Updated Date: 2024-07-23 // -------------------------------------------------------------------- // Contacts // -------------------------------------------------------------------- // Donate: https://boosty.to/calabonga/donate -// Blog: https://www.calabonga.net/blog/post/nimble-framework-7 +// Blog: https://www.calabonga.net // GitHub: https://github.com/Calabonga/Microservice-Template -// BoostyTo: https://boosty.to/calabonga +// Boosty: https://boosty.to/calabonga // YouTube: https://youtube.com/sergeicalabonga // DZen: https://dzen.ru/calabonga // -------------------------------------------------------------------- // Description: // -------------------------------------------------------------------- -// Minimal API for NET7 used with Definitions. +// Minimal API for NET8 used with Definitions. // This template implements Web API and OpenIddict (OAuth2.0) // functionality. Also, support two type of Authentication: // Cookie and Bearer @@ -68,7 +68,7 @@ } Log.Fatal(ex, "Unhandled exception"); - return 1; + throw; } finally { diff --git a/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Properties/launchSettings.json b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Properties/launchSettings.json new file mode 100644 index 00000000..66f08d0c --- /dev/null +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/Properties/launchSettings.json @@ -0,0 +1,13 @@ +{ + "profiles": { + "Kestrel": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "https://localhost:20001" + } + } +} \ No newline at end of file diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.Development.json b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.Development.json similarity index 95% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.Development.json rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.Development.json index f8299029..ec6c2967 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.Development.json +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.Development.json @@ -17,7 +17,7 @@ { "Name": "File", "Args": { - "path": "/logs/log-.log", + "path": "logs/log-.log", "rollingInterval": "Day", "rollOnFileSizeLimit": true, "shared": true, diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.Production.json b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.Production.json similarity index 91% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.Production.json rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.Production.json index 200d96aa..51626176 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.Production.json +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.Production.json @@ -5,7 +5,7 @@ "Serilog": { "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], "MinimumLevel": { - "Default": "Debug", + "Default": "Information", "Override": { "Microsoft": "Warning", "System": "Warning", @@ -17,7 +17,7 @@ { "Name": "File", "Args": { - "path": "/logs/log-.log", + "path": "logs/log-.log", "rollingInterval": "Day", "rollOnFileSizeLimit": true, "shared": true, diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.json b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.json similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.json rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/appsettings.json diff --git a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/readme.md b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/readme.md similarity index 70% rename from AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/readme.md rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/readme.md index 6020f1a2..441230f0 100644 --- a/AspNetCore v7.0/TemplateIdentityModule/Calabonga.Microservice.IdentityModule.Web/readme.md +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/readme.md @@ -1,18 +1,19 @@ # Attentions -Please find out all comments with 'ATTENTION!' because that is required some decisions from you +Please find out all comments with 'ATTENTION!' because that is required some decisions from you. # About | Name | Description | | ------------ | ------------------------------------------ | | Name | Microservice Template for ASP.NET Core API | -| Author | Calabonga SOFT © 2005-2023 Calabonga SOFT | -| Created Date | 2019-04-13 3:28:39 PM | +| Author | Calabonga SOFT © 2005-2024 Calabonga SOFT | +| Created Date | 2024-11-26 | +| Create From | Microservice-Template NET8.0 | # Versions -Nimble Framework Templates build on .NET 7.0. That`s why it have the same major version. But the all improvements will increment minor versions. +Nimble Framework Templates build on .NET 9.0. That`s why it have the same major version. But the all improvements will increment minor versions. # Contacts @@ -26,4 +27,4 @@ You can contact me by using the next opportunities: # Description: -This template implements Web API functionality using minimal API feature from NET 7.0 \ No newline at end of file +This template implements Web API functionality using minimal API feature from NET 9.0 \ No newline at end of file diff --git a/AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/tempkey.jwk b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/tempkey.jwk similarity index 100% rename from AspNetCore v6.0/Calabonga.Microservice.Module/Calabonga.Microservice.Module.Web/tempkey.jwk rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.Web/tempkey.jwk diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.sln b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.sln similarity index 91% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.sln rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.sln index d2d35476..8de79c28 100644 --- a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.sln +++ b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/content/Calabonga.Microservice.Module.sln @@ -3,11 +3,11 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31912.275 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Calabonga.Microservice.Module.Domain", "Calabonga.Microservice.Module.Domain\Calabonga.Microservice.Module.Domain.csproj", "{2DA97A11-5594-406B-8216-F46B29B41BF4}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.Module.Domain", "Calabonga.Microservice.Module.Domain\Calabonga.Microservice.Module.Domain.csproj", "{2DA97A11-5594-406B-8216-F46B29B41BF4}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Calabonga.Microservice.Module.Infrastructure", "Calabonga.Microservice.Module.Infrastructure\Calabonga.Microservice.Module.Infrastructure.csproj", "{62AC64BB-F04B-445C-83A6-94C491C8F897}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.Module.Infrastructure", "Calabonga.Microservice.Module.Infrastructure\Calabonga.Microservice.Module.Infrastructure.csproj", "{62AC64BB-F04B-445C-83A6-94C491C8F897}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Calabonga.Microservice.Module.Web", "Calabonga.Microservice.Module.Web\Calabonga.Microservice.Module.Web.csproj", "{9D94187D-B284-4069-8AC4-AEBD4D633A35}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Calabonga.Microservice.Module.Web", "Calabonga.Microservice.Module.Web\Calabonga.Microservice.Module.Web.csproj", "{9D94187D-B284-4069-8AC4-AEBD4D633A35}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/AspNetCore v7.0/Calabonga.Microservice.Module.Template/logo.png b/AspNetCore v9.0/Calabonga.Microservice.Module.Template/logo.png similarity index 100% rename from AspNetCore v7.0/Calabonga.Microservice.Module.Template/logo.png rename to AspNetCore v9.0/Calabonga.Microservice.Module.Template/logo.png diff --git a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider.sln b/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider.sln deleted file mode 100644 index fa69c718..00000000 --- a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider.sln +++ /dev/null @@ -1,25 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.31903.59 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Calabonga.Microservice.TemplateBuilder", "Calabonga.Microservice.TemplateBuider\Calabonga.Microservice.TemplateBuilder.csproj", "{610AF7DA-6505-45BA-AA2C-7B0CA1B8175E}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {610AF7DA-6505-45BA-AA2C-7B0CA1B8175E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {610AF7DA-6505-45BA-AA2C-7B0CA1B8175E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {610AF7DA-6505-45BA-AA2C-7B0CA1B8175E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {610AF7DA-6505-45BA-AA2C-7B0CA1B8175E}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {4E2E3E78-FAF3-45CC-85C0-B9BD3DD93E1C} - EndGlobalSection -EndGlobal diff --git a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuilder.csproj b/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuilder.csproj deleted file mode 100644 index b0d414a9..00000000 --- a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuilder.csproj +++ /dev/null @@ -1,36 +0,0 @@ - - - - Exe - net6.0 - disable - enable - true - true - win-x64 - true - - - - - - - - - - - - - - - Always - - - Always - - - Always - - - - diff --git a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/DataManager.cs b/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/DataManager.cs deleted file mode 100644 index faacb70f..00000000 --- a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/DataManager.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Serilog; - -namespace Calabonga.Microservice.TemplateBuilder -{ - public class DataManager - { - private readonly SemaphoreSlim _gate = new(1); - private readonly TemplateOptions _templateOptions; - private readonly FileService _fileService; - private readonly ReadWriteService _readWriteService; - private readonly ReplaceService _replaceService; - private readonly ConcurrentBag _results = new(); - - public DataManager( - TemplateOptions templateOptions, - FileService fileService, - ReadWriteService readWriteService, - ReplaceService replaceService) - { - _templateOptions = templateOptions; - _fileService = fileService; - _readWriteService = readWriteService; - _replaceService = replaceService; - } - - public async Task BuildAsync() - { - var items = LoadItemsFromRootPath(); - Log.Logger.Information($"Total {items.Count} items found"); - - var cancellationTokenSource = new CancellationTokenSource(); - var tasks = CreateTasks(items, cancellationTokenSource.Token).ToArray(); - await Task.WhenAll(tasks); - _replaceService.Replace(_results, _templateOptions, cancellationTokenSource.Token); - Log.Logger.Information($"Processing done ({_results.Sum(x => x.Length)} bytes)"); - - foreach (var result in _results) - { - await _readWriteService.SaveDataAsync(result.FileName, result.Replaced, cancellationTokenSource.Token); - } - } - - private IEnumerable CreateTasks(List items, CancellationToken cancellationToken = default) - { - return items.Select(item => LoadFileDataAsync(item, cancellationToken)); - } - - private async Task LoadFileDataAsync(string fileNameWithPath, CancellationToken cancellationToken = default) - { - try - { - await _gate.WaitAsync(cancellationToken); - var data = await _readWriteService.LoadDataAsync(fileNameWithPath, cancellationToken); - var loadedData = new FileData - { - FileName = fileNameWithPath, - FileExtension = Path.GetExtension(fileNameWithPath), - Content = data, - Length = data.Length - }; - _results.Add(loadedData); - Log.Logger.Information($"Loading {loadedData.ToString()}"); - _gate.Release(); - } - catch (Exception exception) - { - Log.Logger.Error(JsonSerializer.Serialize(exception)); - throw; - } - } - - private List LoadItemsFromRootPath() - { - var items = _fileService.ProcessFolder(_templateOptions.RootDirectoryPath, _templateOptions); - if (items.Length == 0) - { - Log.Logger.Information("Nothing to replace"); - return new(); - } - - return items.ToList(); - } - } - - public class FileData - { - public string Content { get; set; } = null!; - - public string FileName { get; set; } = null!; - - public string FileExtension { get; set; } = null!; - - public int Length { get; set; } - - public string Replaced { get; set; } = null!; - - /// Returns a string that represents the current object. - /// A string that represents the current object. - public override string ToString() => $"{FileName} ({Length} bytes)"; - } -} diff --git a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/FileService.cs b/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/FileService.cs deleted file mode 100644 index 15faf8bf..00000000 --- a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/FileService.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; - -namespace Calabonga.Microservice.TemplateBuilder -{ - public class FileService - { - private readonly List _files; - public FileService() - { - - _files = new List(); - } - - public string[] ProcessFolder(string path, TemplateOptions options) - { - foreach (var pattern in options.PatternDefinitions.DistinctBy(x => x.FileExtension)) - { - var files = Directory.GetFiles(path, $"*{pattern.FileExtension}", SearchOption.AllDirectories); - if (files.Any()) - { - _files.AddRange(files); - } - } - - return _files.ToArray(); - } - } -} diff --git a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/FileServiceOptions.cs b/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/FileServiceOptions.cs deleted file mode 100644 index 4a2ab98a..00000000 --- a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/FileServiceOptions.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Calabonga.Microservice.TemplateBuilder -{ - public class PatternDefinition - { - public string FileExtension { get; set; } = null!; - - public string ContentType { get; set; } = null!; - - public string SearchTextForReplace { get; set; } = null!; - - public string ReplaceTextWith { get; set; } = null!; - } -} diff --git a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/MicroserviceTemplates.cs b/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/MicroserviceTemplates.cs deleted file mode 100644 index f9812274..00000000 --- a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/MicroserviceTemplates.cs +++ /dev/null @@ -1,8 +0,0 @@ -using System.Collections.Generic; - -namespace Calabonga.Microservice.TemplateBuilder; - -public class MicroserviceTemplates -{ - public List TemplateOptions { get; set; } = null!; -} \ No newline at end of file diff --git a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/Program.cs b/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/Program.cs deleted file mode 100644 index daffd242..00000000 --- a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/Program.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text.Json; -using System.Threading.Tasks; -using Microsoft.Extensions.Configuration; -using Serilog; - -namespace Calabonga.Microservice.TemplateBuilder -{ - class Program - { - public static async Task Main(string[] args) - { - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Verbose() - .WriteTo.Console() - .WriteTo.File("Application.log") - .CreateLogger(); - - Log.Logger.Information("Microservice Template Builder v.1.0.0-beta2"); - - var configFile = args.Any() ? args[0] : "appsettings.json"; - - if (string.IsNullOrWhiteSpace(configFile)) - { - Log.Logger.Information("appSettings.json file not provided."); - //return; - } - Log.Logger.Information("Using application settings from: {0}", configFile); - Log.Logger.Information("Building configuration from {0}", configFile); - var configuration = new ConfigurationBuilder() - .AddJsonFile(configFile, optional: false) - .Build(); - - var projectsTemplates = configuration.Get(); - - if (projectsTemplates is null) - { - Log.Logger.Information("{0} file not provided or configuration wrong.", configFile); - return; - } - - await RunProcessAsync(projectsTemplates.TemplateOptions); - } - - private static async Task RunProcessAsync(List templates) - { - foreach (var projectsTemplate in templates) - { - Log.Logger.Information($"Processing templates for {projectsTemplate.ProjectName}"); - var templatePath = projectsTemplate.RootDirectoryPath; - Log.Logger.Information($"Processing path: {templatePath}"); - - var directory = Directory.Exists(templatePath) ? new DirectoryInfo(templatePath) : null; - - if (directory is null) - { - Log.Logger.Information("No directory was found"); - return; - } - - var projects = directory.GetDirectories(); - if (!projects.Any()) - { - Log.Logger.Information("No projects folder were found"); - return; - } - - // prepare manager - var loadService = new ReadWriteService(); - var replaceService = new ReplaceService(); - var fileService = new FileService(); - var manager = new DataManager(projectsTemplate, fileService, loadService, replaceService); - - // run build process - await manager.BuildAsync(); - - Log.Logger.Information("Work completed"); - } - } - } -} \ No newline at end of file diff --git a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/ReadWriteService.cs b/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/ReadWriteService.cs deleted file mode 100644 index e3085bc2..00000000 --- a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/ReadWriteService.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.IO; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace Calabonga.Microservice.TemplateBuilder -{ - public class ReadWriteService - { - public Task LoadDataAsync(string fileNameWithPath, CancellationToken cancellationToken = default) - { - try - { - return File.ReadAllTextAsync(fileNameWithPath, Encoding.UTF8, cancellationToken); - - } - catch (Exception exception) - { - Console.WriteLine(exception.Message); - return Task.FromResult(string.Empty); - } - } - - public Task SaveDataAsync(string fileNameWithPath, string? content, CancellationToken cancellationToken = default) - { - try - { - return File.WriteAllTextAsync(fileNameWithPath, content, Encoding.UTF8, cancellationToken); - - } - catch (Exception exception) - { - Console.WriteLine(exception.Message); - return Task.FromResult(string.Empty); - } - } - } -} diff --git a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/ReplaceService.cs b/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/ReplaceService.cs deleted file mode 100644 index b5ee2df7..00000000 --- a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/ReplaceService.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Collections.Concurrent; -using System.IO; -using System.Linq; -using System.Threading; -using Serilog; - -namespace Calabonga.Microservice.TemplateBuilder -{ - public class ReplaceService - { - public void Replace(ConcurrentBag results, TemplateOptions templateOptions, CancellationToken token) - { - foreach (var option in templateOptions.PatternDefinitions) - { - foreach (var item in results.Where(x => x.FileExtension.Equals(option.FileExtension))) - { - Log.Logger.Verbose($"BEFORE REPLACE {Path.GetFileName(item.FileName)}"); - Log.Logger.Verbose(item.Content); - if (string.IsNullOrEmpty(item.Replaced)) - { - var replaced = item.Content.Replace(option.SearchTextForReplace, option.ReplaceTextWith); - item.Replaced = replaced; - } - else - { - var replaced = item.Replaced.Replace(option.SearchTextForReplace, option.ReplaceTextWith); - item.Replaced = replaced; - } - Log.Logger.Verbose($"AFTER REPLACE {Path.GetFileName(item.FileName)}"); - Log.Logger.Verbose(item.Replaced); - } - } - } - } -} diff --git a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/TemplateOptions.cs b/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/TemplateOptions.cs deleted file mode 100644 index f7413ead..00000000 --- a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/TemplateOptions.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Collections.Generic; - -namespace Calabonga.Microservice.TemplateBuilder; - -public class TemplateOptions -{ - public List PatternDefinitions { get; set; } = new(); - - public string RootDirectoryPath { get; set; } = null!; - - public string ProjectName { get; set; } = null!; -} \ No newline at end of file diff --git a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/appsettings.json b/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/appsettings.json deleted file mode 100644 index e0f28777..00000000 --- a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/appsettings.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "Name": "THis is The name" -} - -//{ -// "TemplateOptions": [ -// { -// "ProjectName": "Calabonga.Microservice.IdentityModule", -// "PatternDefinitions": [ -// { -// "FileExtension": ".cs", -// "ContentType": "Csharp file", -// "SearchTextForReplace": "using Calabonga.Microservice.IdentityModule", -// "ReplaceTextWith": "using $ext_projectname$" -// }, -// { -// "FileExtension": ".csproj", -// "ContentType": "Project file", -// "SearchTextForReplace": "Calabonga.Microservice.IdentityModule.", -// "ReplaceTextWith": "$ext_projectname$." -// } -// ], -// "RootDirectoryPath": "D:\\Projects\\MicroserviceTemplate\\AspNetCore v6.0\\FullAPI\\TemplateMicroserviceIdentityModuleV6" -// }, -// { -// "ProjectName": "Calabonga.Microservice.Module", -// "PatternDefinitions": [ -// { -// "FileExtension": ".cs", -// "ContentType": "Csharp file", -// "SearchTextForReplace": "using Calabonga.Microservice.Module", -// "ReplaceTextWith": "using $ext_projectname$" -// }, -// { -// "FileExtension": ".csproj", -// "ContentType": "Project file", -// "SearchTextForReplace": "Calabonga.Microservice.Module.", -// "ReplaceTextWith": "$ext_projectname$." -// } -// ], -// "RootDirectoryPath": "D:\\Projects\\MicroserviceTemplate\\AspNetCore v6.0\\FullAPI\\TemplateMicroserviceModuleV6" -// } -// ] -//} diff --git a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/module-first.json b/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/module-first.json deleted file mode 100644 index 32f7b250..00000000 --- a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/module-first.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "TemplateOptions": [ - { - "PatternDefinitions": [ - { - "FileExtension": ".cs", - "ContentType": "Csharp file", - "SearchTextForReplace": "using Calabonga.Microservice.IdentityModule", - "ReplaceTextWith": "using $ext_projectname$" - }, - { - "FileExtension": ".csproj", - "ContentType": "Project file", - "SearchTextForReplace": "Calabonga.Microservice.IdentityModule.", - "ReplaceTextWith": "$ext_projectname$." - } - ], - "RootDirectoryPath": "C:\\Projects\\Microservice-Template\\AspNetCore v7.0\\TemplateIdentityModule", - "ProjectName": "Calabonga.Microservice.IdentityModule" - } - ] -} \ No newline at end of file diff --git a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/module-second.json b/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/module-second.json deleted file mode 100644 index 75cff482..00000000 --- a/Builder/Calabonga.Microservice.TemplateBuider/Calabonga.Microservice.TemplateBuider/module-second.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "TemplateOptions": [ - { - "PatternDefinitions": [ - { - "FileExtension": ".cs", - "ContentType": "Csharp file", - "SearchTextForReplace": "using Calabonga.Microservice.Module", - "ReplaceTextWith": "using $ext_projectname$" - }, - { - "FileExtension": ".csproj", - "ContentType": "Project file", - "SearchTextForReplace": "Calabonga.Microservice.Module.", - "ReplaceTextWith": "$ext_projectname$." - } - ], - "RootDirectoryPath": "C:\\Projects\\Microservice-Template\\AspNetCore v7.0\\TemplateModule", - "ProjectName": "Calabonga.Microservice.Module" - } - ] -} \ No newline at end of file diff --git a/Builder/readme.txt b/Builder/readme.txt deleted file mode 100644 index 1ef51fe2..00000000 --- a/Builder/readme.txt +++ /dev/null @@ -1 +0,0 @@ -dotnet publish -r win-x64 -c Release -p:PublishSingleFile=true --self-contained false \ No newline at end of file diff --git a/IdentityServer4Mvc/Controllers/IdentificationController.cs b/IdentityServer4Mvc/Controllers/IdentificationController.cs deleted file mode 100644 index 5009454c..00000000 --- a/IdentityServer4Mvc/Controllers/IdentificationController.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System.Threading.Tasks; - -using Calabonga.Microservice.IdentityModule.Data; -using Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels; -using IdentityServer4.Services; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Mvc; - -namespace Calabonga.Microservice.IdentityModule.Web.Controllers -{ - [AllowAnonymous] - [Route("[controller]")] - public class IdentificationController : Controller - { - private readonly IIdentityServerInteractionService _interaction; - private readonly SignInManager _signInManager; - private readonly UserManager _userManager; - - public IdentificationController( - IIdentityServerInteractionService interaction, - SignInManager signInManager, - UserManager userManager) - { - _interaction = interaction; - _signInManager = signInManager; - _userManager = userManager; - } - - [HttpGet("[action]")] - public async Task Login(string returnUrl) - { - return View(); - } - - [HttpPost("[action]")] - - public async Task Login(LoginViewModel model) - { - if (!ModelState.IsValid) - { - ModelState.AddModelError("", "Please. Validate your credentials and try again."); - return View(model); - } - - var user = await _userManager.FindByNameAsync(model.UserName); - if (user == null) - { - ModelState.AddModelError("UserName", "User not found"); - return View(model); - } - - var signResult = await _signInManager.PasswordSignInAsync(user, model.Password, false, false); - if (!signResult.Succeeded) - { - ModelState.AddModelError("", "Something went wrong"); - return View(model); - } - - return Redirect(model.ReturnUrl); - } - - [HttpGet("[action]")] - public async Task Logout(string logoutId) - { - var logout = await _interaction.GetLogoutContextAsync(logoutId); - await _signInManager.SignOutAsync(); - return Redirect(logout.PostLogoutRedirectUri); - } - } -} diff --git a/IdentityServer4Mvc/ViewModels/AccountViewModels/LoginViewModel.cs b/IdentityServer4Mvc/ViewModels/AccountViewModels/LoginViewModel.cs deleted file mode 100644 index 22b8dbe4..00000000 --- a/IdentityServer4Mvc/ViewModels/AccountViewModels/LoginViewModel.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels -{ - public class LoginViewModel - { - [Required] - public string UserName { get; set; } - - [Required] - public string Password { get; set; } - - [Required] - public string ReturnUrl { get; set; } - } -} diff --git a/IdentityServer4Mvc/Views/Identification/Login.cshtml b/IdentityServer4Mvc/Views/Identification/Login.cshtml deleted file mode 100644 index b66140aa..00000000 --- a/IdentityServer4Mvc/Views/Identification/Login.cshtml +++ /dev/null @@ -1,28 +0,0 @@ -@model Calabonga.Microservice.IdentityModule.Web.ViewModels.AccountViewModels.LoginViewModel - -
- -
- -

Enter zone

- -
- - - -
- - -
- -
- - -
-

- -

- -
-
-
\ No newline at end of file diff --git a/IdentityServer4Mvc/Views/Shared/_Layout.cshtml b/IdentityServer4Mvc/Views/Shared/_Layout.cshtml deleted file mode 100644 index afcade1e..00000000 --- a/IdentityServer4Mvc/Views/Shared/_Layout.cshtml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - @ViewBag.Title - - - -
- @RenderBody() -
- - - - - - diff --git a/IdentityServer4Mvc/Views/_ViewImports.cshtml b/IdentityServer4Mvc/Views/_ViewImports.cshtml deleted file mode 100644 index e0f0985e..00000000 --- a/IdentityServer4Mvc/Views/_ViewImports.cshtml +++ /dev/null @@ -1 +0,0 @@ -@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers \ No newline at end of file diff --git a/IdentityServer4Mvc/Views/_ViewStart.cshtml b/IdentityServer4Mvc/Views/_ViewStart.cshtml deleted file mode 100644 index a5f10045..00000000 --- a/IdentityServer4Mvc/Views/_ViewStart.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@{ - Layout = "_Layout"; -} diff --git a/Output/v3.1.x/TemplateMicroserviceIdentityModuleV3_2.2.0.zip b/Output/v3.1.x/TemplateMicroserviceIdentityModuleV3_2.2.0.zip deleted file mode 100644 index 34944bbe..00000000 Binary files a/Output/v3.1.x/TemplateMicroserviceIdentityModuleV3_2.2.0.zip and /dev/null differ diff --git a/Output/v3.1.x/TemplateMicroserviceModuleV3_2.2.0.zip b/Output/v3.1.x/TemplateMicroserviceModuleV3_2.2.0.zip deleted file mode 100644 index 7300a95f..00000000 Binary files a/Output/v3.1.x/TemplateMicroserviceModuleV3_2.2.0.zip and /dev/null differ diff --git a/Output/v6.1.x/TemplateMicroserviceIdentityModuleMinV6.1.4.zip b/Output/v6.1.x/TemplateMicroserviceIdentityModuleMinV6.1.4.zip deleted file mode 100644 index 044a69de..00000000 Binary files a/Output/v6.1.x/TemplateMicroserviceIdentityModuleMinV6.1.4.zip and /dev/null differ diff --git a/Output/v6.1.x/TemplateMicroserviceModuleMinV6.1.2.zip b/Output/v6.1.x/TemplateMicroserviceModuleMinV6.1.2.zip deleted file mode 100644 index 2e628748..00000000 Binary files a/Output/v6.1.x/TemplateMicroserviceModuleMinV6.1.2.zip and /dev/null differ diff --git a/Output/v7.0.x/TemplateIdentityModule7.0.6.zip b/Output/v7.0.x/TemplateIdentityModule7.0.6.zip deleted file mode 100644 index 148eb306..00000000 Binary files a/Output/v7.0.x/TemplateIdentityModule7.0.6.zip and /dev/null differ diff --git a/Output/v7.0.x/TemplateModule7.0.6.zip b/Output/v7.0.x/TemplateModule7.0.6.zip deleted file mode 100644 index 51603c81..00000000 Binary files a/Output/v7.0.x/TemplateModule7.0.6.zip and /dev/null differ diff --git a/Output/v8.0.x/README.md b/Output/v8.0.x/README.md deleted file mode 100644 index cd22c4fe..00000000 --- a/Output/v8.0.x/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Как установить 8.x (How to install 8.x) - -Пожалуйста прочитайте статью [wiki](https://github.com/Calabonga/Microservice-Template/wiki), в которой описано как очень просто установить шаблоны при помощи одной команды из командной строки на ваш рабочий компьютер. - -Please, read [wiki](https://github.com/Calabonga/Microservice-Template/wiki) where you can find information about a simple way using one command in command prompt to install templates on your workstation. \ No newline at end of file diff --git a/README.md b/README.md index 1676038d..24271fa8 100644 --- a/README.md +++ b/README.md @@ -6,11 +6,11 @@ ## Как установить -Для установки версии 8.x пожалуйста прочитайте статью [wiki](https://github.com/Calabonga/Microservice-Template/wiki), в которой описано как очень просто установить шаблоны при помощи одной команды из командной строки на ваш рабочий компьютер. Также вы можете использовать расширение для Visual Studio [Microservice-Template](https://marketplace.visualstudio.com/items?itemName=Calabonga.microserivce-templates) из marketplace. +Для установки шаблонов в среду разработки (`Visual Studio`, `Rider`, `dotnet CLI`) пожалуйста прочитайте статью [wiki](https://github.com/Calabonga/Microservice-Template/wiki), в которой описано, как очень просто установить шаблоны при помощи одной команды из командной строки на ваш рабочий компьютер. ## How to install -To install version 8.x please, read [wiki](https://github.com/Calabonga/Microservice-Template/wiki) where you can find information about a simple way using one command in command prompt to install templates on your workstation. Another way to install extension is use Visual Studio marketplace [Microservice-Template](https://marketplace.visualstudio.com/items?itemName=Calabonga.microserivce-templates). +To install templates (`Visual Studio`, `Rider`, `dotnet CLI`) please, read [wiki](https://github.com/Calabonga/Microservice-Template/wiki) where you can find information about a simple way to use a command (command prompt) to install templates on your workstation. ## Дополнительная информация (Additional info) @@ -19,6 +19,19 @@ To install version 8.x please, read [wiki](https://github.com/Calabonga/Microser ## История Nimble Framework +### 2024-11-26 Версия 9.0.0 + +* Обновилась версия платформы NET9.0, установлены nuget-пакеты, соответствующие версии. +* Подключен `Microsoft.AspNetCore.OpenApi` как основной генератор документации. +* `Swashbuckle.AspNetCore` nuget-пакет удален. +* `Swashbuckle.AspNetCore.SwaggerUI` nuget-пакет установлен для использования как UI для интерактивного использования OpenApi документации (`openapi/v1.json`). +* Настройки CORS обновлены +* Сборка CI/CD переведена на использование NET9, +* Из репозитория удалена папка `Output`, где хранились собранные сборки предыдущих версий. +* Из репозитория удален проект (папка `VSIX`) с расширением для `Visual Studio`, так поддерживать данный плагин нецелесообразно, в виду просты использования шаблонов для Visual Studio. +* Из репозитория удалена папка `IdentityServer4Mvc`, где хранились формы MVC-проекта для IdentityServer4. +* Из репозитория удален проект `Builder` (папка Builder), который позволял "вручную" собирать проекты шаблонов. Данный функционал больше не требуется. + ### 2024-09-20 Версия 8.0.6 * Обновились nuget-пакеты в проекте `IdentityModule` diff --git a/VSIX/MicroserviceTemplateVSIX.sln b/VSIX/MicroserviceTemplateVSIX.sln deleted file mode 100644 index 2ea06a24..00000000 --- a/VSIX/MicroserviceTemplateVSIX.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.0.31903.59 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MicroserviceTemplateVSIX", "MicroserviceTemplateVSIX\MicroserviceTemplateVSIX.csproj", "{954FCFF7-9198-4291-935B-D45C0B380C24}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {954FCFF7-9198-4291-935B-D45C0B380C24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {954FCFF7-9198-4291-935B-D45C0B380C24}.Debug|Any CPU.Build.0 = Debug|Any CPU - {954FCFF7-9198-4291-935B-D45C0B380C24}.Debug|x86.ActiveCfg = Debug|x86 - {954FCFF7-9198-4291-935B-D45C0B380C24}.Debug|x86.Build.0 = Debug|x86 - {954FCFF7-9198-4291-935B-D45C0B380C24}.Release|Any CPU.ActiveCfg = Release|Any CPU - {954FCFF7-9198-4291-935B-D45C0B380C24}.Release|Any CPU.Build.0 = Release|Any CPU - {954FCFF7-9198-4291-935B-D45C0B380C24}.Release|x86.ActiveCfg = Release|x86 - {954FCFF7-9198-4291-935B-D45C0B380C24}.Release|x86.Build.0 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {42421DC2-A5AF-407A-ACBE-0B9AE3DE7665} - EndGlobalSection -EndGlobal diff --git a/VSIX/MicroserviceTemplateVSIX/GetStarted.txt b/VSIX/MicroserviceTemplateVSIX/GetStarted.txt deleted file mode 100644 index 7668b5e4..00000000 --- a/VSIX/MicroserviceTemplateVSIX/GetStarted.txt +++ /dev/null @@ -1,10 +0,0 @@ -More information: -1. GitHub (https://github.com/Calabonga/Microservice-Template) -2. Calabonga's blog about .NET https://www.calabonga.net/ -3. Nimble Framework playlist "https://www.youtube.com/playlist?list=PLIB8be7sunXMhdxAYk0My8UNG0zvOkWwK" -4. Микросервисы "https://www.youtube.com/playlist?list=PLIB8be7sunXMXTZKptqEtXAACpsYZdzi_" -5. Video blog https://dzen.ru/calabonga - -Donate: - -https://boosty.to/calabonga/donate \ No newline at end of file diff --git a/VSIX/MicroserviceTemplateVSIX/License.txt b/VSIX/MicroserviceTemplateVSIX/License.txt deleted file mode 100644 index 32c5acd7..00000000 --- a/VSIX/MicroserviceTemplateVSIX/License.txt +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2001-2024 Calabonga - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/VSIX/MicroserviceTemplateVSIX/MicroserviceTemplateVSIX.csproj b/VSIX/MicroserviceTemplateVSIX/MicroserviceTemplateVSIX.csproj deleted file mode 100644 index 3f4d9453..00000000 --- a/VSIX/MicroserviceTemplateVSIX/MicroserviceTemplateVSIX.csproj +++ /dev/null @@ -1,103 +0,0 @@ - - - - 17.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - Debug - AnyCPU - 2.0 - {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - {954FCFF7-9198-4291-935B-D45C0B380C24} - Library - Properties - MicroserviceTemplateVSIX - MicroserviceTemplateVSIX - v4.7.2 - true - true - true - false - false - true - true - Program - $(DevEnvDir)devenv.exe - /rootsuffix Exp - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - Always - true - - - Always - true - - - Designer - - - - - - - - - - - - Always - true - - - Always - true - - - Always - true - - - Always - true - - - Always - true - - - - - - - \ No newline at end of file diff --git a/VSIX/MicroserviceTemplateVSIX/MicroserviceTemplateVSIXPackage.cs b/VSIX/MicroserviceTemplateVSIX/MicroserviceTemplateVSIXPackage.cs deleted file mode 100644 index 21d6d7ad..00000000 --- a/VSIX/MicroserviceTemplateVSIX/MicroserviceTemplateVSIXPackage.cs +++ /dev/null @@ -1,53 +0,0 @@ -using Microsoft.VisualStudio.Shell; -using System; -using System.Runtime.InteropServices; -using System.Threading; -using Task = System.Threading.Tasks.Task; - -namespace MicroserviceTemplateVSIX -{ - /// - /// This is the class that implements the package exposed by this assembly. - /// - /// - /// - /// The minimum requirement for a class to be considered a valid package for Visual Studio - /// is to implement the IVsPackage interface and register itself with the shell. - /// This package uses the helper classes defined inside the Managed Package Framework (MPF) - /// to do it: it derives from the Package class that provides the implementation of the - /// IVsPackage interface and uses the registration attributes defined in the framework to - /// register itself and its components with the shell. These attributes tell the pkgdef creation - /// utility what data to put into .pkgdef file. - /// - /// - /// To get loaded into VS, the package must be referred by <Asset Type="Microsoft.VisualStudio.VsPackage" ...> in .vsixmanifest file. - /// - /// - [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] - [Guid(MicroserviceTemplateVSIXPackage.PackageGuidString)] - public sealed class MicroserviceTemplateVSIXPackage : AsyncPackage - { - /// - /// MicroserviceTemplateVSIXPackage GUID string. - /// - public const string PackageGuidString = "01f49a18-333d-4a18-874b-d5b3016d00d2"; - - #region Package Members - - /// - /// Initialization of the package; this method is called right after the package is sited, so this is the place - /// where you can put all the initialization code that rely on services provided by VisualStudio. - /// - /// A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down. - /// A provider for progress updates. - /// A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method. - protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress progress) - { - // When initialized asynchronously, the current thread may be a background thread at this point. - // Do any initialization that requires the UI thread after switching to the UI thread. - await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); - } - - #endregion - } -} diff --git a/VSIX/MicroserviceTemplateVSIX/ProjectTemplates/1.zip b/VSIX/MicroserviceTemplateVSIX/ProjectTemplates/1.zip deleted file mode 100644 index 63e89816..00000000 Binary files a/VSIX/MicroserviceTemplateVSIX/ProjectTemplates/1.zip and /dev/null differ diff --git a/VSIX/MicroserviceTemplateVSIX/ProjectTemplates/2.zip b/VSIX/MicroserviceTemplateVSIX/ProjectTemplates/2.zip deleted file mode 100644 index a8f19982..00000000 Binary files a/VSIX/MicroserviceTemplateVSIX/ProjectTemplates/2.zip and /dev/null differ diff --git a/VSIX/MicroserviceTemplateVSIX/Properties/AssemblyInfo.cs b/VSIX/MicroserviceTemplateVSIX/Properties/AssemblyInfo.cs deleted file mode 100644 index 29789f42..00000000 --- a/VSIX/MicroserviceTemplateVSIX/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("MicroserviceTemplateVSIX")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("MicroserviceTemplateVSIX")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/VSIX/MicroserviceTemplateVSIX/Release.txt b/VSIX/MicroserviceTemplateVSIX/Release.txt deleted file mode 100644 index ee8585c4..00000000 --- a/VSIX/MicroserviceTemplateVSIX/Release.txt +++ /dev/null @@ -1,438 +0,0 @@ -# Nimble Framework - ->Внимание! Пожалуйста, ознакомьтесь со всеми комментариями с надписью "ATTENTION!", потому что эти места потребуют от вас некоторых решений и/или действий. - ->Attention! Please find out all comments with 'ATTENTION!' because that is required some decisions or actions from you. - -## Как установить - -Для установки версии 8.x пожалуйста прочитайте статью [wiki](https://github.com/Calabonga/Microservice-Template/wiki), в которой описано как очень просто установить шаблоны при помощи одной команды из командной строки на ваш рабочий компьютер. - -Также вы можете использовать расширение для Visual Studio [Microservice-Template](https://marketplace.visualstudio.com/items?itemName=Calabonga.microserivce-templates) из marketplace, но версия уже только v7.x. - -## How to install - -To install version 8.x please, read [wiki](https://github.com/Calabonga/Microservice-Template/wiki) where you can find information about a simple way using one command in command prompt to install templates on your workstation. - -Another way to install extension is use Visual Studio marketplace [Microservice-Template](https://marketplace.visualstudio.com/items?itemName=Calabonga.microserivce-templates), but templates version is 7.x. - -## Дополнительная информация (Additional info) - -* На [сайте разработчика](https://www.calabonga.net/blog/post/microservice-templates). -* Видео презентация новой версии [Nimble Framework v.6](https://youtu.be/euOLhhNEcwg). - -## История Nimble Framework - -### 2024-02-06 Версия 8.0.1 - -Вместо nuget-пакета [`OperationResultCore`](https://github.com/Calabonga/OperationResult)в обоих шаблонах теперь используется более простая и современная реализация RFC7807 - [`Calabonga.Results`](https://github.com/Calabonga/Calabonga.Results), которая существенно "облегчила" сериализацию выдаваемых результатов повысив параметры производительности в несколько раз. - -* Сборка `OperationResultCore` удалена из обоих шаблонов. -* Сборка `Calabonga.Results` установлена из обоих шаблонов. -* Обновились nuget-пакеты -* Удалены ненужные архивы старых версий на платформах ниже версии 8.x. -* Удалены артефакты, которые позволяли генерировать шаблоны без использования template-проектов. - - -### 2023-11-20 Версия 8.0.0 - -Новая и первая версия шаблонов для микросервисов на платформе NET8. - -![Install module](Whatnot/v8-1.png) - -* Произведен некоторый рефакторинг папок и, соответственно, namespace в шаблонах, чтобы соблюсти договоренности о именованиях. -* Обновлены nuget-пакеты -* `IdentityModule`: добавлена возможно авторизации и по `Bearer` вдобавок к `Cookie`. -* `IdentityModule`: добавлена `PolicyCorsName` и `PolicyDefaultName` -* `IdentityModule` и `Module`: обновлена реализация `EventItemEndpoints` и `ProfilesEndpoints` чтобы можно было использовать `Endpoint Explorer` для генерации `.http` файлов для вызова методов прямо из `Visual Studio`: - - ![Install module](Whatnot/v8-2.png) ![Install module](Whatnot/v8-3.png) - -* Подключена сборка `Microsoft.AspNetCore.OpenApi` для полноценной реализации `OpenApi`. Удалены ненужные зависимости. -* Произведены другие мелкие правки, в том числе синтаксические. - - -### 2023-09-24 Версия 7.0.8: - -* Из репозитория удалены исходные файлы для NET 5, а также готовые архивы для использования NET 5. -* Обновлены nuget-пакеты -* Небольшие правки по оптимизации `appSettings.json` для `develop` и `production` развертывания. -* Добавлена обязательная проверка возможных NullReferenceException в файл проекта для каждого из шаблонов. - ``` diff - - - - net7.0 - - enable - - enable - - - + - + net7.0 - + enable - + enable - + true - + enable - + - ``` -* Обновлена конфигурация `.editor.config`. - - ``` diff - +[*.json] - + - +indent_size = 4 - +indent_style = space - +tab_width = 4 - - # C# files - [*.cs] - @@ -218,10 +223,15 @@ dotnet_naming_style.instance_field_style.required_prefix = _ - - # ReSharper properties - max_line_length = 200 - +resharper_arguments_anonymous_function = named - +resharper_blank_lines_after_multiline_statements = 1 - +resharper_blank_lines_before_control_transfer_statements = 1 - +resharper_csharp_keep_blank_lines_in_code = 1 - resharper_csharp_max_line_length = 200 - resharper_csharp_wrap_after_declaration_lpar = true - resharper_csharp_wrap_extends_list_style = chop_if_long - resharper_csharp_wrap_lines = false - +resharper_instance_members_qualify_declared_in = base_class - resharper_max_attribute_length_for_same_line = 300 - resharper_place_type_constraints_on_same_line = true - resharper_wrap_before_arrow_with_expressions = true - ``` - -### 2023-08-07 Версия 7.0.7 - -* Сделан рефакторинг папок в проектах с целью добиться максимального соответствия концепции Clean Architecture, и в частности Vertical Slice Architecture. Выпущена -* Обновлены nuget-пакеты некоторых базовых сборок -* Исправлены мелкие недочеты (naming convention, syntax issies, etc.) - -### 2023-08-04 Версия 7.0.6 - -Созданы шаблоны для `dotnet CLI`. Теперь можно установить шаблоны очень просто через команду `dotnet`. Например, чтобы установить шаблон для `Microservice Identity Module` достаточно выполнить команду: - -``` bash -dotnet new install Calabonga.Microservice.IdentityModule.Template -``` - -![Install identity module](Whatnot/install_identity_module.png) - -А для установки `Microservice Module` нужно такую команду: - -``` bash -dotnet new install Calabonga.Microservice.Module.Template -``` - -![Install module](Whatnot/install_module.png) - -Проверить установлены ли шаблоны можно командой -``` bash -dotnet new list -``` - -Команда выведет список всех установленных шаблонов: - -![template list](Whatnot/templates_list.png) - -Также после установки шаблонов, они станут доступы в Visual Studio и JetBrains Rider. - -### Visual Studio - -![Visual Studio create new project screen](Whatnot/nimble_vs.png) - -### JetBrains Rider - -![JetBrains Rider create new project screen](Whatnot/nimble_rider.png) - -### 2023-06-15 Версия 7.0.5 - -* Обновлены nuget-пакеты -* Немного изменена структура классов для наследников от `IRequest` и `IRequestHandler`. Теперь запросы с перехватчиками объединены в один класс, что на самом деле гораздо удобнее. -* Поправлены некоторые описания Summary - -### 2023-05-22 - -[Пример использования шаблона для построения backend (API) для каталога товаров](https://github.com/Calabonga/Calabonga.Catalog). В этом репозитории "пошаговая" реализация, которая записана на видео. Можно посмотреть примеры (examples of using) разных механизмов: Validation, Transactions, Notification and etc. - -### 2023-04-15 Версия 7.0.4 - -* Обновлены сборки (nuget) для `AutoMapper`, `FluentValidation`, `Microsoft.AspNetCore.Authentication`,`Serilog`. -* Конфигурация для `Serilog` вынесена в `appSettings.json` -* `LoggerExtensions` удалены, потому что подключено Structural logging на базе `Serilog`. -* Потому как `StopTheHostException` переименован `HostAbortedException` перехватывать его теперь стали по-новому. -* Перехват исключений `ValidationException` теперь работает через `OperationResult`, для этого обновлен `ValidatorBehavior`. - -### 2023-03-11 Версия 7.0.3 - -* Обновлены сборки (nuget) для OpenIddict (OAuth2.0). -* Из шаблона удалена сборка `GitInfo`, которая позволяла использовать версионирование на основе GIT, потому что при создании проекта вне папки репозитория появлялась ошибка: `NETSDK1018 Invalid NuGet version string: '0.0.0+main.'.`. Пожалуйста, ознакомьтесь со всеми комментариями с надписью "ATTENTION!", потому что эти места потребует от вас некоторых решений или действий. Например, использовать или не использовать версионирование на основе GIT возможностей. -* Исправлена работа `FluentValidation` для `EventItemValidator`. -* Исправлена работа `ErrorHandlerMiddleware` для отображения ошибок валидации. - -### 2023-02-24 Версия 7.0.2 - -Версия получила следующие изменения: - -* Новая версия `Mediatr` получила обновление, в том числе была удалена зависимость от nuget-пакета `MediatR.Extensions.Microsoft.DependencyInjection`. А также изменилась регистрация зависимости. - -``` diff -- services.AddMediatR(Assembly.GetExecutingAssembly()); -+ services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining()); -``` - -* Обновились сборки `EntityFramework`. -* Обновилась версия для расширение для Visual Studio (VSIX). - -### 2023-02-05 Версия 7.0.1 - -* Обновлены почти все nuget-пакеты, в том числе и один из самых важных `OpenIddict`: - -``` diff -- -+ -``` - -* Исправлено несколько синтаксических ошибок -* Обновлены методы в `IAccountService`. За счет этого существенно сокращено количество повторяющихся запрос в базу данных за информацией о пользователе. - -### 2022-11-12 - -Шаблоны для создания проектов для микросервисной архитектуры успешно мигрировали на NET7. Обновились сборки всех необходимых nuget-пакетов, а также сами проекты теперь строятся на NET7. Не забудьте обновить CI/CD если будете публиковать новые версии для NET7. - -### 2022-10-02 - -Новые версии шаблонов теперь работают совместно. То есть теперь созданное приложение из шаблона `Calabonga.Microservice.Module` может авторизоваться у приложения, которое создано из шаблона `Calabonga.Microservice.IdentityModule` прямо после создания приложений из шаблонов. - -В связи с тем, что обновления были в разных модулях в прошлый раз, шаблоны на данный момент имеют разные версии (В будущем это расхождение будет невелировано): - -* Calabonga.Microservice.IdentityModule имеет версию `6.1.4` -* Calabonga.Microservice.Module имеет версию `6.1.2` - -### Что в новой версии - -* Обновлены сборки (nuget-пакеты) -* Удалены шаблоны, которые использовали IdentityServer4 в качестве сервера авторизации. -* Добавлена сборка [Calabonga.AspNetCore.AppDefinitions](https://www.nuget.org/packages/Calabonga.AspNetCore.AppDefinitions/), которая подключает возможность использования AppDefinitions в проектах на платформе ASP.NET Core. - -### 2022-09-03 Версия 6.1.3 - -В новой версии `6.1.3` обновился метод авторизации по `Authorization Code Flow`. Подключены механизмы, которые приведены в пример на сайте [OpenIddict Samples](https://github.com/openiddict/openiddict-samples). Теперь авторизация учитывает `Consent`, а также подключены более жесткие требования к формированию `id_token` и `access_token`, которые рекомендованы стандартами `OAuth2.0`. - -image - -### 2022-07-26 Версия 6.1.2 - -В новой версии `6.1.2` добавлены некоторые инициализации для того, чтобы было проще подключить `EntityFramework` провайдер для `Microsoft SQL Server` (UseSqlClient). Добавленные строки кода были закоментированы, чтобы можно было оставить функциональность для IN-MEMORY режима. - -### 2022-07-04 Версия 6.1.1 - -В новой версии `6.1.1` удалены проекты из папки FullAPI (вместе с папкой). Версия с `IdentityServer` больше не будет получать обновления, но пока останется доступной. Вы можете ее найти в папке MinimalAPI-IS4. Если вам еще нужны эти проекты, настоятельно рекомендую сделать fork моего репозитория. - -* Обновлены nuget-пакеты, которые использованы в шаблонах (EntityFramework, FluentValidation). -* Удалены старые проекты. -* Обновлены собранные архивы для Visual Studio в папке OUTPUT. - -### 2022-05-14 Версия 6.1.0 - -На платформе `NET6` (В папке AspNetCore v6.1) можно найти новую версию `Nimble Framework`, который предназначен для быстрого создания микросервисной архитектуры. `Nimble Framework` содержит `IdentityModule` (AuthServer) и Module (microservice). Новая версия доступна для скачивания. - -* Удален IdentityServer4 как основа для аутентификации и авторизации на базе OAuth2.0. Теперь Nimble Framework использует для шаблона с сервером авторизации OpenIddict, который также реализует спецификации OAuth2.0. -* Обновлен механизм авторизации на странице swagger. Теперь используется Authorization Code Flow, который реализует форму входа. Это позволит использовать шаблон "из коробки". -* Обновлен механизм авторизации для второстепенных сервисов (механизм передачи ролей в токен) -* Обновлены почти все сборки (переведены на NET6), которые использованы в шаблонах -* Реализована система Definitions - -### 2022-01-16 Версия 6.0.1 - -1. Обновлены nuget-пакеты Automapper и Mediatr -2. Обновились сборки для ASP.NET Core, EntityFrameworkCore -3. Добавлена информация к шаблону о его времени сборке и прочая информация про Copyright -4. Обновлен "сборщик" шаблонов, который позволяет быстро обновлять solutions - -[В статье блога](https://www.calabonga.net/blog/post/nimble-framework-v-6-1) и [Видео презентация](https://youtu.be/xijBGwMEL8E) - -### 2022-05-11 - -Реализация `OpenIddict` в шаблонах завершена, теперь формируются шаблоны для `Visual Studio`. - -### 2022-05-04 - -Начались работы по переходу от IdentityServer4 на OpenIddict как основной сервис авторизации OAuth2.0. Причина переезда - скорое окончание срока поддержки IdentityServer4 и перехода его на платную основу. - -### 2021-11-21 - -На платформе NET6 (В папке `AspNetCore v6.0`) теперь существует два вида шаблонов микросервисов (FullAPI и MinimalAPI), каждый из которых содержит IdentityModel и простой Module. Папка FullAPI содержит уже знакомые шаблоны микросервисов, просто они теперь переведены на NET6. А в папке MinimalAPI новая версия тех же шаблонов, которые построены на базе [MinimalAPI](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0). - -1. Шаблоны микросервисов переведены на новую версию NET6. Обновлены почти все файлы, использованы новые "фишки", которые появились в C#. -2. Обновились сборки для ASP.NET Core, EntityFrameworkCore и Swagger (OpenAPI). Теперь используются версии NET6. -3. Удалены дубликаты контроллеров, которые демонстрировали использовать подхода Readonly/Writable (Calabonga.UnitOfWork.Controllers). Теперь остался только один пример, построенный на базе Mediatr. -4. Обновлена инфраструктура папок. Использована Vertical Slice Architecture, которую представил Jimmy Bogard. -5. Обновилось расширение VSIX-расширения для Visual Studio. - -### 2021-11-01 - -1. Удалены старые шаблоны для версий NET Core 2.2 и NET Core 3.0. -2. Началась разработка шаблонов для новой версии. - -### 2021-09-06 Версия 5.0.7 - -1. Обновились сборки для ASP.NET Core, EntityFrameworkCore и Swagger (OpenAPI). А также nuget-пакеты Calabonga.Microservices.Core, FluentValidation и другие. -2. Добавлено несколько комментариев в код для обеспечения определенности в действиях -3. Обновилось расширение VSIX-расширения для Visual Studio. -4. - -## 2021-10-31 Версия 5.0.8 - -1. Обновились сборки для ASP.NET Core, EntityFrameworkCore и Swagger (OpenAPI). А также nuget-пакет FluentValidation и другие. -2. Конструкции некоторых методов переведин на lambda-выражения, чтобы следовать моде. -3. Обновилось расширение VSIX-расширения для Visual Studio. - -## 2021-09-08 Версия 5.0.6 - -1. Обновились сборки для ASP.NET Core и EntityFrameworkCore. А также nuget-пакеты OperationResultCore, Calabonga.Microservices.Core, Swagger, FluentValidation и другие. -2. Обновились метаданные, используемые для VSIX-расширения для Visual Studio. - -## 2021-06-04 Версия 5.0.5 - -1. Исправлено несколько опечаток. -2. Обновились сборки для ASP.NET Core и EntityFrameworkCore. А также nuget-пакеты OperationResultCore, Calabonga.Microservices.Core, Swagger, FluentValidation и другие. - -## 2021-03-23 Версия 5.0.4 - -1. Стандартный logger заменен на Serilog. Теперь читать логи стало проще. -2. Исправлено несколько опечаток. -3. Обновились сборки для ASP.NET Core и EntityFrameworkCore. А также nuget-пакеты OperationResultCore, Calabonga.Microservices.Core и другие. -4. Реализация Mediatr-запросов (Request) из классов превратились в записи (class -> record) С#. - -## 2021-03-16 Версия 5.0.3 - -1. Удалена зависимость от некоторых сборок, которые вынесены на более высокий уровень. Это позволит обновлять их отдельно. -2. Исправлено несколько опечаток. -3. Обновились сборки для ASP.NET Core и EntityFrameworkCore до версий (5.0.4). А также nuget-пакеты OperationResultCore, Calabonga.Microservices.Core и другие. -4. Реализация Mediatr-запросов из контроллеров перенесены в проекты шаблонов из сборки Calabonga.AspNetCore.Controllers, чтобы примеры использования были доступны разработчику. - -## 2021-01-27 Версия 5.0.2 - -1. Применены языковые *фишки* из C# 9.0. Другими словами, был неслабый рефакторинг кода для оптимизации. -2. Исправлено несколько опечаток. -3. Обновились сборки для `ASP.NET Core` и `EntityFramework Core` до версий (5.0.2). А также nuget-пакеты `OperationResultCore`, `Calabonga.Microservices.Core` и другие. - -## 2020-12-04 Версия 5.0.1 - -1. В шаблоне микросервиса с IdentityServer4 и шаблоне без него удалены проекты xxx.Core. Файлы из этих проектов перенесены в проект xxx.Entities. Ссылки на Exceptions вынесены в nuget-пакет `Calabonga.Microservices.Core`. -2. В шаблоне микросервиса с IdentityServer4 добавлена возможность аутентификации как для Cookie типа, так и для Bearer. Да! Теперь настроено два типа аутентификации. -3. Применены языковые *фишки* из C# 8.0. Другими словами, был неслабый рефакторинг кода для оптимизации. -4. Исправлено множество опечаток. - -## 2020-11-15 Версия 5.0.0 - -1. Все проекты во всех решениях (solutions) обновились до версии .NET 5.0. -2. Обновились nuget-сборки для `ASP.NET Core` и `EntityFramework Core` (5.0.0). -3. Добавилась реализация логирования, как пример использования, который описан на видео [ILogger в ASP.NET Core](https://youtu.be/09EVKgHgwnM) -4. На страницу API (`Swagger`) выведена информация о названии ветки (branch) и номер публикации (commit). - -# Документация - -Документация доступна на GitHub в разделе [Wiki](https://github.com/Calabonga/Microservice-Template/wiki/Nimble-Microservice-Templates) - -# Микросервисы - -Шаблон (template) для Visual Studio для построения инфраструктуры микросервисов на базе ASP.NET Core. - -# Microservices - -Visual Studio project template for microservice module base on ASP.NET Core - -# Скачать (Download) - -[ASP NET Core 3.1](https://github.com/Calabonga/microservice-template/tree/master/Output/AspNetCore-v.3.1) - Шаблоны для версии ASP.NET Core 3.1 - -[ASP NET Core 5.0](https://github.com/Calabonga/microservice-template/tree/master/Output/AspNetCore-v.5.0) - Шаблоны для версии ASP.NET Core 5.0 - -[ASP NET Core 6.0](https://github.com/Calabonga/microservice-template/tree/master/Output/AspNetCore-v.6.0) - Шаблоны для версии ASP.NET Core 6.0 - -# Инструкции и дополнительные материалы - -[Установка Nimble Templates](https://www.calabonga.net/blog/post/install-nimble-framework-version-5) - -[Calabonga.AspNetCore.Controllers](https://github.com/Calabonga/Calabonga.AspNetCore.Controllers/) nuget-пакет на базе Mediatr - -[Calabonga.UnitOfWork.Controllers](https://github.com/Calabonga/Calabonga.UnitOfWork.Controllers) nuget-пакет на base Readonly/Writable controllers - -[Микросервисы: Шаблон для микросервиса](https://www.calabonga.net/blog/post/microservises-template) - -[Микросервисы: Управление доступом](https://www.calabonga.net/blog/post/mikroservisy-3-centralizovannoe-upravlenie-dostupom) - -[Микросервисы: Обмен данными между микросервисами](https://www.calabonga.net/blog/post/reshenie-obmen-dannym-mezhdu-mikroservisami) - -[Микросервисы: Прокси для frontend](https://www.calabonga.net/blog/post/odin-frontend-dolzhen-rabotat-tolko-so-svoim-backend) - -[Вопросы можно задать в блоге](https://www.calabonga.net/blog) - -# Видео - -Про NimbleFramework можно найти следующие видео ролики. Они разделятся по версиям, но для всеобщего понимания настоятельно рекомендуется - -## по версии 6.0 - -[Nimble Framework v6.1](https://youtu.be/xijBGwMEL8E) - -[Nimble Framework v6.0](https://youtu.be/euOLhhNEcwg) - -## по версии 3.1 (3.0) - -Часть 0. [Nimble: Установка шаблонов для микросервисов](https://youtu.be/rc0wvL0jlzc) - -Часть 1. [Nimble: Демонстрация шаблона микросервиса на примере](https://youtu.be/N0dRGGV2iEg) - -Часть 2. [Nimble: Установка шаблонов для микросервисов](https://youtu.be/rc0wvL0jlzc) - -Часть 3. [Nimble: Основные и базовые понятия](https://youtu.be/WbSwp1Aa7hM) - -Часть 4. [Nimble: Создаем свой Query и Handler для IMediator](https://youtu.be/wUfT5aLHVV8) - -[Микросервисы 2](https://www.youtube.com/playlist?list=PLIB8be7sunXMh9dckizdXz65hLX_HRzlc) (плей-лист) - -## о по версии 2.2 - -[Микросервисы](https://www.youtube.com/playlist?list=PLIB8be7sunXMXTZKptqEtXAACpsYZdzi_) (плей-лист) - -# Visual Studio Extensions - -Теперь шаблоны для генерации микросервисов доступны также и в Visual Studio Marketplace - -![marketplace](Whatnot/vs-extension-market-view.png) - -[Посмотреть marketplace](https://marketplace.visualstudio.com/items?itemName=Calabonga.microserivce-templates) - -Также можно установить прямо из Visual Studio -![extension](Whatnot/vs-extension.png) - -# Дополнительные материалы по Nimble Framework - -[Микросервисы: Nimble Framework v.2](https://youtu.be/bTxruvbhDss) - -[Nimble: Создание микросервиса](https://youtu.be/7nw8Naxf2U0) - -Nimble Framework для NET6 Готовится - -# Благодарности - -Благодарности помощь каналу принимаются (Support This Project): - -* - -## Комментарии, пожелания, замечания - -Пишите комментарии к видео на сайте [www.calabonga.net](https://www.calabonga.net) - -# Автор - -Сергей Калабонга (Calabonga) - -![Author](Whatnot/Calabonga.gif) - -# Обратная связь - -* [Блог по программированию](https://www.calabonga.net) -* [Видео канал Boosty.to/Calabonga](https://boosty.to/Calabonga) diff --git a/VSIX/MicroserviceTemplateVSIX/__TemplateIcon.png b/VSIX/MicroserviceTemplateVSIX/__TemplateIcon.png deleted file mode 100644 index 12387ef6..00000000 Binary files a/VSIX/MicroserviceTemplateVSIX/__TemplateIcon.png and /dev/null differ diff --git a/VSIX/MicroserviceTemplateVSIX/favicon.ico b/VSIX/MicroserviceTemplateVSIX/favicon.ico deleted file mode 100644 index ec019342..00000000 Binary files a/VSIX/MicroserviceTemplateVSIX/favicon.ico and /dev/null differ diff --git a/VSIX/MicroserviceTemplateVSIX/source.extension.vsixmanifest b/VSIX/MicroserviceTemplateVSIX/source.extension.vsixmanifest deleted file mode 100644 index 89aaa917..00000000 --- a/VSIX/MicroserviceTemplateVSIX/source.extension.vsixmanifest +++ /dev/null @@ -1,30 +0,0 @@ - - - - - MicroserviceTemplate - Microservice template gives you a possibility to start developing a microservice architecture with UI (Swagger Open API) and Mediatr (CQRS). Template Based on NET 8.0.x - https://github.com/Calabonga/Microservice-Template - License.txt - GetStarted.txt - Release.txt - favicon.ico - __TemplateIcon.png - calabonga microservice template nimble identity OpenIddict swagger cqrs mediatr - - - - amd64 - - - - - - - - - - - - - diff --git a/Whatnot/thunder-collection-nimble-template.json b/Whatnot/thunder-collection-nimble-template.json deleted file mode 100644 index c00c3f75..00000000 --- a/Whatnot/thunder-collection-nimble-template.json +++ /dev/null @@ -1 +0,0 @@ -{"client":"Thunder Client","collectionName":"MicroserviceTemplate","dateExported":"2022-05-08T01:50:58.263Z","version":"1.1","folders":[],"requests":[{"_id":"2c03be2e-e221-4c38-991c-7ba4b656deba","colId":"dca145ef-c5a8-4a1d-bec6-951516f6d50b","containerId":"","name":"openid-configuration","url":"{{auth-server}}/.well-known/openid-configuration","method":"GET","sortNum":10000,"created":"2022-05-03T07:07:13.634Z","modified":"2022-05-08T01:44:46.071Z","headers":[],"params":[],"tests":[{"type":"Content-Type","custom":"","action":"equal","value":"application/json;charset=UTF-8"},{"type":"res-body","custom":"","action":"contains","value":"grant_types_supported"},{"type":"res-code","custom":"","action":"equal","value":"200"},{"type":"res-body","custom":"","action":"contains","value":"password"},{"type":"res-body","custom":"","action":"contains","value":"refresh_token"}]},{"_id":"2e058b94-6464-44e1-aea9-172c26e37abf","colId":"dca145ef-c5a8-4a1d-bec6-951516f6d50b","containerId":"","name":"token-client-credentials","url":"{{auth-server}}/connect/token","method":"POST","sortNum":15000,"created":"2022-05-03T08:08:02.214Z","modified":"2022-05-08T01:49:12.801Z","headers":[],"params":[],"body":{"type":"formencoded","raw":"","form":[{"name":"client_id","value":"{{client-id-credantials}}"},{"name":"client_secret","value":"{{client-secret-credantials}}"},{"name":"scope","value":"{{scope}}"},{"name":"grant_type","value":"client_credentials"}]},"tests":[{"type":"res-code","custom":"","action":"equal","value":"200"},{"type":"res-body","custom":"","action":"contains","value":"access_token"},{"type":"res-body","custom":"","action":"contains","value":"token_type"},{"type":"res-body","custom":"","action":"contains","value":"expires_in"},{"type":"json-query","custom":"json.expires_in","action":">","value":"0"},{"type":"json-query","custom":"json.token_type","action":"equal","value":"Bearer"}]},{"_id":"2b2f47fe-fd8d-420f-8ac1-968e0ba0f7c9","colId":"dca145ef-c5a8-4a1d-bec6-951516f6d50b","containerId":"","name":"logs-paged","url":"{{auth-server}}/api/logs/paged?pageindex=0&pagesize=10","method":"GET","sortNum":20000,"created":"2022-05-03T07:07:49.617Z","modified":"2022-05-08T01:50:02.246Z","headers":[],"params":[{"name":"pageindex","value":"0","isPath":false},{"name":"pagesize","value":"10","isPath":false}],"auth":{"type":"oauth2","oauth2":{"accessToken":"eyJhbGciOiJSUzI1NiIsImtpZCI6Ijc0QzAxQUU2RTBDOUVCRjk1RTExNkU2Qjk1OEZDNTYwN0I5MUU2Q0YiLCJ4NXQiOiJkTUFhNXVESjZfbGVFVzVybFlfRllIdVI1czgiLCJ0eXAiOiJhdCtqd3QifQ.eyJzdWIiOiJlYzY5YTE3My1kNzZmLTQwZjItOWE0My1kOGZhYzg1MzA2MjYiLCJuYW1lIjoibWljcm9zZXJ2aWNlQHlvcG1haWwuY29tIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvZW1haWxhZGRyZXNzIjoibWljcm9zZXJ2aWNlQHlvcG1haWwuY29tIiwiQXNwTmV0LklkZW50aXR5LlNlY3VyaXR5U3RhbXAiOiJlNDA3MTc2NS05OGIwLTQ2NmItODQxYi1lMTAxZTY0Nzc0YzkiLCJyb2xlIjpbIkFkbWluaXN0cmF0b3IiLCJNYW5hZ2VyIl0sIkV2ZW50SXRlbXM6VXNlclJvbGVzOlZpZXciOiJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9naXZlbm5hbWUiOiJNaWNyb3NlcnZpY2UiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zdXJuYW1lIjoiQWRtaW5pc3RyYXRvciIsIm9pX3Byc3QiOiJjbGllbnRfaWRfY29kZSIsIm9pX2F1X2lkIjoiMzRiMWMxZDAtNjY5NS00M2QyLTgyZmItNzA2MDViODU4MWEwIiwiY2xpZW50X2lkIjoiY2xpZW50X2lkX2NvZGUiLCJvaV90a25faWQiOiJhZDAyZWUyOS00ZDcxLTQ4ZTMtYTIzZC03ZjJlNTJiMWUwMDAiLCJzY29wZSI6ImFwaSIsImV4cCI6MTY1MTk3NzUwNCwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6MjAwMDEvIiwiaWF0IjoxNjUxOTczOTA0fQ.FpUlDc1gWyKoZ2ENvi88zJ9R-jGuTpHMF9Qn7s4sl34RwMEYhv4vRqZgM7II6oF7pZPyH8jBXbge7qwtHDlPP81ObDvwmpLX4jIFRLCPx8Cr0a-YE6CbKwjNo39jzvUMeeWqWNEFVyY_-i5DP5_RK2T7p7hwGBAOFqlgUvDMnWHk5aK-NVEYUMN77nUtwKHzDcWj0rHYFFhJh1Htl9qpydv-h_UBnDCluus7Afbt5eLq3skw3IrNPIpc2z8f6NguEl2PD--bqqExfRg6c_U3oKnDSH9meQldEaXK8jYRZHs52pLEARnBHlmhjwQoYlUGCn_9HdVe_pMObps8g3Ig2A","grantType":"authorization_code","callbackUrl":"https://www.thunderclient.com/oauth/callback","authUrl":"{{auth-server}}/connect/authorize","tokenUrl":"{{auth-server}}/connect/token","clientId":"{{client-id-code}}","clientSecret":"{{client-secret-code}}","clientAuth":"in-header","scope":"{{scope}}","state":"calabonga-nimble-framework"}},"tests":[{"type":"res-code","custom":"","action":"equal","value":"200"},{"type":"res-body","custom":"","action":"contains","value":"result"},{"type":"res-body","custom":"","action":"contains","value":"ok"},{"type":"json-query","custom":"json.ok","action":"equal","value":"true"}]},{"_id":"26592046-924e-4a12-8178-9dad03dc5a4a","colId":"dca145ef-c5a8-4a1d-bec6-951516f6d50b","containerId":"","name":"logs-by-id","url":"{{auth-server}}/api/logs/1b830921-dfab-4093-4b97-99df0136c55f","method":"GET","sortNum":30000,"created":"2022-05-08T01:38:48.415Z","modified":"2022-05-08T01:50:39.449Z","headers":[],"params":[],"auth":{"type":"oauth2","oauth2":{"accessToken":"eyJhbGciOiJSUzI1NiIsImtpZCI6Ijc0QzAxQUU2RTBDOUVCRjk1RTExNkU2Qjk1OEZDNTYwN0I5MUU2Q0YiLCJ4NXQiOiJkTUFhNXVESjZfbGVFVzVybFlfRllIdVI1czgiLCJ0eXAiOiJhdCtqd3QifQ.eyJzdWIiOiJlYzY5YTE3My1kNzZmLTQwZjItOWE0My1kOGZhYzg1MzA2MjYiLCJuYW1lIjoibWljcm9zZXJ2aWNlQHlvcG1haWwuY29tIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvZW1haWxhZGRyZXNzIjoibWljcm9zZXJ2aWNlQHlvcG1haWwuY29tIiwiQXNwTmV0LklkZW50aXR5LlNlY3VyaXR5U3RhbXAiOiJlNDA3MTc2NS05OGIwLTQ2NmItODQxYi1lMTAxZTY0Nzc0YzkiLCJyb2xlIjpbIkFkbWluaXN0cmF0b3IiLCJNYW5hZ2VyIl0sIkV2ZW50SXRlbXM6VXNlclJvbGVzOlZpZXciOiJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9naXZlbm5hbWUiOiJNaWNyb3NlcnZpY2UiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zdXJuYW1lIjoiQWRtaW5pc3RyYXRvciIsIm9pX3Byc3QiOiJjbGllbnRfaWRfY29kZSIsIm9pX2F1X2lkIjoiMWU1YTk5MjAtMDIxOS00YjcwLTg2ZTEtY2I5MjkwMjA4OTcyIiwiY2xpZW50X2lkIjoiY2xpZW50X2lkX2NvZGUiLCJvaV90a25faWQiOiIyOGIzMjEzOS1hMzhiLTQwZWEtOGFiYy00NTY1OTRkNjU0MjQiLCJzY29wZSI6ImFwaSIsImV4cCI6MTY1MTk3NzU2OCwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6MjAwMDEvIiwiaWF0IjoxNjUxOTczOTY4fQ.YqrEm5Q4RC4HL8W9rYyjAPq05FPXNpaCmS8kmN1lT2fcoG7eHV5jaSbje7CZ2vowfaSvaqWbBYJuKTlQm8sk0qYQdRhFrYnON4lFqVXs138YE89rkN-AUoz4BAwwKcnznCPZsTVRZhHYLfAe5qCkabvcFnmyuG_BwuiMNdizOncbFI3tQEgLoOkkh8Z239AuCEpt_E1O3DPY286OqoGVAOPExjraLojlIXz4zV7bGteuO86wXiCBVbcc2LTKX9z6sXsJIAOeTYZAchhM6DUJo1zjaJ0twHKolRvWddD3aAfTkRxibgLRcqCwhChS_noXQsvUG5fs6G_ccfrCPDKzmQ","grantType":"authorization_code","callbackUrl":"https://www.thunderclient.com/oauth/callback","authUrl":"{{auth-server}}/connect/authorize","tokenUrl":"{{auth-server}}/connect/token","clientId":"{{client-id-code}}","clientSecret":"{{client-secret-code}}","clientAuth":"in-header","scope":"{{scope}}","state":"calabonga-nimble-framework"}},"tests":[{"type":"res-code","custom":"","action":"equal","value":"200"},{"type":"res-body","custom":"","action":"contains","value":"result"},{"type":"res-body","custom":"","action":"contains","value":"ok"},{"type":"json-query","custom":"json.ok","action":"equal","value":"true"}]}]}