Strip unnecessary data for the dashboard

This commit is contained in:
Wvader 2022-10-30 16:40:33 +00:00
parent 737238ab41
commit 8379ec8f62
63 changed files with 6 additions and 2805 deletions

View File

@ -1,48 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>10</LangVersion>
<RootNamespace>BlueWest.WebApi</RootNamespace>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<DocumentationFile>bin\$(Configuration)\$(AssemblyName).xml</DocumentationFile>
<PublishDependencyDocumentationFiles>true</PublishDependencyDocumentationFiles>
<AnalysisLevel>preview</AnalysisLevel>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.49.0-pre1" />
<PackageReference Include="Microsoft.AspNetCore.ApiAuthorization.IdentityServer" Version="6.0.8" />
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="6.0.8" />
<PackageReference Include="Microsoft.AspNetCore.Authorization.Policy" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="6.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.2-mauipre.1.22102.15" />
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="6.0.2-mauipre.1.22054.8" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlueWest.Data.Auth\BlueWest.Data.Auth.csproj" />
<ProjectReference Include="..\BlueWest.Domain\BlueWest.Domain.csproj" />
<ProjectReference Include="..\BlueWest\BlueWest.csproj" />
</ItemGroup>
<ItemGroup>
<Content Include="obj\rider.project.restore.info" />
</ItemGroup>
</Project>

View File

@ -1,23 +0,0 @@
using System;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers;
[ApiController]
[Route("application")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
[EnableCors(Constants.CorsPolicyName)]
[ServiceFilter(typeof(SessionAuthorizationFilter))]
public class ApplicationController : ControllerBase
{
[HttpGet]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public ContentResult GetTimeTicks() => Content(
DateTime.Now.Ticks.ToString());
}

View File

@ -1,141 +0,0 @@
using BlueWest.Data.Application.Users;
using BlueWest.Domain;
using BlueWest.WebApi.Context.Users;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers
{
/// <inheritdoc />
[ApiController]
[Route("application/users")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
[EnableCors(Constants.CorsPolicyName)]
[ServiceFilter(typeof(SessionAuthorizationFilter))]
public class ApplicationUserController : ControllerBase
{
private readonly ApplicationUserDbContext _dbContext;
/// <inheritdoc />
public ApplicationUserController(ApplicationUserDbContext context)
{
_dbContext = context;
}
#region Users
/// <summary>
/// Get Application users
/// </summary>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet]
public ActionResult GetApplicationUsers(
int skip = 0,
int take = 50,
int orderDir = 1)
{
var (success, users) = _dbContext.GetUsers( skip, take, orderDir);
if (!success) return new NotFoundResult();
return Ok(users);
}
/// <summary>
/// Updates a User
/// </summary>
/// <param name="UserCode">The UserId ISO 3166 code</param>
/// <param name="UserToUpdate">User payload data</param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpPut("{UserCode}")]
public ActionResult UpdateApplicationUser(string applicationUserId, ApplicationUserUnique UserToUpdate)
{
var (success, updatedUser) = _dbContext.UpdateApplicationUser(UserToUpdate, applicationUserId);
if (success)
{
return Ok(updatedUser);
}
return new NotFoundResult();
}
#endregion
/*
#region GetUserById
/// <summary>
/// Get User by Id
/// </summary>
/// <param name="UserId">ISO 3166-1 UserId numeric code</param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{UserId}", Name = nameof(GetUserById))]
public ActionResult GetUserById(int UserId)
{
var (success, User) = _dbContext.GetOneUserById(UserId);
if (success)
{
return Ok(User);
}
return new NotFoundResult();
}
#endregion
*/
#region Roles
/// <summary>
/// Get Application users
/// </summary>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("roles")]
public ActionResult GetApplicationRoles(
int skip = 0,
int take = 50,
int orderDir = 1)
{
var (success, users) = _dbContext.GetRoles( skip, take, orderDir);
if (!success) return new NotFoundResult();
return Ok(users);
}
#endregion
}
}
/// <summary>
/// Application Constants
/// </summary>
public static class Constants
{
/// <summary>
/// Policy Name
/// </summary>
public const string CorsPolicyName = "_myAllowSpecificOrigins";
}

View File

@ -1,109 +0,0 @@
using System.Threading.Tasks;
using BlueWest.Data.Auth;
using BlueWest.Data.Auth.Context.Users;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers;
/// <summary>
/// Auth controller
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize(Policy = SessionConstants.ApiNamePolicy)]
/*[EnableCors(Constants.CorsPolicyName)]*/
public class AuthController : Controller
{
private readonly IAuthManager _authManager;
private readonly IUserManager _userManager;
/// <summary>
///
/// </summary>
/// <param name="authManager"></param>
/// <param name="userManager"></param>
public AuthController( IAuthManager authManager, IUserManager userManager)
{
_authManager = authManager;
_userManager = userManager;
}
/// <summary>
/// Signup user
/// </summary>
/// <param name="registerRequest"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpPost("register")]
public async Task<ActionResult<IdentityResult>> SignupUserAsync(RegisterRequest registerRequest)
{
return await _authManager.CreateUserAsync(registerRequest);
}
/// <summary>
/// Gets a bearer token
/// </summary>
/// <param name="loginViewModel"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpPost("login")]
public async Task<ActionResult<IdentityResult>> GetSessionToken(LoginRequest loginViewModel)
{
var (success, sessionToken, _) = await _authManager.GetSessionTokenIdByLoginRequest(loginViewModel, JwtBearerDefaults.AuthenticationScheme);
if (success)
{
return Ok(new {sessionToken});
}
return Problem();
}
/// <summary>
/// Do Cookie based login.
/// </summary>
/// <param name="loginDto"></param>
/// <returns></returns>
/*[AllowAnonymous]
[HttpPost("login")]
public async Task<ActionResult> DoLoginByCookie(LoginRequest loginDto)
{
var (success, sessionToken, identity) = await _authManager.GetSessionTokenId(loginDto);
if (success)
{
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity),
new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.Add(SessionConstants.DefaultValidForSpan)
});
return Ok(new {authenticated = true, sessionToken});
}
return new ForbidResult(CookieAuthenticationDefaults.AuthenticationScheme);
}*/
/// <summary>
/// Do Cookie based logout
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[HttpPost("logout")]
public async Task DoCookieLogoutAsync()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
}

View File

@ -1,205 +0,0 @@
using BlueWest.Domain;
using BlueWest.Data;
using BlueWest.Data.Auth;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers
{
/// <summary>
/// Controller responsible to get countryId data
/// </summary>
[ApiController]
[Route("[controller]")]
[Authorize(Policy = SessionConstants.ApiNamePolicy)]
[EnableCors(Constants.CorsPolicyName)]
[ServiceFilter(typeof(SessionAuthorizationFilter))]
// [Authorize(Roles = "Administrator")]
public class CountryController : ControllerBase
{
#region Initialization
private readonly CountryDbContext _dbContext;
/// <summary>
/// Controller responsible for handling countryId data in the Country table
/// </summary>
/// <param name="dbContext"></param>
public CountryController(CountryDbContext dbContext)
{
_dbContext = dbContext;
}
#endregion
public override AcceptedAtActionResult AcceptedAtAction(string actionName, string controllerName)
{
return base.AcceptedAtAction(actionName, controllerName);
}
#region GetCountries
/// <summary>
/// Get countries
/// </summary>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet]
public ActionResult GetCountries(
int skip = 0,
int take = 50,
int orderDir = 1)
{
var (success, countries) = _dbContext.GetCountries( skip, take, orderDir);
if (!success) return new NotFoundResult();
return Ok(countries);
}
#endregion
#region GetCountryById
/// <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("{countryId}", Name = nameof(GetCountryById))]
public ActionResult GetCountryById(int countryId)
{
var (success, country) = _dbContext.GetOneCountryById(countryId);
if (success)
{
return Ok(country);
}
return new NotFoundResult();
}
#endregion
#region GetCountryCurrencies
/// <summary>
/// Get currencies of a countryId
/// </summary>
/// <param name="countryId"></param>
/// <param name="skip">How many records to skip</param>
/// <param name="take">How many records to take</param>
/// <param name="orderDir">The order direction</param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{countryId}/currencies")]
public ActionResult GetCountryCurrencies(int countryId, int skip = 0, int take = 50, int orderDir = 1)
{
var (success, result) = _dbContext.GetCountryCurrencies(countryId, skip, take, orderDir);
if(success)
{
return Ok(result);
}
return new NotFoundResult();
}
#endregion
#region AddCountry
/// <summary>
/// Add Country
/// </summary>
/// <param name="countryToCreate">The countryId data to create</param>
/// <returns>The newly created countryId</returns>
/// /// <summary>
/// Creates a Country.
/// </summary>
/// <remarks>
/// Sample request:
///
/// POST /Countries
/// {
/// "code": 1,
/// "stateName": "United States of America",
/// "tld": "us"
/// }
///
/// </remarks>
/// <response code="201">Returns the newly created countryId</response>
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status406NotAcceptable)]
[HttpPost]
public ActionResult AddCountry(CountryCreate countryToCreate)
{
var (success, country) = _dbContext.AddCountry(countryToCreate);
if (!success) return new BadRequestResult();
return CreatedAtRoute(nameof(GetCountryById), new {countryId = country.Id}, country);
}
#endregion
#region UpdateCountry
/// <summary>
/// Updates a Country
/// </summary>
/// <param name="countryCode">The countryId ISO 3166 code</param>
/// <param name="countryToUpdate">Country payload data</param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpPut("{countryCode}")]
public ActionResult UpdateCountry(int countryCode, CountryUpdate countryToUpdate)
{
var (success, country) = _dbContext.UpdateCountry(countryToUpdate, countryCode);
if (success)
{
return Ok(country);
}
return new NotFoundResult();
}
#endregion
#region AddCurrencyToCountry
/// <summary>
/// Adds a currency to Country
/// </summary>
/// <param name="countryId"></param>
/// <param name="currencyCreate"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
[HttpPost("{countryId}/currencies")]
public ActionResult AddCurrencyToCountry(int countryId, CurrencyCreate currencyCreate)
{
var (success, message, newCurrency) = _dbContext.AddCurrencyToCountry(countryId, currencyCreate);
if(success)
{
return Ok(newCurrency);
}
return new NotFoundObjectResult(message);
}
#endregion
}
}

