aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorivarlovlie <git@ivarlovlie.no>2021-04-25 00:10:17 +0200
committerivarlovlie <git@ivarlovlie.no>2021-04-25 00:10:17 +0200
commit4322330745d18bb28f7deee1a54ae3c748645d92 (patch)
treee533be4f7630fc4eb53457c0566ab93ec41995a2
downloaddotnet-webapi-template-4322330745d18bb28f7deee1a54ae3c748645d92.tar.xz
dotnet-webapi-template-4322330745d18bb28f7deee1a54ae3c748645d92.zip
Initial commit
-rw-r--r--.gitignore448
-rw-r--r--LICENSE24
-rw-r--r--README.md3
-rw-r--r--src/Controllers/AccountController.cs116
-rw-r--r--src/Controllers/AppControllerBase.cs22
-rw-r--r--src/Data/Database/AppDbContext.cs25
-rw-r--r--src/Data/Database/Base.cs10
-rw-r--r--src/Data/Database/User.cs20
-rw-r--r--src/Data/Dtos/LoginRequestDto.cs9
-rw-r--r--src/Data/General/AppPath.cs27
-rw-r--r--src/Data/General/LoggedInUser.cs10
-rw-r--r--src/Data/Result/ErrorResult.cs13
-rw-r--r--src/Data/Static/AppJsonSettings.cs17
-rw-r--r--src/Data/Static/AppPaths.cs16
-rw-r--r--src/IOL.WebApi.Template.csproj18
-rw-r--r--src/Program.cs38
-rw-r--r--src/Properties/launchSettings.json31
-rw-r--r--src/Startup.cs74
18 files changed, 921 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..de03f94
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,448 @@
+## 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/
+
+# Tye
+.tye/
+
+# 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/
+
+# Ionide - VsCode extension for F# Support
+.ionide/
+
+# 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/LICENSE b/LICENSE
new file mode 100644
index 0000000..fdddb29
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,24 @@
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to <https://unlicense.org>
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..4c2d785
--- /dev/null
+++ b/README.md
@@ -0,0 +1,3 @@
+# dotnet webapi template
+
+Base setup for dotnet webapis with efcore (postgresql) and cookie auth.
diff --git a/src/Controllers/AccountController.cs b/src/Controllers/AccountController.cs
new file mode 100644
index 0000000..7f94711
--- /dev/null
+++ b/src/Controllers/AccountController.cs
@@ -0,0 +1,116 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Security.Claims;
+using System.Threading.Tasks;
+using IOL.WebApi.Template.Data.Database;
+using IOL.WebApi.Template.Data.Dtos;
+using IOL.WebApi.Template.Data.Result;
+using IOL.Helpers;
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.Authentication.Cookies;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+
+namespace IOL.WebApi.Template.Controllers
+{
+ public class AccountController : AppControllerBase
+ {
+ private readonly AppDbContext _context;
+ private readonly IAuthenticationService _authentication;
+
+ public AccountController(
+ AppDbContext context,
+ IAuthenticationService authentication
+ ) {
+ _context = context;
+ _authentication = authentication;
+ }
+
+ [AllowAnonymous]
+ [HttpPost("login")]
+ public ActionResult Login(LoginRequestDto payload) {
+ if (!ModelState.IsValid)
+ return BadRequest(ModelState);
+ var user = _context.Users.SingleOrDefault(u => u.Username == payload.Username);
+ if (user == default || !user.VerifyPassword(payload.Password))
+ return BadRequest(new ErrorResult("Invalid username or password"));
+
+ var claims = new List<Claim> {
+ new(ClaimTypes.NameIdentifier, user.Id.ToString()),
+ new(ClaimTypes.Name, user.Username),
+ };
+
+ var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
+ var principal = new ClaimsPrincipal(identity);
+ var authenticationProperties = new AuthenticationProperties {
+ AllowRefresh = true,
+ IssuedUtc = DateTimeOffset.UtcNow,
+ };
+
+ if (payload.Persist) {
+ authenticationProperties.ExpiresUtc = DateTimeOffset.UtcNow.AddMonths(6);
+ authenticationProperties.IsPersistent = true;
+ }
+
+ HttpContext.SignInAsync(principal, authenticationProperties);
+ return Ok();
+ }
+
+ [HttpGet("logout")]
+ [AllowAnonymous]
+ public ActionResult Logout() {
+ HttpContext.SignOutAsync();
+ return Ok();
+ }
+
+ [AllowAnonymous]
+ [HttpGet("create-initial")]
+ public ActionResult CreateInitialUser(string username, string password) {
+ if (_context.Users.Any()) {
+ return NotFound();
+ }
+
+ var user = new User(username);
+ user.HashAndSetPassword(password);
+ _context.Users.Add(user);
+ _context.SaveChanges();
+ return Ok();
+ }
+
+ [AllowAnonymous]
+ [HttpGet("me")]
+ public async Task<ActionResult> GetLoggedInUser() {
+ var authres =
+ await _authentication.AuthenticateAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme);
+ if (authres.Succeeded)
+ return Ok(LoggedInUser);
+
+ await HttpContext.SignOutAsync();
+ return StatusCode(403);
+ }
+
+ [HttpPost("update-password")]
+ public ActionResult UpdatePassword([FromBody] string newPassword) {
+ if (newPassword.IsNullOrWhiteSpace()) {
+ return BadRequest(new ErrorResult("Invalid request",
+ "The new password field is required"));
+ }
+
+ if (newPassword.Length < 6) {
+ return BadRequest(new ErrorResult("Invalid request",
+ "The new password must contain atleast 6 characters"));
+ }
+
+ var user = _context.Users.SingleOrDefault(c => c.Id == LoggedInUser.Id);
+ if (user == default) {
+ HttpContext.SignOutAsync();
+ return StatusCode(403);
+ }
+
+ user.HashAndSetPassword(newPassword);
+ _context.SaveChanges();
+ return Ok();
+ }
+ }
+}
diff --git a/src/Controllers/AppControllerBase.cs b/src/Controllers/AppControllerBase.cs
new file mode 100644
index 0000000..36b52d7
--- /dev/null
+++ b/src/Controllers/AppControllerBase.cs
@@ -0,0 +1,22 @@
+using System.Linq;
+using System.Security.Claims;
+using IOL.WebApi.Template.Data.General;
+using IOL.Helpers;
+using Microsoft.AspNetCore.Mvc;
+
+namespace IOL.WebApi.Template.Controllers
+{
+ [ApiController]
+ [Route("api/[controller]")]
+ public class AppControllerBase : ControllerBase
+ {
+ public string CurrentHost => Request.GetRequestHost();
+
+ public AppControllerBase() { }
+
+ public LoggedInUser LoggedInUser => new() {
+ Username = User.Identity?.Name,
+ Id = User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value.ToGuid() ?? default
+ };
+ }
+}
diff --git a/src/Data/Database/AppDbContext.cs b/src/Data/Database/AppDbContext.cs
new file mode 100644
index 0000000..9bfabc4
--- /dev/null
+++ b/src/Data/Database/AppDbContext.cs
@@ -0,0 +1,25 @@
+using Microsoft.EntityFrameworkCore;
+
+namespace IOL.WebApi.Template.Data.Database
+{
+ public class AppDbContext : DbContext
+ {
+ public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
+ public DbSet<User> Users { get; set; }
+
+ protected override void OnModelCreating(ModelBuilder modelBuilder) {
+#if false
+ var seedUser = new User("admin@example.org");
+ seedUser.Id = Guid.NewGuid();
+ seedUser.HashAndSetPassword("asdf1234");
+ modelBuilder.Entity<User>().HasData(seedUser);
+#endif
+
+ modelBuilder.Entity<User>(e => {
+ e.ToTable("users");
+ });
+
+ base.OnModelCreating(modelBuilder);
+ }
+ }
+}
diff --git a/src/Data/Database/Base.cs b/src/Data/Database/Base.cs
new file mode 100644
index 0000000..4b1ea55
--- /dev/null
+++ b/src/Data/Database/Base.cs
@@ -0,0 +1,10 @@
+using System;
+
+namespace IOL.WebApi.Template.Data.Database
+{
+ public class Base
+ {
+ public Guid Id { get; set; }
+ public DateTime Created { get; set; }
+ }
+}
diff --git a/src/Data/Database/User.cs b/src/Data/Database/User.cs
new file mode 100644
index 0000000..31513a3
--- /dev/null
+++ b/src/Data/Database/User.cs
@@ -0,0 +1,20 @@
+using IOL.Helpers;
+
+namespace IOL.WebApi.Template.Data.Database
+{
+ public class User : Base
+ {
+ public User(string username) => Username = username;
+
+ public string Username { get; set; }
+ public string Password { get; set; }
+
+ public void HashAndSetPassword(string password) {
+ Password = PasswordHelper.HashPassword(password);
+ }
+
+ public bool VerifyPassword(string password) {
+ return PasswordHelper.Verify(password, Password);
+ }
+ }
+}
diff --git a/src/Data/Dtos/LoginRequestDto.cs b/src/Data/Dtos/LoginRequestDto.cs
new file mode 100644
index 0000000..bed49c4
--- /dev/null
+++ b/src/Data/Dtos/LoginRequestDto.cs
@@ -0,0 +1,9 @@
+namespace IOL.WebApi.Template.Data.Dtos
+{
+ public class LoginRequestDto
+ {
+ public string Username { get; set; }
+ public string Password { get; set; }
+ public bool Persist { get; set; }
+ }
+}
diff --git a/src/Data/General/AppPath.cs b/src/Data/General/AppPath.cs
new file mode 100644
index 0000000..241cf65
--- /dev/null
+++ b/src/Data/General/AppPath.cs
@@ -0,0 +1,27 @@
+using System.IO;
+using IOL.Helpers;
+
+namespace IOL.WebApi.Template.Data.General
+{
+ public sealed record AppPath
+ {
+ public string HostPath { get; init; }
+ public string WebPath { get; init; }
+
+ public string GetHostPathForFilename(string filename, string fallback = "") {
+ if (filename.IsNullOrWhiteSpace()) {
+ return fallback;
+ }
+
+ return Path.Combine(HostPath, filename);
+ }
+
+ public string GetWebPathForFilename(string filename, string fallback = "") {
+ if (filename.IsNullOrWhiteSpace()) {
+ return fallback;
+ }
+
+ return Path.Combine(WebPath, filename);
+ }
+ }
+}
diff --git a/src/Data/General/LoggedInUser.cs b/src/Data/General/LoggedInUser.cs
new file mode 100644
index 0000000..d278d3f
--- /dev/null
+++ b/src/Data/General/LoggedInUser.cs
@@ -0,0 +1,10 @@
+using System;
+
+namespace IOL.WebApi.Template.Data.General
+{
+ public class LoggedInUser
+ {
+ public Guid Id { get; set; }
+ public string Username { get; set; }
+ }
+}
diff --git a/src/Data/Result/ErrorResult.cs b/src/Data/Result/ErrorResult.cs
new file mode 100644
index 0000000..3e585b3
--- /dev/null
+++ b/src/Data/Result/ErrorResult.cs
@@ -0,0 +1,13 @@
+namespace IOL.WebApi.Template.Data.Result
+{
+ public class ErrorResult
+ {
+ public ErrorResult(string title = default, string text = default) {
+ Title = title;
+ Text = text;
+ }
+
+ public string Title { get; set; }
+ public string Text { get; set; }
+ }
+}
diff --git a/src/Data/Static/AppJsonSettings.cs b/src/Data/Static/AppJsonSettings.cs
new file mode 100644
index 0000000..8aad1ba
--- /dev/null
+++ b/src/Data/Static/AppJsonSettings.cs
@@ -0,0 +1,17 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Microsoft.AspNetCore.Mvc;
+
+namespace IOL.WebApi.Template.Data.Static
+{
+ public static class AppJsonSettings
+ {
+ public static Action<JsonOptions> Value { get; } = options => {
+ options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
+ options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
+ options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString;
+ options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
+ };
+ }
+}
diff --git a/src/Data/Static/AppPaths.cs b/src/Data/Static/AppPaths.cs
new file mode 100644
index 0000000..64a249a
--- /dev/null
+++ b/src/Data/Static/AppPaths.cs
@@ -0,0 +1,16 @@
+using System.IO;
+using IOL.WebApi.Template.Data.General;
+
+namespace IOL.WebApi.Template.Data.Static
+{
+ public static class AppPaths
+ {
+ public static AppPath AppData => new() {
+ HostPath = Path.Combine(Directory.GetCurrentDirectory(), "AppData")
+ };
+
+ public static AppPath DataProtectionKeys => new() {
+ HostPath = Path.Combine(Directory.GetCurrentDirectory(), "AppData", "data-protection-keys")
+ };
+ }
+}
diff --git a/src/IOL.WebApi.Template.csproj b/src/IOL.WebApi.Template.csproj
new file mode 100644
index 0000000..5fc7513
--- /dev/null
+++ b/src/IOL.WebApi.Template.csproj
@@ -0,0 +1,18 @@
+<Project Sdk="Microsoft.NET.Sdk.Web">
+
+ <PropertyGroup>
+ <TargetFramework>net5.0</TargetFramework>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="EFCore.NamingConventions" Version="5.0.2" />
+ <PackageReference Include="IOL.Helpers" Version="1.0.4" />
+ <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.5">
+ <PrivateAssets>all</PrivateAssets>
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ </PackageReference>
+ <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.5.1" />
+ <PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
+ </ItemGroup>
+
+</Project>
diff --git a/src/Program.cs b/src/Program.cs
new file mode 100644
index 0000000..113b013
--- /dev/null
+++ b/src/Program.cs
@@ -0,0 +1,38 @@
+using System;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Hosting;
+using Serilog;
+
+namespace IOL.WebApi.Template
+{
+ public class Program
+ {
+ public static int Main(string[] args) {
+ Log.Logger = new LoggerConfiguration()
+ .Enrich.FromLogContext()
+ .WriteTo.Console()
+ .CreateLogger();
+
+ try {
+ Log.Information("Starting web host");
+ CreateHostBuilder(args).Build().Run();
+ return 0;
+ } catch (Exception ex) {
+ Log.Fatal(ex, "Host terminated unexpectedly");
+ return 1;
+ } finally {
+ Log.CloseAndFlush();
+ }
+ }
+
+ private static IHostBuilder CreateHostBuilder(string[] args) {
+ return Host.CreateDefaultBuilder(args)
+ .UseSerilog()
+ .ConfigureWebHostDefaults(webBuilder => {
+ webBuilder.UseKestrel(o =>
+ o.AddServerHeader = false);
+ webBuilder.UseStartup<Startup>();
+ });
+ }
+ }
+}
diff --git a/src/Properties/launchSettings.json b/src/Properties/launchSettings.json
new file mode 100644
index 0000000..bb0b5fa
--- /dev/null
+++ b/src/Properties/launchSettings.json
@@ -0,0 +1,31 @@
+{
+ "$schema": "http://json.schemastore.org/launchsettings.json",
+ "iisSettings": {
+ "windowsAuthentication": false,
+ "anonymousAuthentication": true,
+ "iisExpress": {
+ "applicationUrl": "http://localhost:4608",
+ "sslPort": 44370
+ }
+ },
+ "profiles": {
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "IOL.WebApi.Template": {
+ "commandName": "Project",
+ "dotnetRunMessages": "true",
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "applicationUrl": "https://localhost:5001;http://localhost:5000",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/src/Startup.cs b/src/Startup.cs
new file mode 100644
index 0000000..a3a7009
--- /dev/null
+++ b/src/Startup.cs
@@ -0,0 +1,74 @@
+using System;
+using System.IO;
+using IOL.WebApi.Template.Data.Database;
+using IOL.WebApi.Template.Data.Static;
+using IOL.Helpers;
+using Microsoft.AspNetCore.Authentication.Cookies;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.DataProtection;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Http;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+
+namespace IOL.WebApi.Template
+{
+ public class Startup
+ {
+ public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment) {
+ Configuration = configuration;
+ WebHostEnvironment = webHostEnvironment;
+ }
+
+ private IWebHostEnvironment WebHostEnvironment { get; }
+ private IConfiguration Configuration { get; }
+
+ // This method gets called by the runtime. Use this method to add services to the container.
+ public void ConfigureServices(IServiceCollection services) {
+ services.AddDataProtection()
+ .PersistKeysToFileSystem(new DirectoryInfo(AppPaths.DataProtectionKeys.HostPath));
+
+ services.Configure(AppJsonSettings.Value);
+
+ services.AddDbContext<AppDbContext>(options => {
+ options.UseNpgsql("Server={DB_HOST};Port={DB_PORT};Database={DB_NAME};User Id={DB_USER};Password={DB_PASSWORD}".UnicornFormatWithEnvironment(Configuration),
+ builder => {
+ builder.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
+ builder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), default);
+ })
+ .UseSnakeCaseNamingConvention();
+ if (WebHostEnvironment.IsDevelopment())
+ options.EnableSensitiveDataLogging();
+ });
+
+ services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
+ .AddCookie(options => {
+ options.Cookie.Name = "";
+ options.Cookie.SameSite = SameSiteMode.Strict;
+ options.Cookie.HttpOnly = true;
+ options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
+ });
+
+ services.AddControllers()
+ .AddJsonOptions(AppJsonSettings.Value);
+ }
+
+ // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
+ public void Configure(IApplicationBuilder app) {
+ if (WebHostEnvironment.IsDevelopment()) {
+ app.UseDeveloperExceptionPage();
+ }
+
+ app.UseStaticFiles();
+ app.UseRouting();
+ app.UseAuthentication();
+ app.UseAuthorization();
+ app.UseStatusCodePages();
+ app.UseEndpoints(endpoints => {
+ endpoints.MapControllers();
+ });
+ }
+ }
+}