diff --git a/.github/workflows/dotnetcore.yml b/.github/workflows/dotnetcore.yml new file mode 100644 index 0000000..9846c4c --- /dev/null +++ b/.github/workflows/dotnetcore.yml @@ -0,0 +1,18 @@ +name: eQuantic Google Identity Platform Auth + +on: [push] + +jobs: + build: + runs-on: windows-latest + + steps: + - uses: actions/checkout@v3 + - name: Setup .NET Core + uses: actions/setup-dotnet@v2 + with: + dotnet-version: 7.0.x + - name: Build eQuantic.GoogleIdentityPlatform.Auth Library + run: dotnet build --configuration Release + - name: Push package into Nuget.org + run: dotnet nuget push **/*.nupkg --skip-duplicate -k ${{secrets.nuget_key}} -s https://api.nuget.org/v3/index.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea9dc75 --- /dev/null +++ b/.gitignore @@ -0,0 +1,364 @@ + +# Created by https://www.gitignore.io/api/visualstudio,visualstudiocode +# Edit at https://www.gitignore.io/?templates=visualstudio,visualstudiocode + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ +# ASP.NET Core default setup: bower directory is configured as wwwroot/lib/ and bower restore is true +**/wwwroot/lib/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- Backup*.rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# End of https://www.gitignore.io/api/visualstudio,visualstudiocode + +!artifacts/readme.txt +!build/*.targets +!build/*.props \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e0cc185 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 eQuantic + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..f212a00 --- /dev/null +++ b/README.md @@ -0,0 +1,187 @@ +# eQuantic.Core.Api.Crud Library + +The **eQuantic Core API CRUD** provides all the implementation needed to publish CRUD APIs. + +To install **eQuantic.Core.Api.Crud**, run the following command in the [Package Manager Console](https://docs.nuget.org/docs/start-here/using-the-package-manager-console) +```dos +Install-Package eQuantic.Core.Api.Crud +``` + +## Example of implementation + +### The data entities +```csharp +[Table("orders")] +public class OrderData : EntityDataBase +{ + [Key] + public string Id { get; set; } = string.Empty; + public DateTime Date { get; set; } + + public virtual ICollection Items { get; set; } = new HashSet(); +} + +[Table("orderItems")] +public class OrderItemData : EntityDataBase, IWithReferenceId +{ + [Key] + public int Id { get; set; } + public int OrderId { get; set; } + + [ForeignKey(nameof(OrderId))] + public virtual OrderData? Order { get; set; } + + [Required] + [MaxLength(200)] + public string Name { get; set; } = string.Empty; +} +``` + +### The models +```csharp +public class Order +{ + public string Id { get; set; } = string.Empty; + public DateTime Date { get; set; } +} + +public class OrderItem +{ + public int Id { get; set; } + public int OrderId { get; set; } + public string Name { get; set; } = string.Empty; +} +``` + +### The request models +```csharp +public class OrderRequest +{ + public DateTime? Date { get; set; } +} + +public class OrderItemRequest +{ + public string? Name { get; set; } +} +``` +### The mappers + +```csharp +public class OrderMapper : IMapper, IMapper +{ + public Order? Map(OrderData? source) + { + return Map(source, new Order()); + } + + public Order? Map(OrderData? source, Order? destination) + { + if (source == null) + { + return null; + } + + if (destination == null) + { + return Map(source); + } + + destination.Id = source.Id; + destination.Date = source.Date; + + return destination; + } + + public OrderData? Map(OrderRequest? source) + { + return Map(source, new OrderData()); + } + + public OrderData? Map(OrderRequest? source, OrderData? destination) + { + if (source == null) + { + return null; + } + + if (destination == null) + { + return Map(source); + } + + destination.Date = source.Date ?? DateTime.UtcNow; + + return destination; + } +} +``` +### The services +```csharp +public interface IOrderService : ICrudServiceBase +{ + +} + +[MapCrudEndpoints] +public class OrderService : CrudServiceBase, IOrderService +{ + public OrderService(IQueryableUnitOfWork unitOfWork, IMapperFactory mapperFactory) : base(unitOfWork, mapperFactory) + { + } +} +``` + +### The `Program.cs` + +```csharp +var builder = WebApplication.CreateBuilder(args); +var assembly = typeof(Program).Assembly; + +builder.Services.AddDbContext(opt => + opt.UseInMemoryDatabase("ExampleDb")); + +builder.Services.AddQueryableRepositories(opt => +{ + opt.FromAssembly(assembly) + .AddLifetime(ServiceLifetime.Scoped); +}); + +builder.Services + .AddMappers(opt => opt.FromAssembly(assembly)) + .AddTransient() + .AddControllers() + .AddJsonOptions(options => + { + options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + }) + .AddFilterModelBinder() + .AddSortModelBinder(); + +builder.Services + .AddEndpointsApiExplorer() + .AddApiDocumentation(opt => opt.WithTitle("Example API")); + +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseApiDocumentation(); +} + +app.UseHttpsRedirection(); +app.UseRouting(); +app.MapControllers(); +app.MapCrud(); + +app.Run(); +``` + +or + +```csharp +... +app.MapAllCrud(assembly); +app.Run(); +``` \ No newline at end of file diff --git a/eQuantic.GoogleIdentityPlatform.Auth.sln b/eQuantic.GoogleIdentityPlatform.Auth.sln new file mode 100644 index 0000000..892bcec --- /dev/null +++ b/eQuantic.GoogleIdentityPlatform.Auth.sln @@ -0,0 +1,38 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "eQuantic.GoogleIdentityPlatform.Auth", "src\Auth\eQuantic.GoogleIdentityPlatform.Auth.csproj", "{C7B5BC4E-9FD1-45EE-9415-32E979229117}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{1D8FD0B3-830E-45B2-B248-33F9C20EC243}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "root", "root", "{46DF1D5B-A2C8-4748-995F-38BCC6D9BF49}" + ProjectSection(SolutionItems) = preProject + global.json = global.json + README.md = README.md + LICENSE = LICENSE + dotnetcore.yml = .github/workflows/dotnetcore.yml + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{B8BC6008-428B-44EA-895A-E92F3F328FEB}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflow", "workflow", "{5B1060A8-D4DE-4326-85A8-BEC4C15E132C}" + ProjectSection(SolutionItems) = preProject + .github\workflows\dotnetcore.yml = .github\workflows\dotnetcore.yml + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C7B5BC4E-9FD1-45EE-9415-32E979229117}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C7B5BC4E-9FD1-45EE-9415-32E979229117}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C7B5BC4E-9FD1-45EE-9415-32E979229117}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C7B5BC4E-9FD1-45EE-9415-32E979229117}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {C7B5BC4E-9FD1-45EE-9415-32E979229117} = {1D8FD0B3-830E-45B2-B248-33F9C20EC243} + {B8BC6008-428B-44EA-895A-E92F3F328FEB} = {46DF1D5B-A2C8-4748-995F-38BCC6D9BF49} + {5B1060A8-D4DE-4326-85A8-BEC4C15E132C} = {B8BC6008-428B-44EA-895A-E92F3F328FEB} + EndGlobalSection +EndGlobal diff --git a/global.json b/global.json new file mode 100644 index 0000000..aaac9e0 --- /dev/null +++ b/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "7.0.0", + "rollForward": "latestMinor", + "allowPrerelease": false + } +} \ No newline at end of file diff --git a/src/Auth/Extensions/ServiceCollectionExtensions.cs b/src/Auth/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..154675c --- /dev/null +++ b/src/Auth/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,32 @@ +using eQuantic.GoogleIdentityPlatform.Auth.Handlers; +using eQuantic.GoogleIdentityPlatform.Auth.Options; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.Extensions.DependencyInjection; + +namespace eQuantic.GoogleIdentityPlatform.Auth.Extensions; + +/// +/// Service Registry Extensions +/// +public static class ServiceCollectionExtensions +{ + /// + /// Add Google Identity Platform Authentication and Authorization + /// + /// The service collection + /// The options + /// The registry + public static IServiceCollection AddGoogleIdentityPlatformAuth(this IServiceCollection services, + Action? options = null) + { + var authOptions = new GoogleIdentityPlatformAuthOptions(); + options?.Invoke(authOptions); + services.AddSingleton(authOptions); + + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddScheme(JwtBearerDefaults + .AuthenticationScheme, opt => {}); + return services; + } +} \ No newline at end of file diff --git a/src/Auth/Handlers/FirebaseAuthenticationHandler.cs b/src/Auth/Handlers/FirebaseAuthenticationHandler.cs new file mode 100644 index 0000000..b64de29 --- /dev/null +++ b/src/Auth/Handlers/FirebaseAuthenticationHandler.cs @@ -0,0 +1,73 @@ +using System.Security.Claims; +using System.Text.Encodings.Web; +using eQuantic.GoogleIdentityPlatform.Auth.Options; +using FirebaseAdmin; +using FirebaseAdmin.Auth; +using Google.Apis.Auth.OAuth2; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace eQuantic.GoogleIdentityPlatform.Auth.Handlers; + +public class FirebaseAuthenticationHandler : AuthenticationHandler +{ + private const string AuthorizationKey = "Authorization"; + private const string BearerPrefix = "Bearer "; + private readonly GoogleIdentityPlatformAuthOptions _authOptions; + + public FirebaseAuthenticationHandler( + GoogleIdentityPlatformAuthOptions authOptions, + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder, + ISystemClock clock) : base(options, logger, encoder, clock) + { + _authOptions = authOptions; + } + + protected override async Task HandleAuthenticateAsync() + { + if (!Context.Request.Headers.ContainsKey(AuthorizationKey)) + { + return AuthenticateResult.NoResult(); + } + + var bearerToken = Context.Request.Headers[AuthorizationKey].ToString(); + if (string.IsNullOrEmpty(bearerToken) || !bearerToken.StartsWith(BearerPrefix)) + { + return AuthenticateResult.Fail("Invalid scheme"); + } + + var token = bearerToken[BearerPrefix.Length..]; + var firebaseApp = FirebaseApp.DefaultInstance ?? FirebaseApp.Create(new AppOptions + { + ProjectId = _authOptions.ProjectId, + Credential = GoogleCredential.FromAccessToken(token) + }); + var result = await FirebaseAuth.GetAuth(firebaseApp).VerifyIdTokenAsync(token); + + return AuthenticateResult.Success( + new AuthenticationTicket(new ClaimsPrincipal(new List + { + new(ToClaims(result.Claims), nameof(FirebaseAuthenticationHandler)) + }), + JwtBearerDefaults.AuthenticationScheme)); + } + + private static IEnumerable ToClaims(IReadOnlyDictionary resultClaims) + { + foreach (var (key, value) in resultClaims) + { + var newKey = key switch + { + "user_id" => "id", + "name" => "username", + _ => key + }; + yield return new Claim(newKey, + resultClaims.GetValueOrDefault(key, string.Empty).ToString() ?? string.Empty); + } + } +} \ No newline at end of file diff --git a/src/Auth/Icon.png b/src/Auth/Icon.png new file mode 100644 index 0000000..a46eba3 Binary files /dev/null and b/src/Auth/Icon.png differ diff --git a/src/Auth/Icon_details.png b/src/Auth/Icon_details.png new file mode 100644 index 0000000..658db64 Binary files /dev/null and b/src/Auth/Icon_details.png differ diff --git a/src/Auth/Icon_dialog.png b/src/Auth/Icon_dialog.png new file mode 100644 index 0000000..419796c Binary files /dev/null and b/src/Auth/Icon_dialog.png differ diff --git a/src/Auth/Icon_list.png b/src/Auth/Icon_list.png new file mode 100644 index 0000000..a46eba3 Binary files /dev/null and b/src/Auth/Icon_list.png differ diff --git a/src/Auth/Options/GoogleIdentityPlatformAuthOptions.cs b/src/Auth/Options/GoogleIdentityPlatformAuthOptions.cs new file mode 100644 index 0000000..cda097b --- /dev/null +++ b/src/Auth/Options/GoogleIdentityPlatformAuthOptions.cs @@ -0,0 +1,7 @@ +namespace eQuantic.GoogleIdentityPlatform.Auth.Options; + +public class GoogleIdentityPlatformAuthOptions +{ + public string? ProjectId { get; set; } + public string? ApiKey { get; set; } +} \ No newline at end of file diff --git a/src/Auth/eQuantic.GoogleIdentityPlatform.Auth.csproj b/src/Auth/eQuantic.GoogleIdentityPlatform.Auth.csproj new file mode 100644 index 0000000..8b6e557 --- /dev/null +++ b/src/Auth/eQuantic.GoogleIdentityPlatform.Auth.csproj @@ -0,0 +1,51 @@ + + + + eQuantic Google Identity Platform Auth Library + 2023 + eQuantic Systems + eQuantic.GoogleIdentityPlatform.Auth + eQuantic.GoogleIdentityPlatform.Auth + 1.0.0.0 + 1.0.0.0 + 1.0.0.0 + net7.0 + + eQuantic.GoogleIdentityPlatform.Auth + eQuantic;Google;Identity;Platform;Authentication;Authorization;Library + Google Identity Platform Auth implementations + https://github.com/eQuantic/core-googleidentityplatform-auth + ../artifacts/ + Icon.png + LICENSE + README.md + + false + false + false + false + false + false + True + + https://github.com/eQuantic/core-googleidentityplatform-auth + Git + latest + enable + enable + + + + + + + + + + + + + + + +