View File

@ -1,207 +0,0 @@
using BlueWest.Domain;
using BlueWest.Data;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers
{
/// <summary>
/// The controller responsible to fetch currency data
/// </summary>
[ApiController]
[Route("[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
[EnableCors(Constants.CorsPolicyName)]
[ServiceFilter(typeof(SessionAuthorizationFilter))]
// [Authorize(Roles = "Administrator")]
public partial class CurrencyController : ControllerBase
{
#region Initialization
private readonly CountryDbContext _dbContext;
/// <summary>
/// Api Controller for Currency data
/// </summary>
/// <param name="dbContext"></param>
public CurrencyController(CountryDbContext dbContext)
{
_dbContext = dbContext;
}
#endregion
#region GetCurrencies
/// <summary>
/// Gets the currency data from currency table
/// </summary>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet]
public ActionResult GetCurrencies(int skip = 0, int take = 50, int orderDir = 1)
{
var (success, result) = _dbContext.GetCurrencies(skip, take, orderDir);
if (success)
{
return Ok(result);
}
return new NotFoundResult();
}
#endregion
#region GetCurrencyById
/// <summary>
/// Gets a currency by the currency number (id)
/// </summary>
/// <param name="currencyId">The id of the currency to get</param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{currencyId}", Name = nameof(GetCurrencyById))]
public ActionResult GetCurrencyById(int currencyId)
{
var (success, result) = _dbContext.GetOneCurrencyById(currencyId);
if (success)
{
return Ok(result);
}
return new NotFoundResult();
}
#endregion
#region GetCurrencyWithCode
/// <summary>
/// Gets a currency by code.
/// </summary>
/// <param name="currencyCode">The currency Code </param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{currencyCode}", Name = nameof(GetCurrencyWithCode))]
public ActionResult GetCurrencyWithCode(string currencyCode)
{
var (success, currency) =
_dbContext.GetCurrencyWith(x => x.Code == currencyCode);
if (success)
{
return Ok(currency);
}
return new NotFoundResult();
}
#endregion
#region AddCurrency
/// <summary>
/// Add Currency to the table of currencies
/// </summary>
/// <param name="currencyToCreate">Currency data to create</param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status201Created)]
[HttpPost]
public ActionResult AddCurrency(CurrencyCreate currencyToCreate)
{
var (success, newCurrency) = _dbContext.AddCurrency(currencyToCreate);
if (!success)
{
return new NotFoundResult();
}
return CreatedAtRoute(nameof(GetCurrencyById), new { CurrencyId = newCurrency.Code }, newCurrency);
}
#endregion
#region UpdateCurrency
/// <summary>
/// Update a currency data from the Currency table in the database
/// </summary>
/// <param name="currencyNumber">The currency number we want to update</param>
/// <param name="currencyToUpdate">Currency Data to update</param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpPut("{currencyNumber}")]
public ActionResult UpdateCurrency(int currencyNumber, CurrencyUpdate currencyToUpdate)
{
var (success, currency) = _dbContext.UpdateCurrency(currencyToUpdate, currencyNumber);
if (success)
{
return Ok(currency);
}
return new NotFoundResult();
}
#endregion
#region GetCountryFromCurrency
/// <summary>
/// Gets a specific country id in a country
/// </summary>
/// <param name="currencyId">The id of the currency</param>
/// <param name="countryId">The id of the country</param>
/// <returns></returns>
/*
* [GetOneFrom(nameof(Currency.Id), nameof(Country.Id), typeof(CountryUnique))]
*/
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{currencyId}/countries/{countryId}", Name = nameof(GetCountryFromCurrency))]
public ActionResult GetCountryFromCurrency(int currencyId, int countryId)
{
var (success, country) = _dbContext.GetCountryFromCurrency(currencyId, countryId);
if (success)
{
return Ok(country);
}
return new NotFoundResult();
}
#endregion
#region AddCountry
/// <summary>
/// Add Currency to the table of currencies
/// </summary>
/// <param name="countryToCreate"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status201Created)]
[HttpPost("{currencyId}/countries")]
public ActionResult AddCountry(CountryCreate countryToCreate)
{
var (success, result) = _dbContext.AddCountry(countryToCreate);
if (success)
{
return Ok(result);
}
return new BadRequestResult();
}
#endregion
}
}

View File

@ -1,82 +0,0 @@
using System;
using BlueWest.Domain;
using BlueWest.Data;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers;
/// <summary>
/// The controller responsible to fetch currency data
/// </summary>
[ApiController]
[Route("[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
//[Authorize(Roles = "Administrator")]
[EnableCors(Constants.CorsPolicyName)]
[ServiceFilter(typeof(SessionAuthorizationFilter))]
public class FinanceController : ControllerBase
{
private readonly FinanceDbContext _dbContext;
/// <summary>
/// Finance Controller Api Controller
/// </summary>
/// <param name="dbContext">The finance database context</param>
public FinanceController(FinanceDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Returns a transaction by the provided id
/// </summary>
/// <param name="userId"></param>
/// <param name="transactionId"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpGet("{userId}/transactions/{transactionId}")]
public ActionResult GetTransactionsById(int userId, TimeSpan transactionId)
{
return new NotFoundResult();
}
/// <summary>
/// Posts a finance transaction
/// </summary>
/// <param name="userId"></param>
/// <param name="financeTransaction"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpPost("{userId}/transactions")]
public ActionResult PostTransaction(int userId, FinanceOpCreate financeTransaction)
{
return new BadRequestResult();
}
/// <summary>
/// Get Transactions
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpGet("{userId}/transactions")]
public ActionResult GetTransactions(int userId)
{
return Ok();
}
}

View File

@ -1,126 +0,0 @@
using System.Linq;
using BlueWest.Domain;
using BlueWest.Domain;
using BlueWest.Data;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers
{
/// <summary>
/// Api Controller for handling users data
/// </summary>
[ApiController]
[Route("[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
//[Authorize(Roles = "Administrator")]
[EnableCors(Constants.CorsPolicyName)]
public class UserController : ControllerBase
{
private readonly UserDbContext _dbContext;
/// <summary>
/// Controller responsible to handle user data
/// </summary>
/// <param name="dbContext"></param>
public UserController(UserDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Gets all the users in the user table12312
/// </summary>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[HttpGet]
public ActionResult Get()
{
var users = _dbContext.Users.ToArray();
return Ok(users);
}
/// <summary>
/// Get User by Id
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{userId}", Name = nameof(GetUserById))]
public ActionResult GetUserById(int userId)
{
var user = _dbContext.Users.FirstOrDefault(x => x.Id == userId);
if (user != null)
{
return Ok(user);
}
return new NotFoundResult();
}
/// <summary>
/// Adds a user to the database
/// </summary>
/// <param name="userCreate">User to add </param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status201Created)]
[HttpPost]
public ActionResult AddUser(UserCreate userCreate)
{
var user = new User(userCreate);
_dbContext.Users.Add(user);
_dbContext.SaveChanges();
return CreatedAtRoute(nameof(GetUserById), new {userId = user.Id}, user);
}
/// <summary>
/// Updates user data
/// </summary>
/// <param name="userId">User id</param>
/// <param name="userCreate"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpPut($"{{userId:int}}")]
public ActionResult UpdateUser(int userId, UserCreate userCreate)
{
return new NotFoundResult();
}
/// <summary>
/// Deletes a user from the database
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpDelete("{id:int}")]
public ActionResult DeleteUser(int id)
{
var user = _dbContext.Users.FirstOrDefault(u => u.Id == id);
if (user == null)
{
return new NotFoundResult();
}
_dbContext.Users.Remove(user);
_dbContext.SaveChanges();
return Ok();
}
}
}

View File

@ -1,50 +0,0 @@
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
#EXPOSE 80
#EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["BlueWest.Data.Capital/BlueWest.Data.Capital.csproj", "BlueWest.Data.Capital/"]
RUN dotnet restore "BlueWest.Data.Capital/BlueWest.Data.Capital.csproj"
COPY ["BlueWest/BlueWest.csproj", "BlueWest/"]
RUN dotnet restore "BlueWest/BlueWest.csproj"
COPY ["BlueWest.Data.Application/BlueWest.Data.Application.csproj", "BlueWest.Data.Application/"]
RUN dotnet restore "BlueWest.Data.Application/BlueWest.Data.Application.csproj"
COPY ["BlueWest.Api/BlueWest.Api.csproj", "BlueWest.Api/"]
RUN dotnet restore "BlueWest.Api/BlueWest.Api.csproj"
COPY ["include/BlueWest.MapTo/src/BlueWest.MapTo/BlueWest.MapTo.csproj", "include/BlueWest.MapTo/src/BlueWest.MapTo/"]
RUN dotnet restore "include/BlueWest.MapTo/src/BlueWest.MapTo/BlueWest.MapTo.csproj"
COPY ["include/BlueWest.EfMethods/src/BlueWest.EfMethods/BlueWest.EfMethods.csproj", "include/BlueWest.EfMethods/src/BlueWest.EfMethods/"]
RUN dotnet restore "include/BlueWest.EfMethods/src/BlueWest.EfMethods/BlueWest.EfMethods.csproj"
COPY ["include/Math-Expression-Evaluator/SimpleExpressionEvaluator/SimpleExpressionEvaluator.csproj", "include/Math-Expression-Evaluator/SimpleExpressionEvaluator/"]
RUN dotnet restore "include/Math-Expression-Evaluator/SimpleExpressionEvaluator/SimpleExpressionEvaluator.csproj"
COPY [".", "."]
RUN dotnet build "BlueWest.Api/BlueWest.Api.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "BlueWest.Api/BlueWest.Api.csproj" -c Release -o /app/publish --self-contained false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENV ASPNETCORE_URLS http://0.0.0.0:80
WORKDIR /app
ENTRYPOINT ["dotnet", "BlueWest.Api.dll" ]

View File

@ -1,94 +0,0 @@
using System;
using System.Threading.Tasks;
using BlueWest.Domain;
using BlueWest.Domain;
using BlueWest.Tools;
using BlueWest.WebApi.Context;
namespace BlueWest.WebApi.Interfaces
{
/// <summary>
/// Empty constructor
/// </summary>
public struct ExchangeEvent { }
/// <summary>
/// Interface for getting and storing exchange rates data
/// </summary>
///
public sealed class ExchangeInterface : EventListener<ExchangeEvent>, IDisposable, IAsyncDisposable
{
private readonly ApplicationUserDbContext _applicationUserDbContext;
private readonly EventManager _eventManager;
private readonly CountryDbContext _countryDbContext;
private readonly FinanceDbContext _financeDbContext;
private readonly UserDbContext _userDbContext;
#region Initialization
/// <summary>
/// Database Ef context constructor
/// </summary>
/// <param name="countryDbContext">Country context</param>
/// <param name="financeDbContext">Finance context</param>
/// <param name="userDbContext">User context</param>
/// <param name="eventManager">Event manager injection</param>
public ExchangeInterface(
ApplicationUserDbContext applicationUserDbContext,
CountryDbContext countryDbContext,
FinanceDbContext financeDbContext,
UserDbContext userDbContext,
EventManager eventManager)
{
_applicationUserDbContext = applicationUserDbContext;
_countryDbContext = countryDbContext;
_financeDbContext = financeDbContext;
_userDbContext = userDbContext;
_eventManager = eventManager;
Init();
}
/// <summary>
/// Database Ef context constructor
/// </summary>
public ExchangeInterface() { }
private void Init()
{
_eventManager.EventStartListening<ExchangeEvent>(this);
Console.WriteLine($"{nameof(ExchangeInterface)} Just started!");
}
#endregion
/// <summary>
/// On Exchange Event
/// </summary>
/// <param name="eventType"></param>
public void OnEvent(ExchangeEvent eventType)
{
Console.WriteLine($"Service received exchange {nameof(ExchangeEvent)}");
}
/// <summary>
/// Stop Listening for events on dispose
/// </summary>
public void Dispose()
{
_eventManager.EventStopListening<ExchangeEvent>(this);
}
/// <summary>
/// Stop Listening for events on dispose async
/// </summary>
/// <returns></returns>
public ValueTask DisposeAsync()
{
_eventManager.EventStopListening<ExchangeEvent>(this);
return ValueTask.CompletedTask;
}
}
}

View File

@ -1,83 +0,0 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using BlueWest.Core;
using BlueWest.Tools;
using BlueWest.WebApi.Interfaces;
namespace BlueWest.WebApi
{
/// <summary>
/// Entry point of the application.
/// </summary>
public class Program
{
/// <summary>
/// Event Manager class
/// </summary>
public static EventManager EventManager { get; set; }
private static ThreadServer _threadServer;
/*private static CSharpCompilation GenerateCode(string sourceCode)
{
var codeString = SourceText.From(sourceCode);
var parsedSyntaxTree = SyntaxFactory.ParseSyntaxTree(codeString, CSharpParseOptions.Default);
return CSharpCompilation.Create("Hello.dll",
new[] { parsedSyntaxTree },
references: ReferenceAssemblies.Net50, // install jared's Basic.Reference.Assemblies for this, otherwise, you are going to manually add the DLLs you want
options: new CSharpCompilationOptions(OutputKind.ConsoleApplication,
optimizationLevel: OptimizationLevel.Release));
}*/
/// <summary>
/// Host Interface of the application.
/// </summary>
public static IHost MainHost { get; private set; }
/// <summary>
/// Entry point of the application
/// </summary>
/// <param name="args">Command line arguments.</param>
public static void Main(string[] args)
{
MainHost = CreateHostBuilder(args)
.UseContentRoot(Directory.GetCurrentDirectory())
.Build();
MainHost.Run();
//var tryGetEventManager = MainHost.Services.GetService(typeof(EventManager));
// _ = MainHost.Services.GetService(typeof(ExchangeInterface));
/*if(tryGetEventManager == null) Console.WriteLine($"Failed to get {nameof(EventManager)} Service.");
if (tryGetEventManager is EventManager eventManager)
{
// Use RunASync
System.Threading.Thread.Sleep(2500);
_threadServer = new ThreadServer(eventManager);
_threadServer.Init();
}*/
}
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}

View File

@ -1,31 +0,0 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:65056",
"sslPort": 44398
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"BlueWest.WebApi": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
}
}
}
}

View File

@ -1,21 +0,0 @@
syntax = "proto3";
option csharp_namespace = "BlueWest.Streaming";
package greet;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply);
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings.
message HelloReply {
string message = 1;
}

View File

@ -1,9 +0,0 @@
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace BlueWest.WebApi;
public class GreeterService
{
}

View File

@ -1,13 +0,0 @@
using Grpc.Core.Interceptors;
namespace BlueWest.WebApi.Interceptors
{
/// <summary>
/// Server Logger Interceptor
/// </summary>
public class ServerLoggerInterceptor : Interceptor
{
}
}

View File

@ -1,37 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace BlueWest.WebApi.Context.Users;
/// <summary>
/// Reset password view model
/// </summary>
public class ResetPasswordViewModel
{
/// <summary>
/// Email address from which the password needs to be reset.
/// </summary>
[Required]
[EmailAddress]
public string Email { get; set; }
/// <summary>
/// Password
/// </summary>
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
public string Password { get; set; }
/// <summary>
/// Password confirmation
/// </summary>
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
/// <summary>
/// The code to reset password.
/// </summary>
public string Code { get; set; }
}

View File

@ -1,74 +0,0 @@
using System;
using System.Threading.Tasks;
using BlueWest.Data.Auth;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace BlueWest.WebApi.Controllers;
/// <summary>
/// Use this filter where an authorized session is need to navigate in the frontend.
/// </summary>
public class SessionAuthorizationFilter :
IAsyncAuthorizationFilter,
IAuthorizationFilter
{
private ISessionCache _sessionCache { get;}
/// <summary>
/// Session Authorization filter
/// </summary>
/// <param name="sessionCache"></param>
public SessionAuthorizationFilter(ISessionCache sessionCache)
{
_sessionCache = sessionCache;
}
/// <summary>
/// Empty Attribute Constructor
/// </summary>
public SessionAuthorizationFilter() { }
/// <summary>
/// First verification executed before each request
/// </summary>
/// <param name="context"></param>
public void OnAuthorization(AuthorizationFilterContext context)
{
var sessionToken = context.HttpContext.Request.Headers.GetSessionTokenHeader();
if (sessionToken == String.Empty)
{
context.Result = new ForbidResult("Invalid header");
}
var sessionIsValid = _sessionCache.IsSessionValid(sessionToken);
if (!sessionIsValid)
{
context.Result = new ForbidResult("Session is not valid.");
}
}
/// <summary>
/// First verification executed before each request
/// </summary>
/// <param name="context"></param>
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
var sessionToken = context.HttpContext.Request.Headers.GetSessionTokenHeader();
if (sessionToken == String.Empty)
{
context.Result = new ForbidResult("Invalid header");
}
var sessionIsValid = await _sessionCache.IsSessionValidAsync(sessionToken);
if (!sessionIsValid)
{
context.Result = new ForbidResult("Session is not valid.");
}
}
}

View File

@ -1,24 +0,0 @@
using BlueWest.Data.Auth;
using Microsoft.AspNetCore.Http;
namespace BlueWest.WebApi.Controllers
{
public static class SessionExtensions
{
/// <summary>
/// Check for the session token header
/// </summary>
/// <param name="headerDictionary"></param>
/// <returns></returns>
public static string GetSessionTokenHeader(this IHeaderDictionary headerDictionary)
{
if (headerDictionary.ContainsKey(SessionConstants.SessionTokenHeaderName))
{
return headerDictionary[SessionConstants.SessionTokenHeaderName];
}
return string.Empty;
}
}
}

View File

@ -1,130 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using BlueWest.Cryptography;
using BlueWest.Data.Application;
using BlueWest.Data.Auth;
using Microsoft.Extensions.Hosting;
using Redis.OM;
using Redis.OM.Searching;
namespace BlueWest.WebApi.Session
{
/// <summary>
/// Session Provider Context
/// </summary>
public sealed class SessionManager : ISessionCache
{
private readonly RedisConnectionProvider _provider;
private readonly RedisCollection<SessionToken> _sessionTokens;
/// <summary>
/// Index Creation Device
/// </summary>
/// <param name="provider">Redis connection</param>
public SessionManager(
RedisConnectionProvider provider)
{
_provider = provider;
_sessionTokens = (RedisCollection<SessionToken>)provider.RedisCollection<SessionToken>();
}
/// <summary>
/// Empty constructor
/// </summary>
public SessionManager() { }
/// <summary>
/// Get a session token by the respective Id.
/// </summary>
/// <param name="tokenId"></param>
/// <returns></returns>
public async Task<SessionToken> GetSessionTokenByIdAsync(string tokenId)
{
return await _sessionTokens.Where(x => x.Id == tokenId)
.FirstOrDefaultAsync();
}
/// <summary>
/// Create a new session token
/// </summary>
/// <param name="token"></param>
public async Task AddSessionToken(SessionToken token)
{
await _sessionTokens.InsertAsync(token);
}
/// <inheritdoc />
public async Task SaveAsync()
{
await _sessionTokens.SaveAsync();
}
/// <summary>
/// Save session data
/// </summary>
public void Save()
{
_sessionTokens.Save();
}
/// <summary>
/// Gets a Bearer By Access Token Id
/// </summary>
/// <param name="sessionTokenId"></param>
public async Task<bool> IsSessionValidAsync(string sessionTokenId)
{
var accessToken = await _sessionTokens
.Where(t => t.Id == sessionTokenId)
.FirstOrDefaultAsync();
if (accessToken == null) return false;
if (accessToken.IsValid)
{
// Check if it's not expired
var expirationDate = accessToken.CreatedDate + accessToken.ValidFor;
var timeNow = DateTimeOffset.Now.ToUnixTimeMilliseconds();
if (expirationDate >= timeNow) return accessToken.IsValid;
accessToken.IsValid = false;
await _sessionTokens.SaveAsync();
}
return accessToken.IsValid;
}
/// <summary>
/// Checks if a session is valid
/// </summary>
/// <param name="sessionTokenId"></param>
/// <returns></returns>
public bool IsSessionValid(string sessionTokenId)
{
var accessToken = _sessionTokens
.FirstOrDefault(t => t.Id == sessionTokenId);
if (accessToken == null) return false;
if (!accessToken.IsValid) return accessToken.IsValid;
accessToken.Validate();
_sessionTokens.Save();
return accessToken.IsValid;
}
/// <inheritdoc />
public async Task StartAsync(CancellationToken cancellationToken)
{
await _provider.Connection.CreateIndexAsync(typeof(SessionToken));
}
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}

View File

@ -1,191 +0,0 @@
using System;
using System.IO;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json.Serialization;
using BlueWest.Data.Auth;
using BlueWest.Tools;
using BlueWest.WebApi.Interceptors;
using BlueWest.WebApi.Interfaces;
using BlueWest.WebApi.Tools;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
namespace BlueWest.WebApi
{
/// <summary>
/// Startup class for the API.
/// </summary>
public class Startup
{
private readonly IConfiguration _configuration;
private readonly IWebHostEnvironment _environment;
private readonly string MyAllowSpecificOrigins = Constants.CorsPolicyName;
/// <summary>
/// Startup configuration of the API
/// </summary>
public Startup(IConfiguration configuration, IWebHostEnvironment hostEnvironment)
{
_configuration = configuration;
_environment = hostEnvironment;
}
/// <summary>
/// Configure Services
/// </summary>
/// <param name="services">Dependency injection</param>
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:5173/", "http://localhost:5173", "http://127.0.0.1:5173", "localhost:5173")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.Cookie.Name = ".BlueWest.Session";
options.Cookie.Domain = SessionConstants.CookieDomain;
options.Cookie.HttpOnly = true;
});
services
.AddResponseCaching()
.AddControllers(options =>
{
options.CacheProfiles.Add("Default30",
new CacheProfile()
{
Duration = 30
});
})
.AddJsonOptions(options => options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve);
services.AddLogging(builder =>
{
builder.AddSimpleConsole();
});
services
.AddSwaggerGen(options =>
{
options.SchemaFilter<SwaggerEnumSchemaFilter>();
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "BlueWest.Api.App",
Version = "v1"
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath);
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description =
"JWT Authorization header using the Bearer scheme (Example: 'Bearer 12345abcdef')",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
services.AddGrpc(options =>
{
options.Interceptors.Add<ServerLoggerInterceptor>();
});
services.AddSingleton<ServerLoggerInterceptor>();
/*
services.AddSingleton<IFileProvider>(
new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/ImageFiles")
)
);
*/
services
.AddSingleton<EventManager>();
services.AddAuthServerServices( _configuration, _environment);
services.AddScoped<ExchangeInterface>();
services.PrepareMySqlDatabasePool(_configuration, _environment);
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app">Object with the necessary data to configure an application's request pipeline</param>
/// <param name="env">Provides information about the web hosting environment an application is running in.</param>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//app.UseStaticFiles();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "swagger";
c.SwaggerEndpoint("/swagger/v1/swagger.json", "BlueWest.Api v1");
});
app.UseStaticFiles();
//app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
// endpoints.MapGrpcService<GreeterService>();
});
}
}
}

