Compare commits

...

9 Commits

Author SHA1 Message Date
Julien LEICHER
37fb149a0c
add comments controller 2020-12-22 14:00:51 +01:00
Julien LEICHER
de8b1e6e21
minor changes 2020-12-22 14:00:51 +01:00
YuukanOO
009689449d
add authentication in swagger ui 2020-12-22 14:00:50 +01:00
Julien LEICHER
0ead15ce5a
add bearer authentication! 2020-12-22 14:00:50 +01:00
Julien LEICHER
1d5570c578
add needed routes in LinksController 2020-12-22 14:00:49 +01:00
YuukanOO
5f389ae5f8
generate swagger.json on build 2020-12-22 14:00:49 +01:00
YuukanOO
af913b7ba6
add NSwag documentation 2020-12-22 14:00:48 +01:00
YuukanOO
e6224d1e2a
add empty web project! 2020-12-22 14:00:48 +01:00
93e231928f mvc-styles (#28) 2020-12-22 10:47:22 +01:00
41 changed files with 1962 additions and 225 deletions

20
.vscode/launch.json vendored
View File

@ -4,6 +4,26 @@
// 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",

View File

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

View File

@ -7,6 +7,7 @@ namespace HN.Application
public Guid Id { get; set; }
public string Content { get; set; }
public DateTime CreatedAt { get; set; }
public string CreatedByName { get; set; }
public int UpVotes { get; set; }
public int DownVotes { get; set; }

View File

@ -18,11 +18,13 @@ namespace HN.Application
public Task<CommentDto[]> Handle(GetLinkCommentsQuery request, CancellationToken cancellationToken)
{
var comments = from comment in _context.Comments
join user in _context.Users on comment.CreatedBy equals user.Id
where comment.LinkId == request.LinkId
select new CommentDto
{
Id = comment.Id,
CreatedAt = comment.CreatedAt,
CreatedByName = user.UserName,
Content = comment.Content,
UpVotes = comment.Votes.Count(c => c.Type == VoteType.Up),
DownVotes = comment.Votes.Count(c => c.Type == VoteType.Down)

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

@ -12,6 +12,7 @@ namespace Website.Models
[Required]
[Compare(nameof(Password))]
[Display(Name = "Password confirmation")]
public string PasswordConfirm { get; set; }
}
}

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 =>
@ -107,7 +98,7 @@ namespace Website
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
pattern: "{controller=Links}/{action=Index}/{id?}");
});
}

View File

@ -1,13 +1,20 @@
@model LoginViewModel
@{
ViewData["Title"] = "Login";
}
<form asp-action="Login" method="post">
<form class="form" asp-action="Login" method="post">
<div class="field">
<label asp-for="@Model.Username"></label>
<input asp-for="@Model.Username" />
<span asp-validation-for="@Model.Username"></span>
</div>
<div class="field">
<label asp-for="@Model.Password"></label>
<input type="password" asp-for="@Model.Password" />
<span asp-validation-for="@Model.Password"></span>
</div>
<button type="submit">Sign in</button>
</form>

View File

@ -1,17 +1,27 @@
@model RegisterViewModel
@{
ViewData["Title"] = "Register";
}
<form asp-action="Register" method="post">
<form class="form" asp-action="Register" method="post">
<div class="field">
<label asp-for="@Model.Username"></label>
<input asp-for="@Model.Username" />
<span asp-validation-for="@Model.Username"></span>
</div>
<div class="field">
<label asp-for="@Model.Password"></label>
<input type="password" asp-for="@Model.Password" />
<span asp-validation-for="@Model.Password"></span>
</div>
<div class="field">
<label asp-for="@Model.PasswordConfirm"></label>
<input type="password" asp-for="@Model.PasswordConfirm" />
<span asp-validation-for="@Model.PasswordConfirm"></span>
</div>
<button type="submit">Register</button>
</form>

View File

@ -3,15 +3,16 @@
ViewData["Title"] = "Post a new link";
}
<form method="post">
<div>
<form class="form" method="post">
@* @Html.LabelFor(m => m.Url)
@Html.EditorFor(m => m.Url)
@Html.ValidationMessageFor(m => m.Url) *@
<div class="field">
<label asp-for="@Model.Url"></label>
<input asp-for="@Model.Url" />
<span asp-validation-for="@Model.Url"></span>
</div>
<button type="submit">Post!</button>
</form>

View File

