Refactor and remove redundant user db context

This commit is contained in:
code liturgy 2022-11-16 22:17:37 +00:00
parent 082d65a86c
commit 61f4a0abac
31 changed files with 127 additions and 201 deletions

View File

@ -5,7 +5,7 @@ VisualStudioVersion = 17.3.32819.101
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeLiturgy", "CodeLiturgy\CodeLiturgy.csproj", "{293E7852-8AFD-4EFB-8C2D-F1BBE68AEE78}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeLiturgy", "CodeLiturgy\CodeLiturgy.csproj", "{293E7852-8AFD-4EFB-8C2D-F1BBE68AEE78}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeLiturgy.Data.Capital", "CodeLiturgy.Data.Capital\CodeLiturgy.Data.Capital.csproj", "{E518C62D-768C-4885-9C9D-FD5761605B54}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeLiturgy.Data.Sites", "CodeLiturgy.Data.Sites\CodeLiturgy.Data.Sites.csproj", "{E518C62D-768C-4885-9C9D-FD5761605B54}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlueWest.MapTo", "include\BlueWest.MapTo\src\BlueWest.MapTo\BlueWest.MapTo.csproj", "{72B37540-A12F-466E-A58F-7BA2B247CB74}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlueWest.MapTo", "include\BlueWest.MapTo\src\BlueWest.MapTo\BlueWest.MapTo.csproj", "{72B37540-A12F-466E-A58F-7BA2B247CB74}"
EndProject EndProject
@ -41,8 +41,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeLiturgy.Data.Auth", "Co
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sharp.Augeas", "include\Sharp.Augeas\Sharp.Augeas\Sharp.Augeas.csproj", "{F12DB2F1-2F2C-4A4C-BBAA-944AF5FB0E59}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sharp.Augeas", "include\Sharp.Augeas\Sharp.Augeas\Sharp.Augeas.csproj", "{F12DB2F1-2F2C-4A4C-BBAA-944AF5FB0E59}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeLiturgy.SiteManager", "CodeLiturgy.SiteManager\CodeLiturgy.SiteManager.csproj", "{CE32D9DC-DDC8-47FE-AFCA-71DF894D06DE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sharp.Augeas.Test", "include\Sharp.Augeas\Sharp.Augeas.Test\Sharp.Augeas.Test.csproj", "{03308684-19AC-454B-8CD3-AB1C26B8BBBF}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sharp.Augeas.Test", "include\Sharp.Augeas\Sharp.Augeas.Test\Sharp.Augeas.Test.csproj", "{03308684-19AC-454B-8CD3-AB1C26B8BBBF}"
EndProject EndProject
Global Global
@ -99,10 +97,6 @@ Global
{F12DB2F1-2F2C-4A4C-BBAA-944AF5FB0E59}.Debug|Any CPU.Build.0 = Debug|Any CPU {F12DB2F1-2F2C-4A4C-BBAA-944AF5FB0E59}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F12DB2F1-2F2C-4A4C-BBAA-944AF5FB0E59}.Release|Any CPU.ActiveCfg = Release|Any CPU {F12DB2F1-2F2C-4A4C-BBAA-944AF5FB0E59}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F12DB2F1-2F2C-4A4C-BBAA-944AF5FB0E59}.Release|Any CPU.Build.0 = Release|Any CPU {F12DB2F1-2F2C-4A4C-BBAA-944AF5FB0E59}.Release|Any CPU.Build.0 = Release|Any CPU
{CE32D9DC-DDC8-47FE-AFCA-71DF894D06DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CE32D9DC-DDC8-47FE-AFCA-71DF894D06DE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CE32D9DC-DDC8-47FE-AFCA-71DF894D06DE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CE32D9DC-DDC8-47FE-AFCA-71DF894D06DE}.Release|Any CPU.Build.0 = Release|Any CPU
{03308684-19AC-454B-8CD3-AB1C26B8BBBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03308684-19AC-454B-8CD3-AB1C26B8BBBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03308684-19AC-454B-8CD3-AB1C26B8BBBF}.Debug|Any CPU.Build.0 = Debug|Any CPU {03308684-19AC-454B-8CD3-AB1C26B8BBBF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03308684-19AC-454B-8CD3-AB1C26B8BBBF}.Release|Any CPU.ActiveCfg = Release|Any CPU {03308684-19AC-454B-8CD3-AB1C26B8BBBF}.Release|Any CPU.ActiveCfg = Release|Any CPU

View File

