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/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/.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..d748d6a --- /dev/null +++ b/Apps/Api/Api.csproj @@ -0,0 +1,32 @@ + + + + true + $(NoWarn);1591 + + + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + net5.0 + + + + + + + + + diff --git a/Apps/Api/Controllers/AccountsController.cs b/Apps/Api/Controllers/AccountsController.cs new file mode 100644 index 0000000..4f5fba0 --- /dev/null +++ b/Apps/Api/Controllers/AccountsController.cs @@ -0,0 +1,69 @@ +using System; +using System.IdentityModel.Tokens.Jwt; +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; + } + + /// + /// Récupère un jeton d'accès pour un utilisateur particulier. + /// + /// + /// + [HttpPost("login")] + [AllowAnonymous] + 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/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/Controllers/LinksController.cs b/Apps/Api/Controllers/LinksController.cs new file mode 100644 index 0000000..f67cce6 --- /dev/null +++ b/Apps/Api/Controllers/LinksController.cs @@ -0,0 +1,112 @@ +using System; +using System.Threading.Tasks; +using Api.Models; +using HN.Application; +using HN.Domain; +using MediatR; +using Microsoft.AspNetCore.Authorization; +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; + } + + /// + /// Récupère tous les liens postés. + /// + /// + [ProducesResponseType(typeof(LinkDto[]), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [AllowAnonymous] + public async Task GetLinks() + { + return Ok(await _bus.Send(new ListLinksQuery())); + } + + /// + /// Récupère um lien particulier. + /// + /// + [HttpGet("{id}")] + [AllowAnonymous] + 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")] + [AllowAnonymous] + 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. + /// + /// + /// + [HttpPost] + public async Task CreateLink(AddLinkCommand command) + { + var result = await _bus.Send(command); + + return CreatedAtAction(nameof(GetLinkById), new { id = result }, null); + } + } +} \ 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/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/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/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..f6570a8 --- /dev/null +++ b/Apps/Api/Startup.cs @@ -0,0 +1,132 @@ +using System.Linq; +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.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 +{ + 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) + { + services.AddHN(Configuration).ResolveConnectedUserWith(); + services.AddHttpContextAccessor(); + + // Permet d'avoir des routes en lowercase + services.Configure(options => + { + options.LowercaseUrls = true; + 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(o => + { + o.Filters.Add(new AuthorizeFilter()); // Ou MapControllers().RequireAuthentication() + }); + + services.AddOpenApiDocument(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"; + }; + }); + } + + // 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.UseAuthentication(); + app.UseAuthorization(); + + 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.Development.json b/Apps/Api/appsettings.Development.json new file mode 100644 index 0000000..eaa8762 --- /dev/null +++ b/Apps/Api/appsettings.Development.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information", + "Microsoft.EntityFrameworkCore": "Information" + } + } +} diff --git a/Apps/Api/appsettings.json b/Apps/Api/appsettings.json new file mode 100644 index 0000000..a4417a6 --- /dev/null +++ b/Apps/Api/appsettings.json @@ -0,0 +1,16 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "ConnectionStrings": { + "Default": "Data Source=../Website/hn.db" + }, + "AllowedHosts": "*", + "JwtIssuer": "http://localhost", + "JwtAudience": "http://localhost", + "JwtSecurityKey": "CTtgxbcSFbpJmdmLDnr3Y8h5RWseN7t5" +} diff --git a/Apps/Api/swagger.json b/Apps/Api/swagger.json new file mode 100644 index 0000000..4a56ec2 --- /dev/null +++ b/Apps/Api/swagger.json @@ -0,0 +1,471 @@ +{ + "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/accounts/login": { + "post": { + "tags": [ + "Accounts" + ], + "summary": "Récupère un jeton d'accès pour un utilisateur particulier.", + "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/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": [ + "Links" + ], + "summary": "Récupère tous les liens postés.", + "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": "Poste un nouveau lien.", + "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" + } + } + } + } + } + } + }, + "/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": { + "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, + "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": {} + } + } + }, + "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, + "required": [ + "url" + ], + "properties": { + "url": { + "type": "string", + "format": "uri", + "minLength": 1 + } + } + } + }, + "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 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) { 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..84cb22b 100644 --- a/README.md +++ b/README.md @@ -158,13 +158,26 @@ $ 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 +``` + +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 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