View File

@ -1,256 +0,0 @@
using System;
using System.Text;
using System.Threading.Tasks;
using BlueWest.Domain;
using BlueWest.Domain;
using BlueWest.Cryptography;
using BlueWest.Data.Application.Users;
using BlueWest.Data.Auth;
using BlueWest.Data.Auth.Context.Users;
using BlueWest.WebApi.Configuration;
using BlueWest.WebApi.Context.Users;
using BlueWest.WebApi.Session;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Redis.OM;
namespace BlueWest.WebApi
{
/// <summary>
/// Startup Extensions
/// </summary>
public static class StartupExtensions
{
private static MySqlServerVersion GetMySqlServerVersion(int major, int minor, int build) => new (new Version(major, minor, build));
private static string GetConnectionString(this IConfiguration configurationRoot, string db)
{
// Docker / No-Docker
var startupMode = configurationRoot["mode"];
if (startupMode == "docker")
{
var config = configurationRoot.GetSection("ConnectionStringDocker")[db];
return config;
}
else
{
var config = configurationRoot.GetSection("ConnectionStringNoDocker")[db];
return config;
}
return string.Empty;
}
/// <summary>
/// Get MYSQL Connection String
/// </summary>
/// <param name="optionsBuilder"></param>
/// <param name="configuration"></param>
/// <param name="environment"></param>
private static DbContextOptionsBuilder GetMySqlSettings(
this DbContextOptionsBuilder optionsBuilder,
IConfiguration configuration,
IWebHostEnvironment environment)
{
var sqlVersion = GetMySqlServerVersion(8, 0, 11);
// Docker / No-Docker
var mySqlConnectionString = configuration.GetConnectionString("MySQL");
if (mySqlConnectionString == string.Empty)
{
throw new InvalidOperationException("Fatal error: MySQL Connection string is empty.");
}
optionsBuilder
.UseMySql(
mySqlConnectionString,
sqlVersion)
.UseMySql(sqlVersion,
builder =>
{
builder.EnableRetryOnFailure(6, TimeSpan.FromSeconds(3), null);
});
// The following three options help with debugging, but should
// be changed or removed for production.
if (environment.IsDevelopment())
{
optionsBuilder
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging()
.EnableDetailedErrors();
}
return optionsBuilder;
}
/// <summary>
/// Setup database Contexts
/// </summary>
/// <param name="serviceCollection"></param>
/// <param name="configuration"></param>
/// <param name="environment"></param>
/// <returns></returns>
public static IServiceCollection PrepareMySqlDatabasePool(this IServiceCollection serviceCollection,
IConfiguration configuration, IWebHostEnvironment environment)
{
return serviceCollection
.AddDbContextPool<UserDbContext>(options =>
options.GetMySqlSettings(configuration, environment))
.AddDbContextPool<CountryDbContext>(options =>
options.GetMySqlSettings(configuration, environment))
.AddDbContextPool<FinanceDbContext>(options =>
options.GetMySqlSettings(configuration, environment))
.AddDbContextPool<CompanyDbContext>(options =>
options.GetMySqlSettings(configuration, environment))
.AddDbContextPool<ApplicationUserDbContext>(options =>
options.GetMySqlSettings(configuration, environment));
}
internal static IServiceCollection AddAuthServerServices(this IServiceCollection services, IConfiguration configuration , IWebHostEnvironment environment)
{
var connectionString = configuration.GetConnectionString("Redis");
if (connectionString == null)
{
throw new InvalidOperationException("Redis connection string is empty");
}
services
.AddSingleton(new RedisConnectionProvider(connectionString))
.AddScoped<IJwtTokenHandler, JwtTokenHandler>()
.AddScoped<IJwtFactory, JwtFactory>()
.AddHostedService<SessionManager>()
.AddSingleton<ISessionCache, SessionManager>()
.AddScoped<UserRepository>()
.AddScoped<IUserManager, ApplicationUserManager>()
.AddScoped<IAuthManager, AuthManager>()
.AddScoped<IHasher, Hasher>();
// Database Context and Swagger
// Register the ConfigurationBuilder instance of AuthSettings
var authSettings = configuration.GetSection(nameof(AuthSettings));
services.Configure<AuthSettings>(authSettings);
var signingKey = new SymmetricSecurityKey
(Encoding.ASCII.GetBytes(authSettings[nameof(AuthSettings.SecretKey)]));
// jwt wire up
// Get options from app settings
var jwtAppSettingOptions = configuration
.GetSection(nameof(JwtIssuerOptions));
// Configure JwtIssuerOptions
services.Configure<JwtIssuerOptions>(options =>
{
options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
options.SigningCredentials = new SigningCredentials
(signingKey, SecurityAlgorithms.HmacSha256);
});
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],
ValidateAudience = true,
ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
RequireExpirationTime = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.Cookie.MaxAge = SessionConstants.DefaultSessionMaxAge;
options.LoginPath = "/api/auth/logincookie";
options.LogoutPath = "/api/auth/logout";
})
.AddJwtBearer(configureOptions =>
{
configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
configureOptions.TokenValidationParameters = tokenValidationParameters;
configureOptions.SaveToken = true;
configureOptions.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
},
};
});
// api user claim policy
services.AddAuthorization(options =>
{
options.AddPolicy(SessionConstants.ApiNamePolicy,
policy => policy.RequireClaim(Data.Auth.Context.Users.Constants.JwtClaimIdentifiers.Rol,
Data.Auth.Context.Users.Constants.JwtClaims.ApiAccess));
});
// add identity
var identityBuilder = services.AddIdentityCore<ApplicationUser>(o =>
{
o.User.RequireUniqueEmail = true;
// configure identity options
o.Password.RequireDigit = false;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
o.Password.RequireNonAlphanumeric = false;
o.Password.RequiredLength = 6;
})
.AddUserManager<ApplicationUserManager>()
.AddUserStore<UserRepository>();
identityBuilder = new IdentityBuilder(identityBuilder.UserType, typeof(ApplicationRole), identityBuilder.Services);
identityBuilder
.AddEntityFrameworkStores<ApplicationUserDbContext>()
.AddDefaultTokenProviders();
return services;
}
}
}

