From e6224d1e2ab1f87fd6c49207de83611dac1218fb Mon Sep 17 00:00:00 2001 From: YuukanOO Date: Fri, 18 Dec 2020 12:27:02 +0100 Subject: [PATCH 1/8] add empty web project! --- Apps/Api/.gitignore | 442 ++++++++++++++++++ Apps/Api/.vscode/launch.json | 36 ++ Apps/Api/.vscode/tasks.json | 42 ++ Apps/Api/Api.csproj | 7 + Apps/Api/Program.cs | 20 + Apps/Api/Properties/launchSettings.json | 28 ++ Apps/Api/Startup.cs | 45 ++ Apps/Api/appsettings.Development.json | 9 + Apps/Api/appsettings.json | 10 + Apps/Website/Startup.cs | 15 +- Apps/Website/Website.csproj | 1 - Infrastructure/Infrastructure.csproj | 1 + Infrastructure/ServiceCollectionExtensions.cs | 41 ++ README.md | 9 + hn-dotnet.sln | 15 + 15 files changed, 708 insertions(+), 13 deletions(-) create mode 100644 Apps/Api/.gitignore create mode 100644 Apps/Api/.vscode/launch.json create mode 100644 Apps/Api/.vscode/tasks.json create mode 100644 Apps/Api/Api.csproj create mode 100644 Apps/Api/Program.cs create mode 100644 Apps/Api/Properties/launchSettings.json create mode 100644 Apps/Api/Startup.cs create mode 100644 Apps/Api/appsettings.Development.json create mode 100644 Apps/Api/appsettings.json create mode 100644 Infrastructure/ServiceCollectionExtensions.cs diff --git a/Apps/Api/.gitignore b/Apps/Api/.gitignore new file mode 100644 index 0000000..920d1cd --- /dev/null +++ b/Apps/Api/.gitignore @@ -0,0 +1,442 @@ +## 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 + +# Mono auto generated files +mono_crash.* + +# 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/ +[Ll]ogs/ + +# 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 +nunit-*.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 + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + +# 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 +# NuGet Symbol Packages +*.snupkg +# 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 +*.appxbundle +*.appxupload + +# 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/ + +# 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 +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).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/ + +# 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 + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# JetBrains Rider +.idea/ +*.sln.iml + +## +## Visual Studio Code +## +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json diff --git a/Apps/Api/.vscode/launch.json b/Apps/Api/.vscode/launch.json new file mode 100644 index 0000000..236bfb9 --- /dev/null +++ b/Apps/Api/.vscode/launch.json @@ -0,0 +1,36 @@ +{ + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (web)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/bin/Debug/net5.0/Api.dll", + "args": [], + "cwd": "${workspaceFolder}", + "stopAtEntry": false, + // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ] +} \ No newline at end of file diff --git a/Apps/Api/.vscode/tasks.json b/Apps/Api/.vscode/tasks.json new file mode 100644 index 0000000..41d341a --- /dev/null +++ b/Apps/Api/.vscode/tasks.json @@ -0,0 +1,42 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/Api.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/Api.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "${workspaceFolder}/Api.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/Apps/Api/Api.csproj b/Apps/Api/Api.csproj new file mode 100644 index 0000000..842a770 --- /dev/null +++ b/Apps/Api/Api.csproj @@ -0,0 +1,7 @@ + + + + net5.0 + + + diff --git a/Apps/Api/Program.cs b/Apps/Api/Program.cs new file mode 100644 index 0000000..377ac8c --- /dev/null +++ b/Apps/Api/Program.cs @@ -0,0 +1,20 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Api +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git a/Apps/Api/Properties/launchSettings.json b/Apps/Api/Properties/launchSettings.json new file mode 100644 index 0000000..97e75bf --- /dev/null +++ b/Apps/Api/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:13248", + "sslPort": 44312 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "Api": { + "commandName": "Project", + "dotnetRunMessages": "true", + "launchBrowser": true, + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/Apps/Api/Startup.cs b/Apps/Api/Startup.cs new file mode 100644 index 0000000..d982d09 --- /dev/null +++ b/Apps/Api/Startup.cs @@ -0,0 +1,45 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Api +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. + // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 + public void ConfigureServices(IServiceCollection services) + { + + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseRouting(); + + app.UseEndpoints(endpoints => + { + endpoints.MapGet("/", async context => + { + await context.Response.WriteAsync("Hello World!"); + }); + }); + } + } +} diff --git a/Apps/Api/appsettings.Development.json b/Apps/Api/appsettings.Development.json new file mode 100644 index 0000000..8983e0f --- /dev/null +++ b/Apps/Api/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git a/Apps/Api/appsettings.json b/Apps/Api/appsettings.json new file mode 100644 index 0000000..d9d9a9b --- /dev/null +++ b/Apps/Api/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" +} diff --git a/Apps/Website/Startup.cs b/Apps/Website/Startup.cs index b2ca043..3b23394 100644 --- a/Apps/Website/Startup.cs +++ b/Apps/Website/Startup.cs @@ -1,10 +1,5 @@ -using HN.Application; -using HN.Domain; using HN.Infrastructure; -using HN.Infrastructure.Behaviors; using HN.Infrastructure.Identity; -using HN.Infrastructure.Repositories; -using MediatR; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -30,13 +25,9 @@ namespace Website // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - services.AddDbContext(options => options.UseSqlite(Configuration.GetConnectionString("Default"))); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(typeof(IPipelineBehavior<,>), typeof(UnitOfWorkBehavior<,>)); - services.AddMediatR(typeof(HN.Application.IHNContext)); + services + .AddHN(Configuration) + .ResolveConnectedUserWith(); // Permet d'avoir des routes en lowercase services.Configure(options => diff --git a/Apps/Website/Website.csproj b/Apps/Website/Website.csproj index 3d54b85..e2f8af3 100644 --- a/Apps/Website/Website.csproj +++ b/Apps/Website/Website.csproj @@ -5,7 +5,6 @@ - diff --git a/Infrastructure/Infrastructure.csproj b/Infrastructure/Infrastructure.csproj index 5c7acfe..d940ad2 100644 --- a/Infrastructure/Infrastructure.csproj +++ b/Infrastructure/Infrastructure.csproj @@ -6,6 +6,7 @@ + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/Infrastructure/ServiceCollectionExtensions.cs b/Infrastructure/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..e88b93e --- /dev/null +++ b/Infrastructure/ServiceCollectionExtensions.cs @@ -0,0 +1,41 @@ +using HN.Application; +using HN.Domain; +using HN.Infrastructure.Behaviors; +using HN.Infrastructure.Repositories; +using MediatR; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace HN.Infrastructure +{ + public sealed class HNServicesBuilder + { + private readonly IServiceCollection _services; + + internal HNServicesBuilder(IServiceCollection services) + { + _services = services; + } + + public void ResolveConnectedUserWith() where TExecutingUserProvider : class, IExecutingUserProvider + { + _services.AddScoped(); + } + } + + public static class ServiceCollectionExtensions + { + public static HNServicesBuilder AddHN(this IServiceCollection services, IConfiguration configuration) + { + services.AddDbContext(options => options.UseSqlite(configuration.GetConnectionString("Default"))); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(typeof(IPipelineBehavior<,>), typeof(UnitOfWorkBehavior<,>)); + services.AddMediatR(typeof(HN.Application.IHNContext)); + + return new HNServicesBuilder(services); + } + } +} \ No newline at end of file diff --git a/README.md b/README.md index 35f9e11..b34dc6b 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,15 @@ $ dotnet add package Microsoft.EntityFrameworkCore.Design On installe les outils Entity framework `dotnet tool install --global dotnet-ef`. +On crée un projet d'api web vide (pour permettre de mieux comprendre comment fonctionne Asp.Net) avec : + +```console +$ cd Apps +$ dotnet new web -o Api +$ cd Api +$ dotnet new gitignore +``` + Pour plus tard, pour la génération de doc : project.csproj diff --git a/hn-dotnet.sln b/hn-dotnet.sln index ae29231..575a0b4 100644 --- a/hn-dotnet.sln +++ b/hn-dotnet.sln @@ -13,6 +13,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Apps", "Apps", "{7D23D5C3-1 EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Website", "Apps\Website\Website.csproj", "{44842863-BEB0-4718-BBD0-F7640D7AE0D0}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Api", "Apps\Api\Api.csproj", "{8F282012-6BE1-4756-9AE7-4B1AF4BD6738}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -74,8 +76,21 @@ Global {44842863-BEB0-4718-BBD0-F7640D7AE0D0}.Release|x64.Build.0 = Release|Any CPU {44842863-BEB0-4718-BBD0-F7640D7AE0D0}.Release|x86.ActiveCfg = Release|Any CPU {44842863-BEB0-4718-BBD0-F7640D7AE0D0}.Release|x86.Build.0 = Release|Any CPU + {8F282012-6BE1-4756-9AE7-4B1AF4BD6738}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8F282012-6BE1-4756-9AE7-4B1AF4BD6738}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8F282012-6BE1-4756-9AE7-4B1AF4BD6738}.Debug|x64.ActiveCfg = Debug|Any CPU + {8F282012-6BE1-4756-9AE7-4B1AF4BD6738}.Debug|x64.Build.0 = Debug|Any CPU + {8F282012-6BE1-4756-9AE7-4B1AF4BD6738}.Debug|x86.ActiveCfg = Debug|Any CPU + {8F282012-6BE1-4756-9AE7-4B1AF4BD6738}.Debug|x86.Build.0 = Debug|Any CPU + {8F282012-6BE1-4756-9AE7-4B1AF4BD6738}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8F282012-6BE1-4756-9AE7-4B1AF4BD6738}.Release|Any CPU.Build.0 = Release|Any CPU + {8F282012-6BE1-4756-9AE7-4B1AF4BD6738}.Release|x64.ActiveCfg = Release|Any CPU + {8F282012-6BE1-4756-9AE7-4B1AF4BD6738}.Release|x64.Build.0 = Release|Any CPU + {8F282012-6BE1-4756-9AE7-4B1AF4BD6738}.Release|x86.ActiveCfg = Release|Any CPU + {8F282012-6BE1-4756-9AE7-4B1AF4BD6738}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {44842863-BEB0-4718-BBD0-F7640D7AE0D0} = {7D23D5C3-15B1-407D-9FE1-E30C3FBBA1A4} + {8F282012-6BE1-4756-9AE7-4B1AF4BD6738} = {7D23D5C3-15B1-407D-9FE1-E30C3FBBA1A4} EndGlobalSection EndGlobal -- 2.39.5 From af913b7ba6ba47ec7102b3db84718e46614b54b8 Mon Sep 17 00:00:00 2001 From: YuukanOO Date: Fri, 18 Dec 2020 14:50:07 +0100 Subject: [PATCH 2/8] add NSwag documentation --- Apps/Api/Api.csproj | 14 ++++++++ Apps/Api/Controllers/LinksController.cs | 44 +++++++++++++++++++++++++ Apps/Api/HttpExecutingUserProvider.cs | 32 ++++++++++++++++++ Apps/Api/Startup.cs | 34 +++++++++++++++++++ Apps/Api/UserNotConnected.cs | 12 +++++++ Apps/Api/appsettings.json | 3 ++ README.md | 6 +++- 7 files changed, 144 insertions(+), 1 deletion(-) create mode 100644 Apps/Api/Controllers/LinksController.cs create mode 100644 Apps/Api/HttpExecutingUserProvider.cs create mode 100644 Apps/Api/UserNotConnected.cs diff --git a/Apps/Api/Api.csproj b/Apps/Api/Api.csproj index 842a770..2751af7 100644 --- a/Apps/Api/Api.csproj +++ b/Apps/Api/Api.csproj @@ -1,7 +1,21 @@ + + true + $(NoWarn);1591 + + + + + + + + + + net5.0 + diff --git a/Apps/Api/Controllers/LinksController.cs b/Apps/Api/Controllers/LinksController.cs new file mode 100644 index 0000000..9c2671b --- /dev/null +++ b/Apps/Api/Controllers/LinksController.cs @@ -0,0 +1,44 @@ +using System.Threading.Tasks; +using HN.Application; +using MediatR; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace Api.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public sealed class LinksController : ControllerBase + { + private readonly IMediator _bus; + + public LinksController(IMediator bus) + { + _bus = bus; + } + + /// + /// Retrieve all links already posted. + /// + /// + [ProducesResponseType(typeof(LinkDto[]), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task GetLinks() + { + return Ok(await _bus.Send(new ListLinksQuery())); + } + + /// + /// Post a new link. + /// + /// + /// + [HttpPost] + public async Task CreateLink(AddLinkCommand command) + { + var result = await _bus.Send(command); + + return Created("blabla", result); + } + } +} \ No newline at end of file diff --git a/Apps/Api/HttpExecutingUserProvider.cs b/Apps/Api/HttpExecutingUserProvider.cs new file mode 100644 index 0000000..57c3081 --- /dev/null +++ b/Apps/Api/HttpExecutingUserProvider.cs @@ -0,0 +1,32 @@ +using System; +using HN.Application; +using HN.Infrastructure.Identity; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; + +namespace Api +{ + public sealed class HttpExecutingUserProvider : IExecutingUserProvider + { + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly UserManager _userManager; + + public HttpExecutingUserProvider(IHttpContextAccessor httpContextAccessor, UserManager userManager) + { + _httpContextAccessor = httpContextAccessor; + _userManager = userManager; + } + + public Guid GetCurrentUserId() + { + var uid = _userManager.GetUserId(_httpContextAccessor.HttpContext.User); + + if (!Guid.TryParse(uid, out Guid result)) + { + throw new UserNotConnected(); + } + + return result; + } + } +} \ No newline at end of file diff --git a/Apps/Api/Startup.cs b/Apps/Api/Startup.cs index d982d09..bebf575 100644 --- a/Apps/Api/Startup.cs +++ b/Apps/Api/Startup.cs @@ -1,12 +1,24 @@ +using System; +using HN.Application; +using HN.Infrastructure; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Api { + public class MockExecutingContext : IExecutingUserProvider + { + public Guid GetCurrentUserId() + { + return Guid.NewGuid(); + } + } + public class Startup { public Startup(IConfiguration configuration) @@ -20,21 +32,43 @@ namespace Api // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { + services.AddHN(Configuration).ResolveConnectedUserWith(); + services.AddHttpContextAccessor(); + // Permet d'avoir des routes en lowercase + services.Configure(options => + { + options.LowercaseUrls = true; + options.LowercaseQueryStrings = true; + }); + + services.AddControllers(); + services.AddSwaggerDocument(d => + { + d.PostProcess = od => + { + od.Info.Title = "Hacker news like API in .Net"; + }; + d.SchemaType = NJsonSchema.SchemaType.OpenApi3; + }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { + app.UseOpenApi(); + if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); + app.UseSwaggerUi3(); } app.UseRouting(); app.UseEndpoints(endpoints => { + endpoints.MapControllers(); endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); diff --git a/Apps/Api/UserNotConnected.cs b/Apps/Api/UserNotConnected.cs new file mode 100644 index 0000000..87658b5 --- /dev/null +++ b/Apps/Api/UserNotConnected.cs @@ -0,0 +1,12 @@ +using System; + +namespace Api +{ + public sealed class UserNotConnected : Exception + { + public UserNotConnected() : base("User not connected!") + { + + } + } +} \ No newline at end of file diff --git a/Apps/Api/appsettings.json b/Apps/Api/appsettings.json index d9d9a9b..55f4a8f 100644 --- a/Apps/Api/appsettings.json +++ b/Apps/Api/appsettings.json @@ -6,5 +6,8 @@ "Microsoft.Hosting.Lifetime": "Information" } }, + "ConnectionStrings": { + "Default": "Data Source=../Website/hn.db" + }, "AllowedHosts": "*" } diff --git a/README.md b/README.md index b34dc6b..84cb22b 100644 --- a/README.md +++ b/README.md @@ -167,13 +167,17 @@ $ cd Api $ dotnet new gitignore ``` +L'attribut ApiController : https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-5.0#apicontroller-attribute + +On ajoute NSwag pour la génération de la documentation avec `dotnet add package NSwag.AspNetCore`. + Pour plus tard, pour la génération de doc : project.csproj true - bin\YourApi.XML + $(NoWarn);1591 ## Docker -- 2.39.5 From 5f389ae5f8bdb4c3569a22dfd8e54935c425a86d Mon Sep 17 00:00:00 2001 From: YuukanOO Date: Fri, 18 Dec 2020 15:06:24 +0100 Subject: [PATCH 3/8] generate swagger.json on build --- Apps/Api/Api.csproj | 10 +++ Apps/Api/swagger.json | 158 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 168 insertions(+) create mode 100644 Apps/Api/swagger.json diff --git a/Apps/Api/Api.csproj b/Apps/Api/Api.csproj index 2751af7..f245fe5 100644 --- a/Apps/Api/Api.csproj +++ b/Apps/Api/Api.csproj @@ -3,6 +3,7 @@ true $(NoWarn);1591 + @@ -11,11 +12,20 @@ + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + net5.0 + + + + + diff --git a/Apps/Api/swagger.json b/Apps/Api/swagger.json new file mode 100644 index 0000000..248b757 --- /dev/null +++ b/Apps/Api/swagger.json @@ -0,0 +1,158 @@ +{ + "x-generator": "NSwag v13.9.4.0 (NJsonSchema v10.3.1.0 (Newtonsoft.Json v12.0.0.0))", + "openapi": "3.0.0", + "info": { + "title": "Hacker news like API in .Net", + "version": "1.0.0" + }, + "paths": { + "/api/links": { + "get": { + "tags": [ + "Links" + ], + "summary": "Retrieve all links already posted.", + "operationId": "Links_GetLinks", + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LinkDto" + } + } + } + } + }, + "400": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + } + }, + "post": { + "tags": [ + "Links" + ], + "summary": "Post a new link.", + "operationId": "Links_CreateLink", + "requestBody": { + "x-name": "command", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AddLinkCommand" + } + } + }, + "required": true, + "x-position": 1 + }, + "responses": { + "200": { + "description": "", + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "LinkDto": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "format": "guid" + }, + "url": { + "type": "string", + "nullable": true + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "createdByName": { + "type": "string", + "nullable": true + }, + "upVotes": { + "type": "integer", + "format": "int32" + }, + "downVotes": { + "type": "integer", + "format": "int32" + } + } + }, + "ProblemDetails": { + "type": "object", + "additionalProperties": { + "nullable": true + }, + "properties": { + "type": { + "type": "string", + "nullable": true + }, + "title": { + "type": "string", + "nullable": true + }, + "status": { + "type": "integer", + "format": "int32", + "nullable": true + }, + "detail": { + "type": "string", + "nullable": true + }, + "instance": { + "type": "string", + "nullable": true + }, + "extensions": { + "type": "object", + "nullable": true, + "additionalProperties": {} + } + } + }, + "AddLinkCommand": { + "type": "object", + "additionalProperties": false, + "required": [ + "url" + ], + "properties": { + "url": { + "type": "string", + "format": "uri", + "minLength": 1 + } + } + } + } + } +} \ No newline at end of file -- 2.39.5 From 1d5570c5784a43e444bb5fd1294302e81519d084 Mon Sep 17 00:00:00 2001 From: Julien LEICHER Date: Mon, 21 Dec 2020 11:10:32 +0100 Subject: [PATCH 4/8] add needed routes in LinksController --- Application/CommentLink/CommentLinkCommand.cs | 3 +- Apps/Api/Controllers/LinksController.cs | 70 +++++- Apps/Api/Models/AddCommentViewModel.cs | 10 + Apps/Api/swagger.json | 200 +++++++++++++++++- 4 files changed, 277 insertions(+), 6 deletions(-) create mode 100644 Apps/Api/Models/AddCommentViewModel.cs diff --git a/Application/CommentLink/CommentLinkCommand.cs b/Application/CommentLink/CommentLinkCommand.cs index 233be2a..a75abb6 100644 --- a/Application/CommentLink/CommentLinkCommand.cs +++ b/Application/CommentLink/CommentLinkCommand.cs @@ -18,9 +18,10 @@ namespace HN.Application } - public CommentLinkCommand(Guid linkId) + public CommentLinkCommand(Guid linkId, string content = null) { LinkId = linkId; + Content = content; } } } \ No newline at end of file diff --git a/Apps/Api/Controllers/LinksController.cs b/Apps/Api/Controllers/LinksController.cs index 9c2671b..9fe3cdb 100644 --- a/Apps/Api/Controllers/LinksController.cs +++ b/Apps/Api/Controllers/LinksController.cs @@ -1,5 +1,8 @@ +using System; using System.Threading.Tasks; +using Api.Models; using HN.Application; +using HN.Domain; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -18,7 +21,7 @@ namespace Api.Controllers } /// - /// Retrieve all links already posted. + /// Récupère tous les liens postés. /// /// [ProducesResponseType(typeof(LinkDto[]), StatusCodes.Status200OK)] @@ -29,7 +32,68 @@ namespace Api.Controllers } /// - /// Post a new link. + /// Récupère um lien particulier. + /// + /// + [HttpGet("{id}")] + public async Task> GetLinkById(Guid id) + { + return Ok(await _bus.Send(new GetLinkQuery(id))); + } + + /// + /// Upvote un lien particulier. + /// + /// + /// + [HttpPut("{id}/upvote")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task Upvote(Guid id) + { + await _bus.Send(new VoteForLinkCommand(id, VoteType.Up)); + return NoContent(); + } + + /// + /// Downvote un lien particulier. + /// + /// + /// + [HttpPut("{id}/downvote")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task Downvote(Guid id) + { + await _bus.Send(new VoteForLinkCommand(id, VoteType.Down)); + return NoContent(); + } + + /// + /// Récupère les commentaires d'un lien particulier. + /// + /// + /// + [HttpGet("{id}/comments")] + public async Task> Comments(Guid id) + { + return Ok(await _bus.Send(new GetLinkCommentsQuery(id))); + } + + /// + /// Poste un nouveau commentaire sur un lien. + /// + /// + /// + /// + [HttpPost("{id}/comments")] + [ProducesResponseType(StatusCodes.Status201Created)] + public async Task AddComment(Guid id, AddCommentViewModel command) + { + var commentId = await _bus.Send(new CommentLinkCommand(id, command.Content)); + return CreatedAtAction("", "", new { id = commentId }, null); + } + + /// + /// Poste un nouveau lien. /// /// /// @@ -38,7 +102,7 @@ namespace Api.Controllers { var result = await _bus.Send(command); - return Created("blabla", result); + return CreatedAtAction(nameof(GetLinkById), new { id = result }); } } } \ No newline at end of file diff --git a/Apps/Api/Models/AddCommentViewModel.cs b/Apps/Api/Models/AddCommentViewModel.cs new file mode 100644 index 0000000..3216a7e --- /dev/null +++ b/Apps/Api/Models/AddCommentViewModel.cs @@ -0,0 +1,10 @@ +using System.ComponentModel.DataAnnotations; + +namespace Api.Models +{ + public sealed class AddCommentViewModel + { + [Required] + public string Content { get; set; } + } +} \ No newline at end of file diff --git a/Apps/Api/swagger.json b/Apps/Api/swagger.json index 248b757..cdc6792 100644 --- a/Apps/Api/swagger.json +++ b/Apps/Api/swagger.json @@ -11,7 +11,7 @@ "tags": [ "Links" ], - "summary": "Retrieve all links already posted.", + "summary": "Récupère tous les liens postés.", "operationId": "Links_GetLinks", "responses": { "200": { @@ -43,7 +43,7 @@ "tags": [ "Links" ], - "summary": "Post a new link.", + "summary": "Poste un nouveau lien.", "operationId": "Links_CreateLink", "requestBody": { "x-name": "command", @@ -71,6 +71,163 @@ } } } + }, + "/api/links/{id}": { + "get": { + "tags": [ + "Links" + ], + "summary": "Récupère um lien particulier.", + "operationId": "Links_GetLinkById", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "guid" + }, + "x-position": 1 + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LinkDto" + } + } + } + } + } + } + }, + "/api/links/{id}/upvote": { + "put": { + "tags": [ + "Links" + ], + "summary": "Upvote un lien particulier.", + "operationId": "Links_Upvote", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "guid" + }, + "x-position": 1 + } + ], + "responses": { + "204": { + "description": "" + } + } + } + }, + "/api/links/{id}/downvote": { + "put": { + "tags": [ + "Links" + ], + "summary": "Downvote un lien particulier.", + "operationId": "Links_Downvote", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "guid" + }, + "x-position": 1 + } + ], + "responses": { + "204": { + "description": "" + } + } + } + }, + "/api/links/{id}/comments": { + "get": { + "tags": [ + "Links" + ], + "summary": "Récupère les commentaires d'un lien particulier.", + "operationId": "Links_Comments", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "guid" + }, + "x-position": 1 + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CommentDto" + } + } + } + } + } + } + }, + "post": { + "tags": [ + "Links" + ], + "summary": "Poste un nouveau commentaire sur un lien.", + "operationId": "Links_AddComment", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "guid" + }, + "x-position": 1 + } + ], + "requestBody": { + "x-name": "command", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AddCommentViewModel" + } + } + }, + "required": true, + "x-position": 2 + }, + "responses": { + "201": { + "description": "" + } + } + } } }, "components": { @@ -139,6 +296,45 @@ } } }, + "CommentDto": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "format": "guid" + }, + "content": { + "type": "string", + "nullable": true + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "upVotes": { + "type": "integer", + "format": "int32" + }, + "downVotes": { + "type": "integer", + "format": "int32" + } + } + }, + "AddCommentViewModel": { + "type": "object", + "additionalProperties": false, + "required": [ + "content" + ], + "properties": { + "content": { + "type": "string", + "minLength": 1 + } + } + }, "AddLinkCommand": { "type": "object", "additionalProperties": false, -- 2.39.5 From 0ead15ce5a8657eefe8b294b67538979edae3eb5 Mon Sep 17 00:00:00 2001 From: Julien LEICHER Date: Mon, 21 Dec 2020 12:24:13 +0100 Subject: [PATCH 5/8] add bearer authentication! --- .vscode/launch.json | 90 +++++++++++-------- Apps/Api/Api.csproj | 1 + Apps/Api/Controllers/AccountsController.cs | 70 +++++++++++++++ Apps/Api/Controllers/LinksController.cs | 2 +- Apps/Api/Models/LoginViewModel.cs | 13 +++ Apps/Api/Startup.cs | 45 +++++++--- Apps/Api/appsettings.json | 5 +- Apps/Api/swagger.json | 72 +++++++++++++++ .../Website/Controllers/AccountsController.cs | 10 +-- 9 files changed, 251 insertions(+), 57 deletions(-) create mode 100644 Apps/Api/Controllers/AccountsController.cs create mode 100644 Apps/Api/Models/LoginViewModel.cs diff --git a/.vscode/launch.json b/.vscode/launch.json index 6691e2c..93bbaef 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,36 +1,56 @@ { - // Use IntelliSense to find out which attributes exist for C# debugging - // Use hover for the description of the existing attributes - // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md - "version": "0.2.0", - "configurations": [ - { - "name": ".NET Core Launch (web)", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build", - // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/Apps/Website/bin/Debug/net5.0/Website.dll", - "args": [], - "cwd": "${workspaceFolder}/Apps/Website", - "stopAtEntry": false, - // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser - "serverReadyAction": { - "action": "openExternally", - "pattern": "\\bNow listening on:\\s+(https?://\\S+)" - }, - "env": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "sourceFileMap": { - "/Views": "${workspaceFolder}/Views" - } - }, - { - "name": ".NET Core Attach", - "type": "coreclr", - "request": "attach", - "processId": "${command:pickProcess}" - } - ] -} \ No newline at end of file + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (api)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + "program": "${workspaceFolder}/Apps/Api/bin/Debug/net5.0/Api.dll", + "args": [], + "cwd": "${workspaceFolder}/Apps/Api", + "stopAtEntry": false, + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, + { + "name": ".NET Core Launch (web)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/Apps/Website/bin/Debug/net5.0/Website.dll", + "args": [], + "cwd": "${workspaceFolder}/Apps/Website", + "stopAtEntry": false, + // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ] +} diff --git a/Apps/Api/Api.csproj b/Apps/Api/Api.csproj index f245fe5..d748d6a 100644 --- a/Apps/Api/Api.csproj +++ b/Apps/Api/Api.csproj @@ -11,6 +11,7 @@ + runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Apps/Api/Controllers/AccountsController.cs b/Apps/Api/Controllers/AccountsController.cs new file mode 100644 index 0000000..ef3b315 --- /dev/null +++ b/Apps/Api/Controllers/AccountsController.cs @@ -0,0 +1,70 @@ +using System; +using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; +using Api.Models; +using HN.Infrastructure.Identity; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.IdentityModel.Tokens; + +namespace Api.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public sealed class AccountsController : ControllerBase + { + private readonly UserManager _usersManager; + private readonly SignInManager _signinManager; + private readonly TokenValidationParameters _tokenParameters; + + public AccountsController(UserManager usersManager, SignInManager signinManager, TokenValidationParameters tokenParameters) + { + _usersManager = usersManager; + _signinManager = signinManager; + _tokenParameters = tokenParameters; + } + + [Authorize] + public IActionResult GetUsers() + { + return Ok(_usersManager.Users.ToArray()); + } + + [HttpPost("login")] + public async Task Login(LoginViewModel command) + { + var user = await _usersManager.FindByNameAsync(command.Username); + + if (user == null) + { + return NotFound(); + } + + var result = await _signinManager.CheckPasswordSignInAsync(user, command.Password, false); + + if (!result.Succeeded) + { + return BadRequest(); + } + + var tokenDescriptor = new SecurityTokenDescriptor + { + Subject = new ClaimsIdentity(new Claim[] + { + new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), + new Claim(ClaimTypes.Name, command.Username), + }), + + Expires = DateTime.UtcNow.AddDays(7), + Issuer = _tokenParameters.ValidIssuer, + Audience = _tokenParameters.ValidAudience, + SigningCredentials = new SigningCredentials(_tokenParameters.IssuerSigningKey, SecurityAlgorithms.HmacSha256Signature) + }; + + return Ok(new JwtSecurityTokenHandler().CreateEncodedJwt(tokenDescriptor)); + } + } +} \ No newline at end of file diff --git a/Apps/Api/Controllers/LinksController.cs b/Apps/Api/Controllers/LinksController.cs index 9fe3cdb..d53038f 100644 --- a/Apps/Api/Controllers/LinksController.cs +++ b/Apps/Api/Controllers/LinksController.cs @@ -102,7 +102,7 @@ namespace Api.Controllers { var result = await _bus.Send(command); - return CreatedAtAction(nameof(GetLinkById), new { id = result }); + return CreatedAtAction(nameof(GetLinkById), new { id = result }, null); } } } \ No newline at end of file diff --git a/Apps/Api/Models/LoginViewModel.cs b/Apps/Api/Models/LoginViewModel.cs new file mode 100644 index 0000000..fc39401 --- /dev/null +++ b/Apps/Api/Models/LoginViewModel.cs @@ -0,0 +1,13 @@ +using System.ComponentModel.DataAnnotations; + +namespace Api.Models +{ + public sealed class LoginViewModel + { + [Required] + public string Username { get; set; } + + [Required] + public string Password { get; set; } + } +} \ No newline at end of file diff --git a/Apps/Api/Startup.cs b/Apps/Api/Startup.cs index bebf575..fb524d5 100644 --- a/Apps/Api/Startup.cs +++ b/Apps/Api/Startup.cs @@ -1,24 +1,19 @@ -using System; -using HN.Application; +using System.Text; using HN.Infrastructure; +using HN.Infrastructure.Identity; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.IdentityModel.Tokens; namespace Api { - public class MockExecutingContext : IExecutingUserProvider - { - public Guid GetCurrentUserId() - { - return Guid.NewGuid(); - } - } - public class Startup { public Startup(IConfiguration configuration) @@ -32,7 +27,7 @@ namespace Api // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { - services.AddHN(Configuration).ResolveConnectedUserWith(); + services.AddHN(Configuration).ResolveConnectedUserWith(); services.AddHttpContextAccessor(); // Permet d'avoir des routes en lowercase @@ -42,6 +37,31 @@ namespace Api options.LowercaseQueryStrings = true; }); + // Ajout de l'authentification + var tokenParams = new TokenValidationParameters + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ValidIssuer = Configuration["JwtIssuer"], + ValidAudience = Configuration["JwtAudience"], + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSecurityKey"])) + }; + + services.AddSingleton(tokenParams); + + services.AddIdentityCore() + .AddRoles() + .AddEntityFrameworkStores() + .AddSignInManager(); + + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(o => + { + o.TokenValidationParameters = tokenParams; + }); + services.AddControllers(); services.AddSwaggerDocument(d => { @@ -66,6 +86,9 @@ namespace Api app.UseRouting(); + app.UseAuthentication(); + app.UseAuthorization(); + app.UseEndpoints(endpoints => { endpoints.MapControllers(); diff --git a/Apps/Api/appsettings.json b/Apps/Api/appsettings.json index 55f4a8f..a4417a6 100644 --- a/Apps/Api/appsettings.json +++ b/Apps/Api/appsettings.json @@ -9,5 +9,8 @@ "ConnectionStrings": { "Default": "Data Source=../Website/hn.db" }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "JwtIssuer": "http://localhost", + "JwtAudience": "http://localhost", + "JwtSecurityKey": "CTtgxbcSFbpJmdmLDnr3Y8h5RWseN7t5" } diff --git a/Apps/Api/swagger.json b/Apps/Api/swagger.json index cdc6792..e8d9d6e 100644 --- a/Apps/Api/swagger.json +++ b/Apps/Api/swagger.json @@ -6,6 +6,60 @@ "version": "1.0.0" }, "paths": { + "/api/accounts": { + "get": { + "tags": [ + "Accounts" + ], + "operationId": "Accounts_GetUsers", + "responses": { + "200": { + "description": "", + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + } + } + } + }, + "/api/accounts/login": { + "post": { + "tags": [ + "Accounts" + ], + "operationId": "Accounts_Login", + "requestBody": { + "x-name": "command", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoginViewModel" + } + } + }, + "required": true, + "x-position": 1 + }, + "responses": { + "200": { + "description": "", + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + } + } + } + }, "/api/links": { "get": { "tags": [ @@ -232,6 +286,24 @@ }, "components": { "schemas": { + "LoginViewModel": { + "type": "object", + "additionalProperties": false, + "required": [ + "username", + "password" + ], + "properties": { + "username": { + "type": "string", + "minLength": 1 + }, + "password": { + "type": "string", + "minLength": 1 + } + } + }, "LinkDto": { "type": "object", "additionalProperties": false, diff --git a/Apps/Website/Controllers/AccountsController.cs b/Apps/Website/Controllers/AccountsController.cs index 0215466..daea63f 100644 --- a/Apps/Website/Controllers/AccountsController.cs +++ b/Apps/Website/Controllers/AccountsController.cs @@ -65,15 +65,7 @@ namespace Website.Controllers return View(); } - var user = await _userManager.FindByNameAsync(command.Username); - - if (user == null) - { - ModelState.AddModelError(nameof(LoginViewModel.Username), "Could not verify user identity"); - return View(); - } - - var result = await _signInManager.PasswordSignInAsync(user, command.Password, true, false); + var result = await _signInManager.PasswordSignInAsync(command.Username, command.Password, true, false); if (!result.Succeeded) { -- 2.39.5 From 009689449d2b9e9dd3cd5314ce3bdf6ebdb743eb Mon Sep 17 00:00:00 2001 From: YuukanOO Date: Mon, 21 Dec 2020 16:47:43 +0100 Subject: [PATCH 6/8] add authentication in swagger ui --- Apps/Api/Controllers/AccountsController.cs | 8 +---- Apps/Api/Controllers/LinksController.cs | 4 +++ Apps/Api/Startup.cs | 34 +++++++++++++++++++- Apps/Api/swagger.json | 36 +++++++++------------- 4 files changed, 52 insertions(+), 30 deletions(-) diff --git a/Apps/Api/Controllers/AccountsController.cs b/Apps/Api/Controllers/AccountsController.cs index ef3b315..4a29fb9 100644 --- a/Apps/Api/Controllers/AccountsController.cs +++ b/Apps/Api/Controllers/AccountsController.cs @@ -1,6 +1,5 @@ using System; using System.IdentityModel.Tokens.Jwt; -using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Api.Models; @@ -27,13 +26,8 @@ namespace Api.Controllers _tokenParameters = tokenParameters; } - [Authorize] - public IActionResult GetUsers() - { - return Ok(_usersManager.Users.ToArray()); - } - [HttpPost("login")] + [AllowAnonymous] public async Task Login(LoginViewModel command) { var user = await _usersManager.FindByNameAsync(command.Username); diff --git a/Apps/Api/Controllers/LinksController.cs b/Apps/Api/Controllers/LinksController.cs index d53038f..f67cce6 100644 --- a/Apps/Api/Controllers/LinksController.cs +++ b/Apps/Api/Controllers/LinksController.cs @@ -4,6 +4,7 @@ using Api.Models; using HN.Application; using HN.Domain; using MediatR; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -26,6 +27,7 @@ namespace Api.Controllers /// [ProducesResponseType(typeof(LinkDto[]), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] + [AllowAnonymous] public async Task GetLinks() { return Ok(await _bus.Send(new ListLinksQuery())); @@ -36,6 +38,7 @@ namespace Api.Controllers /// /// [HttpGet("{id}")] + [AllowAnonymous] public async Task> GetLinkById(Guid id) { return Ok(await _bus.Send(new GetLinkQuery(id))); @@ -73,6 +76,7 @@ namespace Api.Controllers /// /// [HttpGet("{id}/comments")] + [AllowAnonymous] public async Task> Comments(Guid id) { return Ok(await _bus.Send(new GetLinkCommentsQuery(id))); diff --git a/Apps/Api/Startup.cs b/Apps/Api/Startup.cs index fb524d5..545a609 100644 --- a/Apps/Api/Startup.cs +++ b/Apps/Api/Startup.cs @@ -1,3 +1,4 @@ +using System.Linq; using System.Text; using HN.Infrastructure; using HN.Infrastructure.Identity; @@ -6,11 +7,14 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; +using NSwag; +using NSwag.Generation.Processors.Security; namespace Api { @@ -62,13 +66,41 @@ namespace Api o.TokenValidationParameters = tokenParams; }); - services.AddControllers(); + services.AddControllers(o => + { + o.Filters.Add(new AuthorizeFilter()); + }); + services.AddSwaggerDocument(d => { + // cf. https://github.com/RicoSuter/NSwag/wiki/AspNetCore-Middleware#enable-authentication-in-generator-and-swagger-ui + + // Ajoute un type de sécurité à tout le document + d.AddSecurity("JWT", Enumerable.Empty(), new OpenApiSecurityScheme() + { + Type = OpenApiSecuritySchemeType.ApiKey, + Name = "Authorization", + In = OpenApiSecurityApiKeyLocation.Header, + Description = "Type into the textbox: Bearer {your JWT token}." + }); + + // d.DocumentProcessors.Add(new SecurityDefinitionAppender("JWT", new OpenApiSecurityScheme + // { + // Type = OpenApiSecuritySchemeType.ApiKey, + // Name = "Authorization", + // In = OpenApiSecurityApiKeyLocation.Header, + // Description = "Type into the textbox: Bearer {your JWT token}." + // })); + + // Permet la génération des info de sécurité par réflexion (attribut Authorize) + // Fonctionne mal avec les filtres par défaut ... + d.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("JWT")); + d.PostProcess = od => { od.Info.Title = "Hacker news like API in .Net"; }; + d.SchemaType = NJsonSchema.SchemaType.OpenApi3; }); } diff --git a/Apps/Api/swagger.json b/Apps/Api/swagger.json index e8d9d6e..d16fda3 100644 --- a/Apps/Api/swagger.json +++ b/Apps/Api/swagger.json @@ -6,27 +6,6 @@ "version": "1.0.0" }, "paths": { - "/api/accounts": { - "get": { - "tags": [ - "Accounts" - ], - "operationId": "Accounts_GetUsers", - "responses": { - "200": { - "description": "", - "content": { - "application/octet-stream": { - "schema": { - "type": "string", - "format": "binary" - } - } - } - } - } - } - }, "/api/accounts/login": { "post": { "tags": [ @@ -421,6 +400,19 @@ } } } + }, + "securitySchemes": { + "JWT": { + "type": "apiKey", + "description": "Type into the textbox: Bearer {your JWT token}.", + "name": "Authorization", + "in": "header" + } } - } + }, + "security": [ + { + "JWT": [] + } + ] } \ No newline at end of file -- 2.39.5 From de8b1e6e2167b0cf971fe291422dc57e6d2b1e82 Mon Sep 17 00:00:00 2001 From: Julien LEICHER Date: Mon, 21 Dec 2020 18:18:06 +0100 Subject: [PATCH 7/8] minor changes --- Apps/Api/Startup.cs | 2 +- Apps/Api/appsettings.Development.json | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Apps/Api/Startup.cs b/Apps/Api/Startup.cs index 545a609..06439a3 100644 --- a/Apps/Api/Startup.cs +++ b/Apps/Api/Startup.cs @@ -68,7 +68,7 @@ namespace Api services.AddControllers(o => { - o.Filters.Add(new AuthorizeFilter()); + o.Filters.Add(new AuthorizeFilter()); // Ou MapControllers().RequireAuthentication() }); services.AddSwaggerDocument(d => diff --git a/Apps/Api/appsettings.Development.json b/Apps/Api/appsettings.Development.json index 8983e0f..eaa8762 100644 --- a/Apps/Api/appsettings.Development.json +++ b/Apps/Api/appsettings.Development.json @@ -3,7 +3,8 @@ "LogLevel": { "Default": "Information", "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" + "Microsoft.Hosting.Lifetime": "Information", + "Microsoft.EntityFrameworkCore": "Information" } } } -- 2.39.5 From 37fb149a0c2742ce08b5c7dda8987c28dc9601e4 Mon Sep 17 00:00:00 2001 From: Julien LEICHER Date: Tue, 22 Dec 2020 11:02:10 +0100 Subject: [PATCH 8/8] add comments controller --- Apps/Api/Controllers/AccountsController.cs | 5 ++ Apps/Api/Controllers/CommentsController.cs | 48 ++++++++++++++++++++ Apps/Api/Startup.cs | 4 +- Apps/Api/swagger.json | 53 ++++++++++++++++++++++ 4 files changed, 107 insertions(+), 3 deletions(-) create mode 100644 Apps/Api/Controllers/CommentsController.cs diff --git a/Apps/Api/Controllers/AccountsController.cs b/Apps/Api/Controllers/AccountsController.cs index 4a29fb9..4f5fba0 100644 --- a/Apps/Api/Controllers/AccountsController.cs +++ b/Apps/Api/Controllers/AccountsController.cs @@ -26,6 +26,11 @@ namespace Api.Controllers _tokenParameters = tokenParameters; } + /// + /// Récupère un jeton d'accès pour un utilisateur particulier. + /// + /// + /// [HttpPost("login")] [AllowAnonymous] public async Task Login(LoginViewModel command) diff --git a/Apps/Api/Controllers/CommentsController.cs b/Apps/Api/Controllers/CommentsController.cs new file mode 100644 index 0000000..4db8c37 --- /dev/null +++ b/Apps/Api/Controllers/CommentsController.cs @@ -0,0 +1,48 @@ +using System; +using System.Threading.Tasks; +using HN.Application; +using HN.Domain; +using MediatR; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace Api.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public sealed class CommentsController : ControllerBase + { + private readonly IMediator _bus; + + public CommentsController(IMediator bus) + { + _bus = bus; + } + + /// + /// Upvote un commentaire particulier. + /// + /// + /// + [HttpPut("{id}/upvote")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task Upvote(Guid id) + { + await _bus.Send(new VoteForCommentCommand(id, VoteType.Up)); + return NoContent(); + } + + /// + /// Downvote un commentaire particulier. + /// + /// + /// + [HttpPut("{id}/downvote")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task Downvote(Guid id) + { + await _bus.Send(new VoteForCommentCommand(id, VoteType.Down)); + return NoContent(); + } + } +} \ No newline at end of file diff --git a/Apps/Api/Startup.cs b/Apps/Api/Startup.cs index 06439a3..f6570a8 100644 --- a/Apps/Api/Startup.cs +++ b/Apps/Api/Startup.cs @@ -71,7 +71,7 @@ namespace Api o.Filters.Add(new AuthorizeFilter()); // Ou MapControllers().RequireAuthentication() }); - services.AddSwaggerDocument(d => + services.AddOpenApiDocument(d => { // cf. https://github.com/RicoSuter/NSwag/wiki/AspNetCore-Middleware#enable-authentication-in-generator-and-swagger-ui @@ -100,8 +100,6 @@ namespace Api { od.Info.Title = "Hacker news like API in .Net"; }; - - d.SchemaType = NJsonSchema.SchemaType.OpenApi3; }); } diff --git a/Apps/Api/swagger.json b/Apps/Api/swagger.json index d16fda3..4a56ec2 100644 --- a/Apps/Api/swagger.json +++ b/Apps/Api/swagger.json @@ -11,6 +11,7 @@ "tags": [ "Accounts" ], + "summary": "Récupère un jeton d'accès pour un utilisateur particulier.", "operationId": "Accounts_Login", "requestBody": { "x-name": "command", @@ -39,6 +40,58 @@ } } }, + "/api/comments/{id}/upvote": { + "put": { + "tags": [ + "Comments" + ], + "summary": "Upvote un commentaire particulier.", + "operationId": "Comments_Upvote", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "guid" + }, + "x-position": 1 + } + ], + "responses": { + "204": { + "description": "" + } + } + } + }, + "/api/comments/{id}/downvote": { + "put": { + "tags": [ + "Comments" + ], + "summary": "Downvote un commentaire particulier.", + "operationId": "Comments_Downvote", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "guid" + }, + "x-position": 1 + } + ], + "responses": { + "204": { + "description": "" + } + } + } + }, "/api/links": { "get": { "tags": [ -- 2.39.5