Separated app into three layers, cleaned up leftovers
This commit is contained in:
parent
96003c21dd
commit
52667d913d
11
Birdmap.BLL/Birdmap.BLL.csproj
Normal file
11
Birdmap.BLL/Birdmap.BLL.csproj
Normal file
@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Birdmap.DAL\Birdmap.DAL.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -1,9 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Birdmap.Exceptions
|
||||
namespace Birdmap.BLL.Exceptions
|
||||
{
|
||||
public class AuthenticationException : Exception
|
||||
{
|
@ -1,7 +1,7 @@
|
||||
using Birdmap.Models;
|
||||
using Birdmap.DAL.Entities;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Birdmap.Services.Interfaces
|
||||
namespace Birdmap.BLL.Interfaces
|
||||
{
|
||||
public interface IAuthService
|
||||
{
|
@ -1,5 +1,5 @@
|
||||
using Birdmap.Models;
|
||||
using Birdmap.Services.Interfaces;
|
||||
using Birdmap.DAL.Entities;
|
||||
using Birdmap.BLL.Interfaces;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@ -7,25 +7,31 @@ using System.Linq;
|
||||
using System.Security.Authentication;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Birdmap.DAL;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Birdmap.Services
|
||||
namespace Birdmap.BLL.Services
|
||||
{
|
||||
public class AuthService : IAuthService
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly BirdmapContext _context;
|
||||
|
||||
public AuthService(IConfiguration configuration)
|
||||
public AuthService(BirdmapContext context)
|
||||
{
|
||||
_configuration = configuration;
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<User> AuthenticateUserAsync(string username, string password)
|
||||
public Task<User> AuthenticateUserAsync(string username, string password)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrEmpty(password))
|
||||
throw new ArgumentException("Username or password cannot be null or empty.");
|
||||
|
||||
//var user = await _context.Users.SingleOrDefaultAsync(u => u.Name == username)
|
||||
var user = await Temp_GetUserAsync(_configuration)
|
||||
return AuthenticateUserInternalAsync(username, password);
|
||||
}
|
||||
|
||||
private async Task<User> AuthenticateUserInternalAsync(string username, string password)
|
||||
{
|
||||
var user = await _context.Users.SingleOrDefaultAsync(u => u.Name == username)
|
||||
?? throw new AuthenticationException();
|
||||
|
||||
if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
|
||||
@ -60,9 +66,9 @@ namespace Birdmap.Services
|
||||
|
||||
private static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
|
||||
if (storedHash.Length != 64) throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
|
||||
if (storedSalt.Length != 128) throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");
|
||||
if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be null or empty.", nameof(password));
|
||||
if (storedHash.Length != 64) throw new ArgumentException("Invalid length of password hash (64 bytes expected).", nameof(storedHash));
|
||||
if (storedSalt.Length != 128) throw new ArgumentException("Invalid length of password salt (128 bytes expected).", nameof(storedSalt));
|
||||
|
||||
using var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt);
|
||||
|
17
Birdmap.BLL/Startup.cs
Normal file
17
Birdmap.BLL/Startup.cs
Normal file
@ -0,0 +1,17 @@
|
||||
using Birdmap.BLL.Interfaces;
|
||||
using Birdmap.BLL.Services;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Birdmap.BLL
|
||||
{
|
||||
public static class Startup
|
||||
{
|
||||
public static IServiceCollection ConfigureBLL(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddTransient<IAuthService, AuthService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
13
Birdmap.DAL/Birdmap.DAL.csproj
Normal file
13
Birdmap.DAL/Birdmap.DAL.csproj
Normal file
@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.9" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.9" />
|
||||
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="3.1.9" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
27
Birdmap.DAL/BirdmapContext.cs
Normal file
27
Birdmap.DAL/BirdmapContext.cs
Normal file
@ -0,0 +1,27 @@
|
||||
using Birdmap.DAL.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace Birdmap.DAL
|
||||
{
|
||||
public class BirdmapContext : DbContext
|
||||
{
|
||||
public DbSet<User> Users { get; set; }
|
||||
|
||||
public BirdmapContext([NotNull] DbContextOptions options) : base(options)
|
||||
{
|
||||
}
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.ApplyConfigurationsFromAssembly(typeof(BirdmapContext).Assembly);
|
||||
|
||||
SeedDatabase(modelBuilder);
|
||||
}
|
||||
|
||||
private void SeedDatabase(ModelBuilder modelBuilder)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
23
Birdmap.DAL/Entities/Configurations/UserConfiguration.cs
Normal file
23
Birdmap.DAL/Entities/Configurations/UserConfiguration.cs
Normal file
@ -0,0 +1,23 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace Birdmap.DAL.Entities.Configurations
|
||||
{
|
||||
public class UserConfiguration : IEntityTypeConfiguration<User>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<User> builder)
|
||||
{
|
||||
builder.Property(u => u.Name)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(u => u.PasswordHash)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(u => u.PasswordSalt)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(u => u.Role)
|
||||
.IsRequired();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,14 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Birdmap.Models
|
||||
namespace Birdmap.DAL.Entities
|
||||
{
|
||||
public enum Roles
|
||||
{
|
||||
User,
|
||||
Admin,
|
||||
}
|
||||
|
||||
public class User
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
public byte[] PasswordHash { get; set; }
|
||||
public byte[] PasswordSalt { get; set; }
|
||||
|
||||
public Roles Role { get; set; }
|
||||
}
|
||||
}
|
23
Birdmap.DAL/Startup.cs
Normal file
23
Birdmap.DAL/Startup.cs
Normal file
@ -0,0 +1,23 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Birdmap.DAL
|
||||
{
|
||||
public static class Startup
|
||||
{
|
||||
public static IServiceCollection ConfigureDAL(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddDbContext<BirdmapContext>(o =>
|
||||
o.UseSqlServer(configuration["LocalDbConnectionString"]));
|
||||
|
||||
services.AddHealthChecks()
|
||||
.AddDbContextCheck<BirdmapContext>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
14
Birdmap.sln
14
Birdmap.sln
@ -3,7 +3,11 @@ Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.30611.23
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Birdmap", "Birdmap\Birdmap.csproj", "{88855E5F-9555-49E5-92F2-4E8C1194F60B}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Birdmap.API", "Birdmap\Birdmap.API.csproj", "{88855E5F-9555-49E5-92F2-4E8C1194F60B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Birdmap.BLL", "Birdmap.BLL\Birdmap.BLL.csproj", "{879D7B8D-6865-4EBE-B346-E0CA37D3C06A}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Birdmap.DAL", "Birdmap.DAL\Birdmap.DAL.csproj", "{543FAB06-B960-41A9-8865-1624A2ED2170}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@ -15,6 +19,14 @@ Global
|
||||
{88855E5F-9555-49E5-92F2-4E8C1194F60B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{88855E5F-9555-49E5-92F2-4E8C1194F60B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{88855E5F-9555-49E5-92F2-4E8C1194F60B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{879D7B8D-6865-4EBE-B346-E0CA37D3C06A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{879D7B8D-6865-4EBE-B346-E0CA37D3C06A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{879D7B8D-6865-4EBE-B346-E0CA37D3C06A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{879D7B8D-6865-4EBE-B346-E0CA37D3C06A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{543FAB06-B960-41A9-8865-1624A2ED2170}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{543FAB06-B960-41A9-8865-1624A2ED2170}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{543FAB06-B960-41A9-8865-1624A2ED2170}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{543FAB06-B960-41A9-8865-1624A2ED2170}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
@ -10,6 +10,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="10.1.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="3.1.9" />
|
||||
<PackageReference Include="Microsoft.TypeScript.MSBuild" Version="4.0.3">
|
||||
@ -44,6 +45,10 @@
|
||||
<Folder Include="ClientApp\src\components\heatmap\" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Birdmap.BLL\Birdmap.BLL.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
|
||||
<!-- Ensure Node.js is installed -->
|
||||
<Exec Command="node --version" ContinueOnError="true">
|
@ -1,5 +1,7 @@
|
||||
using Birdmap.Models;
|
||||
using Birdmap.Services.Interfaces;
|
||||
using AutoMapper;
|
||||
using Birdmap.API.DTOs;
|
||||
using Birdmap.BLL.Interfaces;
|
||||
using Birdmap.Models;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
@ -20,11 +22,13 @@ namespace Birdmap.Controllers
|
||||
{
|
||||
private readonly IAuthService _service;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public AuthController(IAuthService service, IConfiguration configuration)
|
||||
public AuthController(IAuthService service, IConfiguration configuration, IMapper mapper)
|
||||
{
|
||||
_service = service;
|
||||
_configuration = configuration;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
@ -35,12 +39,13 @@ namespace Birdmap.Controllers
|
||||
var user = await _service.AuthenticateUserAsync(model.Username, model.Password);
|
||||
var expiresInSeconds = TimeSpan.FromHours(2).TotalSeconds;
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var key = Encoding.ASCII.GetBytes(_configuration["BasicAuth:Secret"]);
|
||||
var key = Encoding.ASCII.GetBytes(_configuration["Secret"]);
|
||||
var tokenDescriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity(new Claim[]
|
||||
{
|
||||
new Claim(ClaimTypes.Name, user.Name)
|
||||
new Claim(ClaimTypes.Name, user.Name),
|
||||
new Claim(ClaimTypes.Role, user.Role.ToString()),
|
||||
}),
|
||||
Expires = DateTime.UtcNow.AddHours(expiresInSeconds),
|
||||
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
|
||||
@ -48,14 +53,12 @@ namespace Birdmap.Controllers
|
||||
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||
var tokenString = tokenHandler.WriteToken(token);
|
||||
|
||||
return Ok(
|
||||
new
|
||||
{
|
||||
user_name = user.Name,
|
||||
access_token = tokenString,
|
||||
token_type = "Bearer",
|
||||
expires_in = expiresInSeconds,
|
||||
});
|
||||
var response = _mapper.Map<AuthenticateResponse>(user);
|
||||
response.AccessToken = tokenString;
|
||||
response.TokenType = "Bearer";
|
||||
response.ExpiresIn = expiresInSeconds;
|
||||
|
||||
return Ok(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,41 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Birdmap.Controllers
|
||||
{
|
||||
[Authorize]
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class WeatherForecastController : ControllerBase
|
||||
{
|
||||
private static readonly string[] Summaries = new[]
|
||||
{
|
||||
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
||||
};
|
||||
|
||||
private readonly ILogger<WeatherForecastController> _logger;
|
||||
|
||||
public WeatherForecastController(ILogger<WeatherForecastController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IEnumerable<WeatherForecast> Get()
|
||||
{
|
||||
var rng = new Random();
|
||||
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
|
||||
{
|
||||
Date = DateTime.Now.AddDays(index),
|
||||
TemperatureC = rng.Next(-20, 55),
|
||||
Summary = Summaries[rng.Next(Summaries.Length)]
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
19
Birdmap/DTOs/AuthenticateResponse.cs
Normal file
19
Birdmap/DTOs/AuthenticateResponse.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using Birdmap.DAL.Entities;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Birdmap.API.DTOs
|
||||
{
|
||||
public class AuthenticateResponse
|
||||
{
|
||||
[JsonProperty("user_name")]
|
||||
public string Username { get; set; }
|
||||
[JsonProperty("user_role")]
|
||||
public Roles UserRole { get; set; }
|
||||
[JsonProperty("access_token")]
|
||||
public string AccessToken { get; set; }
|
||||
[JsonProperty("token_type")]
|
||||
public string TokenType { get; set; }
|
||||
[JsonProperty("expires_in")]
|
||||
public double ExpiresIn { get; set; }
|
||||
}
|
||||
}
|
13
Birdmap/MapperProfiles/BirdmapProfile.cs
Normal file
13
Birdmap/MapperProfiles/BirdmapProfile.cs
Normal file
@ -0,0 +1,13 @@
|
||||
using AutoMapper;
|
||||
using Birdmap.DAL.Entities;
|
||||
|
||||
namespace Birdmap.API.MapperProfiles
|
||||
{
|
||||
public class BirdmapProfile : Profile
|
||||
{
|
||||
public BirdmapProfile()
|
||||
{
|
||||
CreateMap<User, DTOs.AuthenticateResponse>().ReverseMap();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,18 +1,15 @@
|
||||
using Birdmap.Services;
|
||||
using Birdmap.Services.Interfaces;
|
||||
using Birdmap.BLL;
|
||||
using Birdmap.BLL.Interfaces;
|
||||
using Birdmap.DAL;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.HttpsPolicy;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Birdmap
|
||||
{
|
||||
@ -34,9 +31,10 @@ namespace Birdmap
|
||||
//opt.JsonSerializerOptions.PropertyNamingPolicy = new JsonNamingPolicy()
|
||||
});
|
||||
|
||||
services.AddTransient<IAuthService, AuthService>();
|
||||
services.ConfigureBLL(Configuration);
|
||||
services.ConfigureDAL(Configuration);
|
||||
|
||||
var key = Encoding.ASCII.GetBytes(Configuration["BasicAuth:Secret"]);
|
||||
var key = Encoding.ASCII.GetBytes(Configuration["Secret"]);
|
||||
services.AddAuthentication(opt =>
|
||||
{
|
||||
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
|
@ -1,15 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace Birdmap
|
||||
{
|
||||
public class WeatherForecast
|
||||
{
|
||||
public DateTime Date { get; set; }
|
||||
|
||||
public int TemperatureC { get; set; }
|
||||
|
||||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
||||
|
||||
public string Summary { get; set; }
|
||||
}
|
||||
}
|
@ -7,9 +7,25 @@
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"BasicAuth": {
|
||||
"Username": "user",
|
||||
"Password": "pass",
|
||||
"Secret": "7vj.3KW.hYE!}4u6"
|
||||
"Secret": "7vj.3KW.hYE!}4u6",
|
||||
"LocalDbConnectionString": null,
|
||||
"Default": {
|
||||
"Users": [
|
||||
{
|
||||
"Username": "user",
|
||||
"Password": "pass",
|
||||
"Role": "User"
|
||||
},
|
||||
{
|
||||
"Username": "admin",
|
||||
"Password": "pass",
|
||||
"Role": "Admin"
|
||||
}
|
||||
],
|
||||
"Endpoints": [
|
||||
"",
|
||||
"",
|
||||
""
|
||||
]
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user