View File

@ -1,29 +0,0 @@
using System;
using System.Linq;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace BlueWest.WebApi.Tools
{
/// <inheritdoc />
public class SwaggerEnumSchemaFilter : ISchemaFilter
{
/// <summary>
/// Apply Swagger OpenApi schema
/// </summary>
/// <param name="model">OpenApiSchema model</param>
/// <param name="context">Schema filter context</param>
public void Apply(OpenApiSchema model, SchemaFilterContext context)
{
if (context.Type.IsEnum)
{
model.Enum.Clear();
Enum.GetNames(context.Type)
.ToList()
.ForEach(n => model.Enum.Add(new OpenApiString(n)));
}
}
}
}

View File

@ -1,6 +0,0 @@
dotnet ef database update -c ApplicationUserDbContext
dotnet ef database update -c CountryDbContext
dotnet ef database update -c CompanyDbContext
dotnet ef database update -c UserDbContext

View File

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

View File

@ -1,25 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStringDocker": {
"MySQL": "server=db;user=blueuser;password=dXjw127124dJ;database=bluedb;",
"Redis": "redis://redisinstance:6379"
},
"ConnectionStringNoDocker": {
"MySQL": "server=localhost;user=blueuser;password=dXjw127124dJ;database=bluedb;",
"Redis": "redis://localhost:6379"
},
"AuthSettings": {
"SecretKey": "iJWHDmHLpUA283sqsfhqGbMRdRj1PVkH"
},
"JwtIssuerOptions": {
"Issuer": "SomeIssuer",
"Audience": "http://localhost:5000"
}
}