@ -1,25 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using MapTo;
namespace BlueWest.Data
{
[MapFrom( typeof(UserCreate))]
[UseUpdate]
public partial class User
{
public string ApplicationUserId { get; set; }
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("CountryId")] public Country Country { get; set; }
public User(int id, string name)
{
Id = id;
Name = name;
}
}
}

View File

@ -1,12 +0,0 @@
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(User))]
public partial class UserCreate
{
public string Name { get; set; }
}
}

View File

@ -1,6 +0,0 @@
namespace BlueWest.Data;
public class UserUnique
{
}

View File

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using BlueWest.Data.Application.Users;
using MapTo; using MapTo;
namespace BlueWest.Data namespace BlueWest.Data
@ -31,7 +32,7 @@ namespace BlueWest.Data
[MaxLength(2)] public string Alpha2Code { get; set; } [MaxLength(2)] public string Alpha2Code { get; set; }
public string TLD { get; set; } public string TLD { get; set; }
public List<User> Users { get; set; } public List<ApplicationUser> Users { get; set; }
public DateTime CreationDate { get; set; } public DateTime CreationDate { get; set; }

View File

@ -8,6 +8,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\CodeLiturgy.Data.Application\CodeLiturgy.Data.Application.csproj" />
<ProjectReference Include="..\include\BlueWest.MapTo\src\BlueWest.MapTo\BlueWest.MapTo.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" /> <ProjectReference Include="..\include\BlueWest.MapTo\src\BlueWest.MapTo\BlueWest.MapTo.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\include\Math-Expression-Evaluator\SimpleExpressionEvaluator\SimpleExpressionEvaluator.csproj" /> <ProjectReference Include="..\include\Math-Expression-Evaluator\SimpleExpressionEvaluator\SimpleExpressionEvaluator.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -21,6 +21,8 @@ namespace CodeLiturgy.Data.Capital
public string Ip { get; set; } public string Ip { get; set; }
public EnvironmentType EnvironmentType { get; set; }
public DateTime CreatedDate { get; set; } public DateTime CreatedDate { get; set; }
public DateTime LastChanged { get; set; } public DateTime LastChanged { get; set; }

View File

@ -12,5 +12,8 @@ namespace CodeLiturgy.Data.Capital
public string Domain { get; set; } public string Domain { get; set; }
public string Ip { get; set; } public string Ip { get; set; }
public EnvironmentType EnvironmentType { get; set; }
} }
} }

View File

@ -14,6 +14,9 @@ namespace CodeLiturgy.Data.Capital
public string Domain { get; set; } public string Domain { get; set; }
public string Ip { get; set; } public string Ip { get; set; }
public EnvironmentType EnvironmentType { get; set; }
} }
} }

View File

@ -33,7 +33,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\CodeLiturgy.Data.Application\CodeLiturgy.Data.Application.csproj" /> <ProjectReference Include="..\CodeLiturgy.Data.Application\CodeLiturgy.Data.Application.csproj" />
<ProjectReference Include="..\CodeLiturgy.Data.Capital\CodeLiturgy.Data.Capital.csproj" /> <ProjectReference Include="..\CodeLiturgy.Data.Sites\CodeLiturgy.Data.Sites.csproj" />
<ProjectReference Include="..\include\BlueWest.EfMethods\src\BlueWest.EfMethods\BlueWest.EfMethods.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" /> <ProjectReference Include="..\include\BlueWest.EfMethods\src\BlueWest.EfMethods\BlueWest.EfMethods.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup> </ItemGroup>

View File

@ -0,0 +1,27 @@
using CodeLiturgy.Data.Capital;
using Microsoft.EntityFrameworkCore;
using BlueWest.EfMethods;
namespace CodeLiturgy.Domain
{
[EfGenerator]
public class SiteDbContext: DbContext
{
[EfGetOneBy(nameof(Site.Id), typeof(SiteUnique))]
[EfGetOne(typeof(SiteUnique))]
[EfAddMethods(createType: typeof(SiteCreate), returnType: typeof(SiteUnique))]
[EfGetMany(typeof(SiteUnique))]
public DbSet<Site> Sites { get; set; }
/// <summary>
/// SiteDbContext Constructor.
/// </summary>
/// <param name="options"></param>
public SiteDbContext(DbContextOptions<SiteDbContext> options) : base(options)
{
Database.EnsureCreated();
}
}
}

View File