@ -3,10 +3,9 @@
ViewData["Title"] = "Latest Links";
}
<a asp-action="Create" title="New post">Post a new super duber link</a>
<a class="mb" asp-action="Create" title="New post">Share a link with the world!</a>
<p>Here are the links</p>
<ul>
<ul class="links">
@foreach (var link in Model)
{
<li>

View File

@ -1,14 +1,22 @@
@model ShowLinkViewModel
@{
ViewData["Title"] = "Viewing";
}
<partial name="_LinkItem" model="@Model.Link" />
@if(Model.Comments.Length == 0) {
<p>No comments yet</p>
} else {
<ul>
@if (Model.Comments.Length == 0)
{
<p class="no-comment-yet">No comments yet</p>
}
else
{
<ul class="comments">
@foreach (var comment in Model.Comments)
{
<li><partial name="_CommentItem" model="@comment" /></li>
<li>
<partial name="_CommentItem" model="@comment" />
</li>
}
</ul>
}

View File

@ -1,2 +1,2 @@
<a asp-action="Register" asp-controller="Accounts">Register</a>
<a asp-action="Login" asp-controller="Accounts">Sign in</a>
<a asp-action="Register" asp-controller="Accounts">Register</a> or <a asp-action="Login" asp-controller="Accounts">Sign
in</a>

View File

@ -1,4 +1,6 @@
<p>Connected as @User.Identity.Name</p>
<div class="loggedin-panel">
<p>Connected as <strong>@User.Identity.Name</strong></p>
<form asp-action="Logout" asp-controller="Accounts" method="post">
<button type="submit">Sign out</button>
<button class="loggedin-panel__out" type="submit">Sign out</button>
</form>
</div>

View File

@ -1,16 +1,21 @@
@model HN.Application.CommentLinkCommand
<div>
<h2>Add a comment</h2>
@if(User.Identity.IsAuthenticated) {
<form asp-action="Create" asp-controller="Comments" method="post">
<h3 class="add-a-comment">Add a comment</h3>
@if (User.Identity.IsAuthenticated)
{
<form class="form" asp-action="Create" asp-controller="Comments" method="post">
<div class="field">
<input type="hidden" asp-for="@Model.LinkId" />
<textarea asp-for="@Model.Content"></textarea>
<span asp-validation-for="@Model.Content"></span>
</div>
<button type="submit">Post a comment</button>
</form>
} else {
}
else
{
<p>Only logged in users can comment.</p>
}
</div>

View File

@ -1,14 +1,21 @@
@model HN.Application.CommentDto
<span>@Model.Content</span>
<div>
👍: @Model.UpVotes / 👎: @Model.DownVotes
</div>
@if (User.Identity.IsAuthenticated) {
<form asp-action="Vote" asp-controller="Comments" asp-route-id="@Model.Id" method="post">
<article class="comment">
<p>@Model.Content</p>
<ul class="comment__actions">
<li>posted at @Model.CreatedAt.ToLocalTime() by <strong>@Model.CreatedByName</strong></li>
<li>
<strong>@Model.UpVotes</strong> 👍 / <strong>@Model.DownVotes</strong> 👎
</li>
@if (User.Identity.IsAuthenticated)
{
<li>
<form class="votable" asp-controller="Comments" asp-action="Vote" asp-route-id="@Model.Id" method="post">
<input type="hidden" name="redirectTo" value="@Context.Request.Path" />
<input type="submit" name="type" value="up" />
<input type="submit" name="type" value="down" />
vote&nbsp;<input type="submit" name="type" value="up" />&nbsp;or&nbsp;<input type="submit" name="type"
value="down" />
</form>
</li>
}
</ul>
</article>

View File

@ -1,51 +1,31 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Website</title>
<link rel="stylesheet" asp-append-version="true" href="~/css/site.css" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Website</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Links" asp-action="Index">Links</a>
</li>
</ul>
</div>
<body>
<header class="topnav">
<div class="logo">
<a class="logo__link" href="/" title="back home">hn-dotnet</a>
</div>
<div class="topnav__account">
<vc:login />
</div>
</nav>
</header>
<div class="container">
<main class="main-content">
<partial name="_FlashMessage" />
<main role="main" class="pb-3">
<h1 class="main-content__title">@ViewData["Title"]</h1>
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2020 - Website - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

View File

@ -1,11 +1,26 @@
@model HN.Application.LinkDto
<a asp-action="Show" asp-controller="Links" asp-route-id="@Model.Id">@Model.Url - created at @Model.CreatedAt.ToLocalTime() by @Model.CreatedByName (👍: @Model.UpVotes / 👎: @Model.DownVotes)</a>
<article class="link">
<h2>
<a class="link_title" href="@Model.Url" rel="nofollow">@Model.Url</a>
</h2>
@if(User.Identity.IsAuthenticated) {
<form asp-controller="Links" asp-action="Vote" asp-route-id="@Model.Id" asp-route-url="@Model.Url" method="post">
<ul class="link__actions">
<li><a asp-action="Show" asp-controller="Links" asp-route-id="@Model.Id">🔍 view</a></li>
<li>posted at @Model.CreatedAt.ToLocalTime() by <strong>@Model.CreatedByName</strong></li>
<li>
<strong>@Model.UpVotes</strong> 👍 / <strong>@Model.DownVotes</strong> 👎
</li>
@if (User.Identity.IsAuthenticated)
{
<li>
<form class="votable" asp-controller="Links" asp-action="Vote" asp-route-id="@Model.Id" asp-route-url="@Model.Url"
method="post">
<input type="hidden" name="redirectTo" value="@Context.Request.Path" />
<input type="submit" name="type" value="up" />
<input type="submit" name="type" value="down" />
vote&nbsp;<input type="submit" name="type" value="up" />&nbsp;or&nbsp;<input type="submit" name="type"
value="down" />
</form>
</li>
}
</ul>
</article>

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

@ -1,71 +1,172 @@
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
/* Provide sufficient contrast against white background */
a {
color: #0366d6;
}
.btn-primary {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
/* Sticky footer styles
-------------------------------------------------- */
html {
font-size: 14px;
}
@media (min-width: 768px) {
html {
font-size: 16px;
}
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
/* Sticky footer styles
-------------------------------------------------- */
html {
position: relative;
min-height: 100%;
* {
margin: 0;
padding: 0;
}
body {
/* Margin bottom by footer height */
margin-bottom: 60px;
background-color: #efefef;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif,
"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
font-size: 1em;
line-height: 1.4;
}
.footer {
position: absolute;
bottom: 0;
a {
color: darkblue;
}
.mb {
display: block;
margin-bottom: 1rem;
}
.topnav {
background-color: orangered;
color: rgba(255, 255, 255, 0.87);
display: flex;
justify-content: space-between;
padding: 1rem;
}
.topnav a {
color: white;
font-weight: bold;
text-decoration: none;
}
.loggedin-panel {
display: flex;
align-items: center;
}
.loggedin-panel__out {
background-color: transparent;
border: none;
color: white;
cursor: pointer;
font: inherit;
font-weight: bold;
margin-left: 1rem;
appearance: none;
}
.main-content {
margin: 2rem auto;
max-width: 900px;
width: 100%;
white-space: nowrap;
line-height: 60px; /* Vertically center the text there */
}
.main-content__title {
font-size: 2rem;
font-weight: bolder;
color: gray;
}
.links,
.comments {
list-style-type: none;
}
.link,
.form {
background-color: white;
padding: 1rem;
box-shadow: 0 4px 4px rgba(0, 0, 0, 0.12);
margin-bottom: 1rem;
}
.link_title {
color: rgba(0, 0, 0, 0.87);
font-size: 1.25rem;
font-weight: bold;
text-decoration: none;
}
.link_title:hover,
.link_title:focus {
text-decoration: underline;
}
.link__actions,
.comment__actions {
align-items: center;
color: rgba(0, 0, 0, 0.54);
display: flex;
list-style-type: none;
}
.link__actions li + li,
.comment__actions li + li {
margin-left: 1rem;
}
.link__actions a,
.comment__actions a {
text-decoration: none;
}
.link__actions a:hover,
.link__actions a:focus,
.comment__actions a:hover,
.comment__actions a:focus {
text-decoration: underline;
}
label,
input,
.field-validation-error {
display: block;
}
label {
font-weight: bold;
}
.field-validation-error {
color: orangered;
}
.field {
margin-bottom: 1rem;
}
.message {
background-color: bisque;
padding: 1rem;
margin-bottom: 1rem;
}
.votable {
align-items: center;
display: flex;
}
.no-comment-yet {
color: rgba(0, 0, 0, 0.72);
font-style: italic;
margin: 2rem 0;
}
.add-a-comment {
color: gray;
font-size: 1.25rem;
}
textarea {
color: inherit;
font: inherit;
width: 100%;
min-height: 100px;
}
.comments {
padding-left: 1rem;
}
.comment {
background-color: #fafafa;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.12);
padding: 1rem;
margin-bottom: 1rem;
}

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