View File

@ -22,7 +22,6 @@
</ItemGroup>
<ItemGroup>
<Folder Include="Application" />
<Folder Include="Capital" />
</ItemGroup>
<Import Project="..\include\BlueWest.MapTo\src\BlueWest.MapTo\MapTo.props" />

View File

@ -1,30 +0,0 @@
using System;
using System.Collections.Generic;
using MapTo;
namespace BlueWest.Data
{
[MapFrom(new [] {typeof(CompanyCreate), typeof(CompanyUpdate)})]
public partial class Company
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public CompanyType CompanyType { get; set; }
public Country CurrentCountry { get; set; }
public Country OriginCountry { get; set; }
public DateTime FoundingDate { get; set; }
public List<Industry> Industry { get; set; }
public DateTime CreationDate { get; set; }
}
}

View File

@ -1,23 +0,0 @@
using System;
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(Company))]
public partial class CompanyCreate
{
public string Name { get; set; }
public string Address { get; set; }
public Country CurrentCountry { get; set; }
public Country OriginCountry { get; set; }
public DateTime FoundingDate { get; set; }
public DateTime CreateTime { get; } = DateTime.Now;
}
}

View File

@ -1,13 +0,0 @@
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(Company))]
public partial class CompanyType
{
public int Id { get; set; }
public string Name { get; set; }
}
}