@ -98,13 +98,6 @@ namespace CodeLiturgy.Domain.Model
private static ModelBuilder ConfigureDatabaseKeys(this ModelBuilder modelBuilder) private static ModelBuilder ConfigureDatabaseKeys(this ModelBuilder modelBuilder)
{ {
// User
modelBuilder
.Entity<User>(builder => builder
.HasKey(user => user.Id))
.Entity<User>().Property(user => user.Id)
.ValueGeneratedOnAdd();
// Country // Country
modelBuilder modelBuilder
.Entity<Country>(builder => builder .Entity<Country>(builder => builder
@ -112,7 +105,6 @@ namespace CodeLiturgy.Domain.Model
.Entity<Country>().Property(country => country.Id) .Entity<Country>().Property(country => country.Id)
.ValueGeneratedOnAdd(); .ValueGeneratedOnAdd();
// FinanceOp // FinanceOp
return return
modelBuilder; modelBuilder;

View File

@ -1,26 +0,0 @@
using CodeLiturgy.Data.Capital;
using Microsoft.EntityFrameworkCore;
using BlueWest.EfMethods;
namespace CodeLiturgy.Domain;
public class SiteDbContext: DbContext
{
[EfGetOneBy(nameof(Site.Id), typeof(SiteUnique))]
[EfGetOne(typeof(SiteUnique))]
[EfAddMethods(createType: typeof(SiteCreate), returnType: typeof(SiteUnique))]
[EfGetMany(typeof(SiteUnique))]
public DbSet<Site> Sites { get; set; }
/// <summary>
/// SiteDbContext Constructor.
/// </summary>
/// <param name="options"></param>
public SiteDbContext(DbContextOptions<SiteDbContext> options) : base(options)
{
Database.EnsureCreated();
}
}

View File

@ -1,44 +0,0 @@
using BlueWest.Data;
using CodeLiturgy.Domain.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace CodeLiturgy.Domain
{
/// <summary>
/// Database context for app users
/// </summary>
public sealed class UserDbContext : DbContext
{
/// <summary>
/// Users entity.
/// </summary>
public DbSet<User> Users { get; set; }
/// <summary>
/// App configuration.
/// </summary>
public IConfiguration Configuration;
/// <summary>
/// Database for the context of database users
/// </summary>
/// <param name="options"></param>
public UserDbContext(DbContextOptions<UserDbContext> options) : base(options)
{
Database.EnsureCreated();
}
/// <summary>
/// On model creating.
/// </summary>
/// <param name="modelBuilder">Builder model of the database</param>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ConfigureCurrentDbModel();
}
}
}

View File

@ -1,13 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\include\Sharp.Augeas\Sharp.Augeas\Sharp.Augeas.csproj" />
</ItemGroup>
</Project>

View File

@ -1,6 +0,0 @@
namespace CodeLiturgy.SiteManager;
public class SiteManager
{
}

View File

@ -4,14 +4,11 @@ using BlueWest.Data.Auth.Context.Users;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using CodeLiturgy.Views.Models; using CodeLiturgy.Views.Models;
using CodeLiturgy.Views.Utils; using CodeLiturgy.Views.Utils;
using Controller = Microsoft.AspNetCore.Mvc.Controller;
namespace CodeLiturgy.Views.Controllers; namespace CodeLiturgy.Views.Controllers;
public class AccountController : UserController public class AccountController : UserController
{ {
private readonly ILogger<AccountController> _logger;
public AccountController(ApplicationUserManager userManager, ILogger<AccountController> logger) : base(userManager, logger) public AccountController(ApplicationUserManager userManager, ILogger<AccountController> logger) : base(userManager, logger)
{ {
_userManager = userManager; _userManager = userManager;
@ -37,7 +34,7 @@ public class AccountController : UserController
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public async Task<IActionResult> Error() public IActionResult Error()
{ {
return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier}); return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier});
} }

View File

@ -21,9 +21,9 @@ namespace CodeLiturgy.Views.Controllers
_authManager = authManager; _authManager = authManager;
} }
public IActionResult Index() public async Task<IActionResult> Index()
{ {
OnEveryAction(); await OnEveryAction();
return View(); return View();
} }

View File

@ -1,39 +0,0 @@
using BlueWest.Data.Auth.Context.Users;
using CodeLiturgy.Data.Capital;
using CodeLiturgy.Domain;
using CodeLiturgy.Views.Utils;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
namespace CodeLiturgy.Views.Controllers
{
[Route("api/envs")]
[ApiController]
[Authorize]
public class EnvironmentsController : ControllerBase
{
private ApplicationUserManager _userManager;
private ILogger<UserController> _logger;
private SiteDbContext _siteDbContext;
public EnvironmentsController(ApplicationUserManager userManager, ILogger<UserController> logger, SiteDbContext siteDbContext)
{
_logger = logger;
_userManager = userManager;
_siteDbContext = siteDbContext;
}
[HttpGet]
public async Task<ActionResult<Site>> GetSites()
{
return Ok(new Site());
}
}
}

View File

@ -0,0 +1,75 @@
using BlueWest.Data.Auth.Context.Users;
using CodeLiturgy.Data.Capital;
using CodeLiturgy.Domain;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace CodeLiturgy.Views.Controllers
{
[Route("api/sites")]
[ApiController]
[Authorize]
public class SitesController : ControllerBase
{
private ApplicationUserManager _userManager;
private ILogger<UserController> _logger;
private readonly SiteDbContext _siteDbContext;
public SitesController(ApplicationUserManager userManager, ILogger<UserController> logger, SiteDbContext siteDbContext)
{
_logger = logger;
_userManager = userManager;
_siteDbContext = siteDbContext;
}
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public ActionResult GetSites(
int skip = 0, int take = 50, int orderDir = 1)
{
var (success, sites) = _siteDbContext.GetSites(skip, take, orderDir);
if (!success) return new NotFoundResult();
return Ok(sites);
}
/// <summary>
/// Get Country by Id
/// </summary>
/// <param name="countryId">ISO 3166-1 countryId numeric code</param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{siteId}", Name = nameof(GetSiteById))]
public ActionResult GetSiteById(string siteId)
{
var (success, site) = _siteDbContext.GetOneSiteById(siteId);
if (success)
{
return Ok(site);
}
return new NotFoundResult();
}
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status406NotAcceptable)]
[HttpPost]
public ActionResult AddSite(SiteCreate siteToCreate)
{
var (success, site) = _siteDbContext.AddSite(siteToCreate);
if (!success) return new BadRequestResult();
return CreatedAtRoute(nameof(GetSiteById), new {countryId = site.Id}, site);
}
}
}

