add-api-project (#29)

This commit is contained in:
Julien Leicher 2020-12-22 14:01:58 +01:00
parent 93e231928f
commit dcdb5da899
26 changed files with 1657 additions and 59 deletions

90
.vscode/launch.json vendored
View File

@ -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}"
}
]
}
// 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}"
}
]
}

View File

@ -18,9 +18,10 @@ namespace HN.Application
}
public CommentLinkCommand(Guid linkId)
public CommentLinkCommand(Guid linkId, string content = null)
{
LinkId = linkId;
Content = content;
}
}
}

442
Apps/Api/.gitignore vendored Normal file
View File

@ -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

36
Apps/Api/.vscode/launch.json vendored Normal file
View File

@ -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}"
}
]
}

42
Apps/Api/.vscode/tasks.json vendored Normal file
View File

@ -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"
}
]
}

32
Apps/Api/Api.csproj Normal file
View File

@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
<!-- <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> -->
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Infrastructure\Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.1" />
<PackageReference Include="NSwag.AspNetCore" Version="13.9.4" />
<PackageReference Include="NSwag.MSBuild" Version="13.9.4">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<!-- Permet de générer le fichier de description de l'api à chaque build qui sera utile pour la génération du client -->
<Target Name="NSwag" AfterTargets="Build">
<Exec EnvironmentVariables="ASPNETCORE_ENVIRONMENT=Development" Command="$(NSwagExe_Net50) aspnetcore2openapi /assembly:$(TargetDir)Api.dll /output:swagger.json" />
</Target>
</Project>

View File

@ -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<User> _usersManager;
private readonly SignInManager<User> _signinManager;
private readonly TokenValidationParameters _tokenParameters;
public AccountsController(UserManager<User> usersManager, SignInManager<User> signinManager, TokenValidationParameters tokenParameters)
{
_usersManager = usersManager;
_signinManager = signinManager;
_tokenParameters = tokenParameters;
}
/// <summary>
/// Récupère un jeton d'accès pour un utilisateur particulier.
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
[HttpPost("login")]
[AllowAnonymous]
public async Task<IActionResult> 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));
}
}
}

View File

@ -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;
}
/// <summary>
/// Upvote un commentaire particulier.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPut("{id}/upvote")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> Upvote(Guid id)
{
await _bus.Send(new VoteForCommentCommand(id, VoteType.Up));
return NoContent();
}
/// <summary>
/// Downvote un commentaire particulier.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPut("{id}/downvote")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> Downvote(Guid id)
{
await _bus.Send(new VoteForCommentCommand(id, VoteType.Down));
return NoContent();
}
}
}

View File

@ -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;
}
/// <summary>
/// Récupère tous les liens postés.
/// </summary>
/// <returns></returns>
[ProducesResponseType(typeof(LinkDto[]), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[AllowAnonymous]
public async Task<IActionResult> GetLinks()
{
return Ok(await _bus.Send(new ListLinksQuery()));
}
/// <summary>
/// Récupère um lien particulier.
/// </summary>
/// <param name="id"></param>
[HttpGet("{id}")]
[AllowAnonymous]
public async Task<ActionResult<LinkDto>> GetLinkById(Guid id)
{
return Ok(await _bus.Send(new GetLinkQuery(id)));
}
/// <summary>
/// Upvote un lien particulier.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPut("{id}/upvote")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> Upvote(Guid id)
{
await _bus.Send(new VoteForLinkCommand(id, VoteType.Up));
return NoContent();
}
/// <summary>
/// Downvote un lien particulier.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPut("{id}/downvote")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> Downvote(Guid id)
{
await _bus.Send(new VoteForLinkCommand(id, VoteType.Down));
return NoContent();
}
/// <summary>
/// Récupère les commentaires d'un lien particulier.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("{id}/comments")]
[AllowAnonymous]
public async Task<ActionResult<CommentDto[]>> Comments(Guid id)
{
return Ok(await _bus.Send(new GetLinkCommentsQuery(id)));
}
/// <summary>
/// Poste un nouveau commentaire sur un lien.
/// </summary>
/// <param name="id"></param>
/// <param name="command"></param>
/// <returns></returns>
[HttpPost("{id}/comments")]
[ProducesResponseType(StatusCodes.Status201Created)]
public async Task<IActionResult> AddComment(Guid id, AddCommentViewModel command)
{
var commentId = await _bus.Send(new CommentLinkCommand(id, command.Content));
return CreatedAtAction("", "", new { id = commentId }, null);
}
/// <summary>
/// Poste un nouveau lien.
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> CreateLink(AddLinkCommand command)
{
var result = await _bus.Send(command);
return CreatedAtAction(nameof(GetLinkById), new { id = result }, null);
}
}
}

View File

@ -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<User> _userManager;
public HttpExecutingUserProvider(IHttpContextAccessor httpContextAccessor, UserManager<User> 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;
}
}
}

View File

@ -0,0 +1,10 @@
using System.ComponentModel.DataAnnotations;
namespace Api.Models
{
public sealed class AddCommentViewModel
{
[Required]
public string Content { get; set; }
}
}

View File

@ -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; }
}
}

20
Apps/Api/Program.cs Normal file
View File

@ -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<Startup>();
});
}
}

View File

@ -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"
}
}
}
}

132
Apps/Api/Startup.cs Normal file
View File

@ -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<HttpExecutingUserProvider>();
services.AddHttpContextAccessor();
// Permet d'avoir des routes en lowercase
services.Configure<RouteOptions>(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<User>()
.AddRoles<Role>()
.AddEntityFrameworkStores<HNDbContext>()
.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<string>(), 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!");
});
});
}
}
}

View File

@ -0,0 +1,12 @@
using System;
namespace Api
{
public sealed class UserNotConnected : Exception
{
public UserNotConnected() : base("User not connected!")
{
}
}
}

View File

@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore": "Information"
}
}
}

16
Apps/Api/appsettings.json Normal file
View File

@ -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"
}

471
Apps/Api/swagger.json Normal file
View File

@ -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": []
}
]
}

View File

@ -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)
{

View File

@ -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<HNDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("Default")));
services.AddScoped<IHNContext, HNDbContext>();
services.AddScoped<ILinkRepository, LinkRepository>();
services.AddScoped<ICommentRepository, CommentRepository>();
services.AddScoped<IExecutingUserProvider, HttpExecutingUserProvider>();
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(UnitOfWorkBehavior<,>));
services.AddMediatR(typeof(HN.Application.IHNContext));
services
.AddHN(Configuration)
.ResolveConnectedUserWith<HttpExecutingUserProvider>();
// Permet d'avoir des routes en lowercase
services.Configure<RouteOptions>(options =>

View File

@ -5,7 +5,6 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="9.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.0" />
</ItemGroup>

View File

@ -6,6 +6,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.0" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="9.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>

View File

@ -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<TExecutingUserProvider>() where TExecutingUserProvider : class, IExecutingUserProvider
{
_services.AddScoped<IExecutingUserProvider, TExecutingUserProvider>();
}
}
public static class ServiceCollectionExtensions
{
public static HNServicesBuilder AddHN(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<HNDbContext>(options => options.UseSqlite(configuration.GetConnectionString("Default")));
services.AddScoped<IHNContext, HNDbContext>();
services.AddScoped<ILinkRepository, LinkRepository>();
services.AddScoped<ICommentRepository, CommentRepository>();
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(UnitOfWorkBehavior<,>));
services.AddMediatR(typeof(HN.Application.IHNContext));
return new HNServicesBuilder(services);
}
}
}

View File

@ -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
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<DocumentationFile>bin\YourApi.XML</DocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
## Docker

View File

@ -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