View File

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

View File

@ -1,24 +0,0 @@
using System;
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(Company))]
public partial class CompanyUnique
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public CompanyType CompanyType { get; set; }
public Country CurrentCountry { get; set; }
public Country OriginCountry { get; set; }
public DateTime FoundingDate { get; set; }
}
}

View File

@ -1,20 +0,0 @@
using System;
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(Company))]
public partial class CompanyUpdate
{
public string Name { get; set; }
public string Address { get; set; }
public Country CurrentCountry { get; set; }
public Country OriginCountry { get; set; }
public DateTime FoundingDate { get; set; }
}
}

View File

@ -1,19 +0,0 @@
using System.Collections.Generic;
using MapTo;
namespace BlueWest.Data
{
[MapFrom(new []{typeof(ProductUpdate), typeof(ProductCreate), typeof(ProductUnique)})]
public partial class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Size { get; set; }
public double Price { get; set; }
public Currency Currency { get; set; }
public Industry Industry { get; set; }
public List<Company> Seller { get; set; }
}
}

View File

@ -1,13 +0,0 @@
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(Product))]
public partial class ProductCreate
{
public string Name { get; set; }
public string Size { get; set; }
public Industry Industry { get; set; }
}
}

View File

@ -1,15 +0,0 @@
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(Product))]
public partial class ProductUnique
{
public int Id { get; set; }
public string Name { get; set; }
public string Size { get; set; }
public Industry Industry { get; set; }
}
}

View File

@ -1,13 +0,0 @@
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(Product))]
public partial class ProductUpdate
{
public string Name { get; set; }
public string Size { get; set; }
public Industry Industry { get; set; }
}
}

View File

@ -31,7 +31,6 @@ namespace BlueWest.Data
[MaxLength(2)] public string Alpha2Code { get; set; }
public string TLD { get; set; }
public List<Currency> Currencies { get; set; }
public List<User> Users { get; set; }
public DateTime CreationDate { get; set; }

View File

@ -1,8 +0,0 @@
namespace BlueWest.Data.generated
{
public class GeneratedCountries
{
}
}

View File

@ -1,24 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using MapTo;
namespace BlueWest.Data
{
[MapFrom(new []{
typeof(CurrencyUpdate),
typeof(CurrencyCreate),
typeof(CurrencyUnique)
})]
public partial class Currency
{
public int Id { get; set; }
public int Num { get; set; }
[MaxLength(3)] public string Code { get; set; }
public List<Country> Countries { get; set; }
public DateTime CreateDate { get; set; }
}
}