View File

@ -73,15 +73,18 @@ public class UserController : Controller
{ {
if (User.IsAuthenticated()) if (User.IsAuthenticated())
{ {
ApplicationUser? user = await _userManager.GetUserAsync(User); ApplicationUser user = await _userManager.GetUserAsync(User);
if (user != null)
{
return new ApplicationUserUnique(user); return new ApplicationUserUnique(user);
} }
}
return null; return null;
} }
public IpInformation ExtractIpInformation(IPAddress? ipAddress) public IpInformation ExtractIpInformation(IPAddress ipAddress)
{ {
string ipAddressString = ""; string ipAddressString = "";
IpType ipType = IpType.Unknown; IpType ipType = IpType.Unknown;
@ -117,7 +120,7 @@ public class UserController : Controller
} }
ViewData[LanguageViewStorage] = currentCultureName; ViewData[LanguageViewStorage] = currentCultureName;
IPAddress? remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress; IPAddress remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;
IpInformation ipInformation = ExtractIpInformation(Request.HttpContext.Connection.RemoteIpAddress); IpInformation ipInformation = ExtractIpInformation(Request.HttpContext.Connection.RemoteIpAddress);

View File

@ -2,7 +2,7 @@ namespace CodeLiturgy.Views.Models;
public class ErrorViewModel public class ErrorViewModel
{ {
public string? RequestId { get; set; } public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
} }

View File

@ -189,7 +189,6 @@ public static class StartupExtensions
IConfiguration configuration, IWebHostEnvironment environment) IConfiguration configuration, IWebHostEnvironment environment)
{ {
return serviceCollection return serviceCollection
.AddDbContextPool<UserDbContext>(options => options.UsePsqlConfiguration(configuration))
.AddDbContextPool<SiteDbContext>(options => options.UsePsqlConfiguration(configuration)) .AddDbContextPool<SiteDbContext>(options => options.UsePsqlConfiguration(configuration))
.AddDbContextPool<CountryDbContext>(options => options.UsePsqlConfiguration(configuration)) .AddDbContextPool<CountryDbContext>(options => options.UsePsqlConfiguration(configuration))
.AddDbContextPool<ApplicationUserDbContext>(options => .AddDbContextPool<ApplicationUserDbContext>(options =>

View File

@ -8,4 +8,4 @@
</div> </div>
@Html.Partial("_FooterMenu"); @await Html.PartialAsync("_FooterMenu");