View File

@ -1,15 +0,0 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(Currency))]
public partial class CurrencyCreate
{
public int Num { get; set; }
[MaxLength(3)] public string Code { get; set; }
//public List<CountryUnique> CountriesToCreate { get; set; }
}
}

View File

@ -1,19 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(Currency))]
public partial class CurrencyUnique
{
public int Id { get; set; }
public int Num { get; set; } // Primary key
[MaxLength(3)] public string Code { get; set; }
public DateTime CreateDate { get; set; }
}
}

View File

@ -1,17 +0,0 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(Currency))]
public partial class CurrencyUpdate
{
public int Num { get; set; }
// ISO 4217 Code
[MaxLength(3)] public string Code { get; set; }
}
}

View File

@ -1,19 +0,0 @@
using System;
using System.Collections.Generic;
using MapTo;
namespace BlueWest.Data
{
[MapFrom(new []{typeof(IndustryCreate), typeof(IndustryUpdate)})]
public partial class Industry
{
public int Id { get; set; }
public string IndustryName { get; set; }
public Industry IndustryParent { get; set; }
public List<Industry> IndustryChilds { get; set; }
public DateTime CreateDate { get; set; }
}
}

View File

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

View File

@ -1,17 +0,0 @@
using System;
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(Industry))]
public partial class IndustryUnique
{
public int Id { get; set; }
public string IndustryName { get; set; }
public Industry IndustryParent { get; set; }
public DateTime CreateDate { get; set; }
}
}

View File

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

View File

@ -1,8 +0,0 @@
namespace BlueWest.Data.Media
{
public class MediaSource
{
public MediaSourceType SourceType { get; set; }
}
}

View File

@ -1,8 +0,0 @@
namespace BlueWest.Data.Media
{
public class MediaSourceType
{
public string SourceTypeName { get; set; }
}
}

View File

@ -1,11 +0,0 @@
namespace BlueWest.Data.Media
{
public class Website
{
public int Id { get; set; }
public string WebsiteDomain { get; set; }
public string IsHttps { get; set; }
public bool HasCloudflareLikeService { get; set; }
}
}

View File

@ -1,33 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(FinanceOpCreate))]
public partial class FinanceOp
{
public int UserId { get; set; }
[Key] public int Id;
public TimeSpan CreationDate { get; set; }
[Required] public Currency Currency { get; }
public FinanceOpType Type {get;}
private string Description {get;}
public FinanceOp(TimeSpan creationDate, int userId,
Currency currency, FinanceOpType financeOpType)
{
CreationDate = creationDate;
UserId = userId;
Currency = currency;
Type = financeOpType;
}
}
}

View File

@ -1,31 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using MapTo;
namespace BlueWest.Data
{
[MapFrom( typeof(FinanceOp))]
public partial class FinanceOpCreate
{
public int UserId { get; set; }
public Currency Currency { get; }
public FinanceOpType FinanceOpType {get;}
public FinanceOpCreate(
int userId,
Currency currency ,
FinanceOpType financeOpType
)
{
Currency = currency;
UserId = userId;
Currency = currency;
FinanceOpType = financeOpType;
}
}
}

View File

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using MapTo;
namespace BlueWest.Data
{
[MapFrom(typeof(FinanceOp))]
public partial class FinanceTransactionReadDto
{
public int UserId { get; set; }
public Currency Currency { get; }
public FinanceOpType FinanceOpType {get;}
public TimeSpan CreationDate { get; set; }
}
}

View File

@ -1,15 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace BlueWest.Data
{
public partial class FinanceOpType
{
[Key] public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}

View File

@ -1,38 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using SimpleExpressionEvaluator;
namespace BlueWest.Data;
public class MathOperation
{
[Key] public TimeSpan CreationDate { get; set; }
private bool _isCalculated = false;
private string _expression;
private decimal _resultingAmount;
private ExpressionEvaluator _expressionEvaluator = new ExpressionEvaluator();
public decimal ResultingAmount
{
get
{
if (_isCalculated) return _resultingAmount;
return 0;
}
}
public MathOperation() { }
public MathOperation(string expression, Dictionary<string, decimal> letters)
{
_resultingAmount = _expressionEvaluator.Evaluate(expression, letters);
_isCalculated = true;
}
}

View File

@ -1,8 +0,0 @@
namespace BlueWest.Data
{
public class TransactionAmount
{
public Currency Currency { get; set; }
}
}

View File

@ -13,8 +13,6 @@ namespace BlueWest.Data
public string ApplicationUserId { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public List<FinanceOp> FinanceTransactions { get; set; }
[ForeignKey("CountryId")] public Country Country { get; set; }

View File

@ -1,87 +0,0 @@
using BlueWest.Data;
using BlueWest.Domain.Model;
using BlueWest.EfMethods;
using Microsoft.EntityFrameworkCore;
namespace BlueWest.Domain
{
/// <summary>
/// Context for accessing company data
/// </summary>
[EfGenerator]
public sealed class CompanyDbContext : DbContext
{
#region Companies
/// <summary>
/// Companies.
/// </summary>
[EfAddMethods(typeof(CompanyCreate), typeof(CompanyUnique))]
[EfUpdateMethods(typeof(CompanyUpdate),returnType: typeof(CompanyUnique),nameof(Company.Id))]
public DbSet<Company> Companies { get; set; }
#endregion
#region Industries
/// <summary>
/// Industries.
/// </summary>
[EfAddMethods(typeof(IndustryCreate), typeof(IndustryUnique))]
[EfUpdateMethods(
updateType: typeof(IndustryUpdate),
returnType: typeof(IndustryUnique),
keyPropertyMemberName: nameof(Industry.Id)
)
]
public DbSet<Industry> Industries { get; set; }
#endregion
#region Products
/// <summary>
/// Products
/// </summary>
[EfAddMethods(typeof(ProductCreate), typeof(ProductUnique))]
[EfUpdateMethods(
updateType: typeof(ProductUpdate),
returnType: typeof(ProductUnique),
keyPropertyMemberName: nameof(Product.Id)
)
]
public DbSet<Product> Products { get; set; }
#endregion
#region Initialization
/// <summary>
/// CompanyDbContext constructor.
/// </summary>
/// <param name="options"></param>
public CompanyDbContext(DbContextOptions<CompanyDbContext> 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();
}
#endregion
}
}

View File

@ -28,34 +28,10 @@ namespace BlueWest.Domain
[EfUpdateMethods( updateType: typeof(CountryUpdate), returnType: typeof(CountryUnique), keyPropertyMemberName: nameof(Country.Id))]
[EfGetMany(typeof(CountryUnique))]
[EfGetList(nameof(Country.Currencies), typeof(CurrencyUnique), nameof(Country.Id))]
[EfAddToList(nameof(Country.Currencies), typeof(CurrencyCreate), typeof(CurrencyUnique), nameof(Country.Id))]
[EfGetOneFromList(nameof(Country.Id), nameof(Country.Currencies), nameof(Currency.Id), typeof(CurrencyUnique))]
public DbSet<Country> Countries { get; set; }
#endregion
#region Currencies
/// <summary>
/// Currencies Database Table
/// </summary>
[EfAddMethods(typeof(CurrencyCreate), typeof(CurrencyUnique))]
[EfUpdateMethods(typeof(CurrencyUpdate), typeof(CurrencyUnique), nameof(Currency.Id))]
[EfGetOneBy(nameof(Currency.Id), typeof(CurrencyUnique))]
[EfGetOne(typeof(CurrencyUnique))]
[EfGetMany(typeof(CurrencyUnique))]
[EfGetList(nameof(Currency.Countries), typeof(CountryUnique), nameof(Currency.Id))]
[EfGetOneFromList(nameof(Currency.Id), nameof(Currency.Countries), nameof(Country.Id), typeof(CountryUnique))]
public DbSet<Currency> Currencies { get; set; }
#endregion
#region Initialization
/// <summary>
@ -81,7 +57,6 @@ namespace BlueWest.Domain
{
base.OnModelCreating(modelBuilder);
modelBuilder.ConfigureCurrentDbModel();
modelBuilder.AddCurrencyAndCountryData();
}
#endregion

View File

@ -8,55 +8,8 @@ namespace BlueWest.Domain.Extensions
/// Code first model builder
/// </summary>
public static class ModelBuilderCountryDbContextExtensions
{ /// <summary>
/// Setup the database model
/// </summary>
/// <param name="modelBuilder"></param>
public static void AddCurrencyAndCountryData(this ModelBuilder modelBuilder)
{
var currencies = new List<Currency>();
var usaCountry = new Country();
usaCountry.Id = 1;
usaCountry.Code = 1;
usaCountry.Name = "United States";
usaCountry.Alpha2Code = "US";
usaCountry.StateName = "United States of America";
usaCountry.TLD = "us";
var germanyCountry = new Country();
germanyCountry.Id = 2;
germanyCountry.Code = 2;
germanyCountry.Name = "Germany";
germanyCountry.Alpha2Code = "DE";
germanyCountry.StateName = "Germany";
germanyCountry.TLD = "de";
var dolar = new Currency();
dolar.Id = 1;
dolar.Code = "USD";
dolar.Countries = new List<Country>();
dolar.Countries.Add(usaCountry);
dolar.Num = 1;
var euro = new Currency();
euro.Id = 2;
euro.Code = "EUR";
euro.Countries = new List<Country>();
euro.Countries.Add(germanyCountry);
euro.Num = 2;
modelBuilder
.Entity<Currency>()
.HasData(currencies.ToArray());
}
{
}
}

View File

@ -131,45 +131,12 @@ namespace BlueWest.Domain.Model
.Entity<Country>().Property(country => country.Id)
.ValueGeneratedOnAdd();
// Currency
modelBuilder
.Entity<Currency>(builder => builder
.HasKey(currency => currency.Id))
.Entity<Currency>()
.Property(currency => currency.Id)
.ValueGeneratedOnAdd();
// Company PK
modelBuilder
.Entity<Company>(builder => builder
.HasKey(company => company.Id))
.Entity<Company>().Property(company => company.Id)
.ValueGeneratedOnAdd();
// Industry PK
modelBuilder
.Entity<Industry>(builder => builder
.HasKey(industry => industry.Id))
.Entity<Industry>().Property(industry => industry.Id)
.ValueGeneratedOnAdd();
// Product
modelBuilder
.Entity<Industry>(builder => builder
.HasKey(industry => industry.Id));
modelBuilder
.Entity<Industry>()
.Property(industry => industry.Id)
.ValueGeneratedOnAdd();
// FinanceOp
return
modelBuilder.Entity<FinanceOp>(builder => builder
.HasKey(financeOp => financeOp.Id));
return
modelBuilder;
}
#endregion
@ -178,30 +145,13 @@ namespace BlueWest.Domain.Model
private static ModelBuilder CurrencyModel(this ModelBuilder modelBuilder)
{
modelBuilder.Entity<Currency>().ToTable("Currencies");
modelBuilder.Entity<Country>().ToTable("Countries");
modelBuilder
.Entity<Currency>()
.HasMany(ub => ub.Countries)
.WithMany(au => au.Currencies);
modelBuilder.Entity<Country>()
.HasMany(ub => ub.Currencies)
.WithMany(au => au.Countries);
return modelBuilder;
}
private static ModelBuilder ConfigureUserModel(this ModelBuilder modelBuilder)
{
// FinanceOp => User
modelBuilder
.Entity<FinanceOp>(builder => builder
.HasOne<User>()
.WithMany(ft => ft.FinanceTransactions)
.HasForeignKey(x => x.UserId));
return modelBuilder;
}

View File

@ -1,56 +0,0 @@
using BlueWest.Data;
using BlueWest.Domain.Model;
using Microsoft.EntityFrameworkCore;
namespace BlueWest.Domain
{
/// <summary>
/// Finance operations table
/// </summary>
public sealed class FinanceDbContext : DbContext
{
#region Transactions
/// <summary>
/// Table storing transactions
/// </summary>
public DbSet<FinanceOp> Transactions { get; set; }
#endregion
#region TransactionType
/// <summary>
/// Table storing transaction types.
/// </summary>
public DbSet<FinanceOpType> TransactionTypes { get; set; }
#endregion
#region Initialization
/// <summary>
/// CompanyDbContext constructor.
/// </summary>
/// <param name="options"></param>
public FinanceDbContext(DbContextOptions<FinanceDbContext> 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();
}
#endregion
}
}

View File

@ -216,10 +216,6 @@ public static class StartupExtensions
options.GetMySqlSettings(configuration, environment))
.AddDbContextPool<CountryDbContext>(options =>
options.GetMySqlSettings(configuration, environment))
.AddDbContextPool<FinanceDbContext>(options =>
options.GetMySqlSettings(configuration, environment))
.AddDbContextPool<CompanyDbContext>(options =>
options.GetMySqlSettings(configuration, environment))
.AddDbContextPool<ApplicationUserDbContext>(options =>
options.GetMySqlSettings(configuration, environment));
}

View File

@ -7,8 +7,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlueWest", "BlueWest\BlueWe
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlueWest.Data.Capital", "BlueWest.Data.Capital\BlueWest.Data.Capital.csproj", "{E518C62D-768C-4885-9C9D-FD5761605B54}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlueWest.Api", "BlueWest.Api\BlueWest.Api.csproj", "{6D3321B5-CF1A-4251-B28D-329EDA6DC278}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlueWest.MapTo", "include\BlueWest.MapTo\src\BlueWest.MapTo\BlueWest.MapTo.csproj", "{72B37540-A12F-466E-A58F-7BA2B247CB74}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleExpressionEvaluator", "include\Math-Expression-Evaluator\SimpleExpressionEvaluator\SimpleExpressionEvaluator.csproj", "{30637214-EDE9-4C2E-BFD6-E4B163FA308B}"
@ -57,10 +55,6 @@ Global
{E518C62D-768C-4885-9C9D-FD5761605B54}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E518C62D-768C-4885-9C9D-FD5761605B54}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E518C62D-768C-4885-9C9D-FD5761605B54}.Release|Any CPU.Build.0 = Release|Any CPU
{6D3321B5-CF1A-4251-B28D-329EDA6DC278}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6D3321B5-CF1A-4251-B28D-329EDA6DC278}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6D3321B5-CF1A-4251-B28D-329EDA6DC278}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6D3321B5-CF1A-4251-B28D-329EDA6DC278}.Release|Any CPU.Build.0 = Release|Any CPU
{72B37540-A12F-466E-A58F-7BA2B247CB74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{72B37540-A12F-466E-A58F-7BA2B247CB74}.Debug|Any CPU.Build.0 = Debug|Any CPU
{72B37540-A12F-466E-A58F-7BA2B247CB74}.Release|Any CPU.ActiveCfg = Release|Any CPU