Compare commits

...

5 Commits
master ... dev

  1. 1
      .gitignore
  2. 10
      Cloud_Manager/BiskAcdbContext.cs
  3. 23
      Cloud_Manager/BiskilogContext.cs
  4. 32
      Cloud_Manager/Controllers/KeyGeneratorController.cs
  5. 24
      Cloud_Manager/Controllers/SyncControllers/SyncCompanyInfoController.cs
  6. 24
      Cloud_Manager/Controllers/SyncControllers/SyncProductsController.cs
  7. 24
      Cloud_Manager/Controllers/SyncControllers/SyncSalesController.cs
  8. 33
      Cloud_Manager/Controllers/WeatherForecastController.cs
  9. 43
      Cloud_Manager/Middleware/KeyValidationMiddleware.cs
  10. 15
      Cloud_Manager/Models/ClientContractModels/Clientapikey.cs
  11. 1
      Cloud_Manager/Models/Enums/AuthEnums.cs
  12. 30
      Cloud_Manager/Models/Interfaces/IKeyService.cs
  13. 18
      Cloud_Manager/Models/Interfaces/ITokenService.cs
  14. 242
      Cloud_Manager/Models/ServiceRepo/TokenService.cs
  15. 31
      Cloud_Manager/Program.cs
  16. 58
      Cloud_Manager/Services/AuthenticationService.cs
  17. 48
      Cloud_Manager/Services/CompanyService.cs
  18. 47
      Cloud_Manager/Services/CustomerService.cs
  19. 155
      Cloud_Manager/Services/ProductRepo.cs
  20. 233
      Cloud_Manager/Services/SalesService.cs
  21. 18
      Cloud_Manager/Services/UserService.cs

1
.gitignore

@ -33,6 +33,7 @@ bld/
[Ll]og/ [Ll]og/
[Ll]ogs/ [Ll]ogs/
.config/
# Visual Studio 2015/2017 cache/options directory # Visual Studio 2015/2017 cache/options directory
.vs/ .vs/
# Uncomment if you have tasks that create the project's static files in wwwroot # Uncomment if you have tasks that create the project's static files in wwwroot

10
Cloud_Manager/BiskAcdbContext.cs

@ -11,11 +11,11 @@ public partial class BiskAcdbContext : DbContext
{ {
private readonly HttpContext m_httpContext; private readonly HttpContext m_httpContext;
private readonly IConnectionService m_connection; private readonly IConnectionService m_connection;
private readonly ITokenService m_tokenService; private readonly IKeyService m_tokenService;
public BiskAcdbContext() public BiskAcdbContext()
{ {
} }
public BiskAcdbContext(DbContextOptions<BiskAcdbContext> options, ITokenService tokenService, IConnectionService connection, IHttpContextAccessor a_httpContextAccessor = null) public BiskAcdbContext(DbContextOptions<BiskAcdbContext> options, IKeyService tokenService, IConnectionService connection, IHttpContextAccessor a_httpContextAccessor = null)
: base(options) : base(options)
{ {
m_tokenService = tokenService; m_tokenService = tokenService;
@ -27,10 +27,10 @@ public partial class BiskAcdbContext : DbContext
{ {
if (!optionsBuilder.IsConfigured) if (!optionsBuilder.IsConfigured)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (!String.IsNullOrEmpty(apiKey) && AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
int? databaseId = m_tokenService.GetDatabaseIdFromToken(token); int? databaseId = m_tokenService.GetDatabaseIdFromKey(apiKey);
string connectionString = m_connection.GetClientConnectionString(databaseId!.Value); string connectionString = m_connection.GetClientConnectionString(databaseId!.Value);
optionsBuilder.UseMySql(connectionString, new MariaDbServerVersion(new Version())); optionsBuilder.UseMySql(connectionString, new MariaDbServerVersion(new Version()));
} }

23
Cloud_Manager/BiskilogContext.cs

@ -30,6 +30,7 @@ public partial class BiskilogContext : DbContext
public virtual DbSet<Siteaccesspermission> Siteaccesspermissions { get; set; } public virtual DbSet<Siteaccesspermission> Siteaccesspermissions { get; set; }
public virtual DbSet<Userauth> Userauths { get; set; } public virtual DbSet<Userauth> Userauths { get; set; }
public virtual DbSet<Clientapikey> Clientapikeys { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
@ -162,7 +163,29 @@ public partial class BiskilogContext : DbContext
.HasColumnType("datetime") .HasColumnType("datetime")
.HasColumnName("start_date"); .HasColumnName("start_date");
}); });
modelBuilder.Entity<Clientapikey>(entity =>
{
entity.HasKey(e => e.Id).HasName("PRIMARY");
entity.ToTable("clientapikey");
entity.HasIndex(e => e.ContractId, "contractId");
entity.Property(e => e.Id)
.HasColumnType("int(11)")
.HasColumnName("id");
entity.Property(e => e.ContractId)
.HasColumnType("int(11)")
.HasColumnName("contractId");
entity.Property(e => e.IsActive)
.HasDefaultValueSql("b'1'")
.HasColumnType("bit(1)")
.HasColumnName("isActive");
entity.Property(e => e.Key)
.HasMaxLength(50)
.HasDefaultValueSql("'0'")
.HasColumnName("key");
});
modelBuilder.Entity<Databasemap>(entity => modelBuilder.Entity<Databasemap>(entity =>
{ {
entity.HasKey(e => e.DbNo).HasName("PRIMARY"); entity.HasKey(e => e.DbNo).HasName("PRIMARY");

32
Cloud_Manager/Controllers/KeyGeneratorController.cs

@ -0,0 +1,32 @@
using Cloud_Manager.Models.ClientContractModels;
using Cloud_Manager.Models.CustomModels;
using Cloud_Manager.Models.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Cloud_Manager.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class KeyGeneratorController : ControllerBase
{
private readonly IKeyService m_keyService;
public KeyGeneratorController(IKeyService a_keyService)
{
m_keyService = a_keyService;
}
[HttpPost, Route("generate-key")]
public async Task<IActionResult> GenerateKeyAsync(Contract a_contract)
{
if (await m_keyService.GenerateKey(a_contract))
{
return Ok("Key generated");
}
else
{
return BadRequest();
}
}
}
}

24
Cloud_Manager/Controllers/SyncControllers/SyncCompanyInfoController.cs

@ -24,14 +24,14 @@ namespace Cloud_Manager.Controllers.SyncControllers
m_companyInfo = a_companyInfo; m_companyInfo = a_companyInfo;
} }
// GET: api/<SyncCompanyInfoController> // GET: api/<SyncCompanyInfoController>
[Authorize]
[HttpGet, Route("lastsyncdate/{a_tableName}")] [HttpGet, Route("lastsyncdate/{a_tableName}")]
public DateTime GetLastSyncDate(string a_tableName) public DateTime GetLastSyncDate(string a_tableName)
{ {
return m_salesService.GetLastSyncDate(a_tableName); return m_salesService.GetLastSyncDate(a_tableName);
} }
// Post: api/<SyncCompanyInfoController> // Post: api/<SyncCompanyInfoController>
[Authorize]
[HttpPost, Route("setsyncdate")] [HttpPost, Route("setsyncdate")]
public void SetLastSyncDate(SyncTimestamp a_timestamp) public void SetLastSyncDate(SyncTimestamp a_timestamp)
{ {
@ -42,7 +42,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of SystemUserRoles rows to the cloud /// Endpoint to publish a collection of SystemUserRoles rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/SystemRoles")] [HttpPost, Route("publish/SystemRoles")]
public async Task SyncSyatemRolesAsync(List<Systemuserrole> a_item) public async Task SyncSyatemRolesAsync(List<Systemuserrole> a_item)
{ {
@ -53,7 +53,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblDriver rows to the cloud /// Endpoint to publish a collection of TblDriver rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblDriver")] [HttpPost, Route("publish/tblDriver")]
public async Task SyncDriversAsync(List<Tbldriver> a_item) public async Task SyncDriversAsync(List<Tbldriver> a_item)
{ {
@ -64,7 +64,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of CompanyDetails rows to the cloud /// Endpoint to publish a collection of CompanyDetails rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblcompanydetails")] [HttpPost, Route("publish/tblcompanydetails")]
public async Task SyncCompanyAsync(List<Tblcompanydetail> a_item) public async Task SyncCompanyAsync(List<Tblcompanydetail> a_item)
{ {
@ -75,7 +75,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblUsers rows to the cloud /// Endpoint to publish a collection of TblUsers rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblusers")] [HttpPost, Route("publish/tblusers")]
public async Task SyncUsersAsync(List<Tbluser> a_item) public async Task SyncUsersAsync(List<Tbluser> a_item)
{ {
@ -86,7 +86,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of Trucks rows to the cloud /// Endpoint to publish a collection of Trucks rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tbltrucks")] [HttpPost, Route("publish/tbltrucks")]
public async Task SyncTrucksAsync(List<Tbltruck> a_item) public async Task SyncTrucksAsync(List<Tbltruck> a_item)
{ {
@ -97,7 +97,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblBranch rows to the cloud /// Endpoint to publish a collection of TblBranch rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblbranch")] [HttpPost, Route("publish/tblbranch")]
public async Task SyncBranchAsync(List<Tblbranch> a_item) public async Task SyncBranchAsync(List<Tblbranch> a_item)
{ {
@ -108,7 +108,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblCustomers rows to the cloud /// Endpoint to publish a collection of TblCustomers rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblcustomers")] [HttpPost, Route("publish/tblcustomers")]
public async Task SyncCustomersAsync(List<Tblcustomer> a_item) public async Task SyncCustomersAsync(List<Tblcustomer> a_item)
{ {
@ -119,7 +119,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblTruck Inventory rows to the cloud /// Endpoint to publish a collection of TblTruck Inventory rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tbltruckinventory")] [HttpPost, Route("publish/tbltruckinventory")]
public async Task SyncTruckInventoryAsync(List<Tbltruckinventory> a_item) public async Task SyncTruckInventoryAsync(List<Tbltruckinventory> a_item)
{ {
@ -130,7 +130,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblTruckAssignment rows to the cloud /// Endpoint to publish a collection of TblTruckAssignment rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblTruckAssignment")] [HttpPost, Route("publish/tblTruckAssignment")]
public async Task SyncTruckAssignmentSync(List<Tbltruckassignment> a_item) public async Task SyncTruckAssignmentSync(List<Tbltruckassignment> a_item)
{ {
@ -141,7 +141,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblDriverMapping rows to the cloud /// Endpoint to publish a collection of TblDriverMapping rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tbldrivermappings")] [HttpPost, Route("publish/tbldrivermappings")]
public async Task SyncTruckDriverMappingSync(List<TbltruckDrivermapping> a_item) public async Task SyncTruckDriverMappingSync(List<TbltruckDrivermapping> a_item)
{ {

24
Cloud_Manager/Controllers/SyncControllers/SyncProductsController.cs

@ -17,14 +17,14 @@ namespace Cloud_Manager.Controllers.SyncControllers
m_productService = a_productService; m_productService = a_productService;
} }
// GET: api/<SyncProductsController> // GET: api/<SyncProductsController>
[Authorize]
[HttpGet, Route("lastsyncdate/{a_tableName}")] [HttpGet, Route("lastsyncdate/{a_tableName}")]
public DateTime GetLastSyncDate(string a_tableName) public DateTime GetLastSyncDate(string a_tableName)
{ {
return m_productService.GetLastSyncDate(a_tableName); return m_productService.GetLastSyncDate(a_tableName);
} }
// Post: api/<SyncProductsController> // Post: api/<SyncProductsController>
[Authorize]
[HttpPost, Route("setsyncdate")] [HttpPost, Route("setsyncdate")]
public void SetLastSyncDate(SyncTimestamp a_timestamp) public void SetLastSyncDate(SyncTimestamp a_timestamp)
{ {
@ -35,7 +35,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblProduct rows to the cloud /// Endpoint to publish a collection of TblProduct rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblProducts")] [HttpPost, Route("publish/tblProducts")]
public async Task SyncProductsAsync(List<Tblproduct> a_item) public async Task SyncProductsAsync(List<Tblproduct> a_item)
{ {
@ -46,7 +46,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblInventory rows to the cloud /// Endpoint to publish a collection of TblInventory rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblInventory")] [HttpPost, Route("publish/tblInventory")]
public async Task SyncInventoryAsync(List<Tblinventory> a_item) public async Task SyncInventoryAsync(List<Tblinventory> a_item)
{ {
@ -57,7 +57,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of Restock rows to the cloud /// Endpoint to publish a collection of Restock rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblRestock")] [HttpPost, Route("publish/tblRestock")]
public async Task SyncRestockAsync(List<Restocklevel> a_item) public async Task SyncRestockAsync(List<Restocklevel> a_item)
{ {
@ -68,7 +68,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblInventoryEntries rows to the cloud /// Endpoint to publish a collection of TblInventoryEntries rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblInventoryentry")] [HttpPost, Route("publish/tblInventoryentry")]
public async Task SyncInventoryEntriesAsync(List<Tblinventoryentry> a_item) public async Task SyncInventoryEntriesAsync(List<Tblinventoryentry> a_item)
{ {
@ -79,7 +79,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of PriceChanges rows to the cloud /// Endpoint to publish a collection of PriceChanges rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tlpricechanges")] [HttpPost, Route("publish/tlpricechanges")]
public async Task SyncPriceChangesAsync(List<Tblpricechange> a_item) public async Task SyncPriceChangesAsync(List<Tblpricechange> a_item)
{ {
@ -90,7 +90,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of ProductAltUnit rows to the cloud /// Endpoint to publish a collection of ProductAltUnit rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblProductAltUnit")] [HttpPost, Route("publish/tblProductAltUnit")]
public async Task SyncProductAltUnitAsync(List<Productaltunit> a_item) public async Task SyncProductAltUnitAsync(List<Productaltunit> a_item)
{ {
@ -101,7 +101,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TbStock rows to the cloud /// Endpoint to publish a collection of TbStock rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblStock")] [HttpPost, Route("publish/tblStock")]
public async Task SyncStockAsync(List<Tbstock> a_item) public async Task SyncStockAsync(List<Tbstock> a_item)
{ {
@ -112,7 +112,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblBrands rows to the cloud /// Endpoint to publish a collection of TblBrands rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblbrands")] [HttpPost, Route("publish/tblbrands")]
public async Task SyncBrandsAsync(List<Tblbrand> a_item) public async Task SyncBrandsAsync(List<Tblbrand> a_item)
{ {
@ -123,7 +123,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblCategory rows to the cloud /// Endpoint to publish a collection of TblCategory rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblCategories")] [HttpPost, Route("publish/tblCategories")]
public async Task SyncCategoriesAsync(List<Tblcategory> a_item) public async Task SyncCategoriesAsync(List<Tblcategory> a_item)
{ {
@ -134,7 +134,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of UnitOfMeasure rows to the cloud /// Endpoint to publish a collection of UnitOfMeasure rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblunitofmeasure")] [HttpPost, Route("publish/tblunitofmeasure")]
public async Task SyncUnitMeasureAsync(List<Unitofmeasure> a_item) public async Task SyncUnitMeasureAsync(List<Unitofmeasure> a_item)
{ {

24
Cloud_Manager/Controllers/SyncControllers/SyncSalesController.cs

@ -18,14 +18,14 @@ namespace Cloud_Manager.Controllers.SyncControllers
m_salesService = a_salesService; m_salesService = a_salesService;
} }
// GET: api/<SyncSalesController> // GET: api/<SyncSalesController>
[Authorize]
[HttpGet, Route("lastsyncdate/{a_tableName}")] [HttpGet, Route("lastsyncdate/{a_tableName}")]
public DateTime GetLastSyncDate(string a_tableName) public DateTime GetLastSyncDate(string a_tableName)
{ {
return m_salesService.GetLastSyncDate(a_tableName); return m_salesService.GetLastSyncDate(a_tableName);
} }
// Post: api/<SyncSalesController> // Post: api/<SyncSalesController>
[Authorize]
[HttpPost, Route("setsyncdate")] [HttpPost, Route("setsyncdate")]
public void SetLastSyncDate(SyncTimestamp a_timestamp) public void SetLastSyncDate(SyncTimestamp a_timestamp)
{ {
@ -36,7 +36,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblCart rows to the cloud /// Endpoint to publish a collection of TblCart rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblCart")] [HttpPost, Route("publish/tblCart")]
public async Task SyncSalesAsync(List<Tblcart> a_item) public async Task SyncSalesAsync(List<Tblcart> a_item)
{ {
@ -47,7 +47,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblCancelledTransation rows to the cloud /// Endpoint to publish a collection of TblCancelledTransation rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblcancelledtransaction")] [HttpPost, Route("publish/tblcancelledtransaction")]
public async Task SyncCancelledTransactionAsync(List<Tblcancelledtransaction> a_item) public async Task SyncCancelledTransactionAsync(List<Tblcancelledtransaction> a_item)
{ {
@ -58,7 +58,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of TblInvoice rows to the cloud /// Endpoint to publish a collection of TblInvoice rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblinvoice")] [HttpPost, Route("publish/tblinvoice")]
public async Task SyncInvoiceAsync(List<Tblinvoice> a_item) public async Task SyncInvoiceAsync(List<Tblinvoice> a_item)
{ {
@ -69,7 +69,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of CreditPurchase rows to the cloud /// Endpoint to publish a collection of CreditPurchase rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblCreditpurchase")] [HttpPost, Route("publish/tblCreditpurchase")]
public async Task SyncCreditPurchaseAsync(List<Creditpurchase> a_item) public async Task SyncCreditPurchaseAsync(List<Creditpurchase> a_item)
{ {
@ -80,7 +80,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of Customer Account rows to the cloud /// Endpoint to publish a collection of Customer Account rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblCustomerAccount")] [HttpPost, Route("publish/tblCustomerAccount")]
public async Task SyncCustomerAccountAsync(List<Customeraccount> a_item) public async Task SyncCustomerAccountAsync(List<Customeraccount> a_item)
{ {
@ -91,7 +91,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of Customer Purchase rows to the cloud /// Endpoint to publish a collection of Customer Purchase rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/CustomerPurchase")] [HttpPost, Route("publish/CustomerPurchase")]
public async Task SyncCustomerPurchaseAsync(List<Tblcustomerpurchase> a_item) public async Task SyncCustomerPurchaseAsync(List<Tblcustomerpurchase> a_item)
{ {
@ -102,7 +102,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of Discount logs rows to the cloud /// Endpoint to publish a collection of Discount logs rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/DiscountLogs")] [HttpPost, Route("publish/DiscountLogs")]
public async Task SyncDiscountLogsAsync(List<Tbldiscountlog> a_item) public async Task SyncDiscountLogsAsync(List<Tbldiscountlog> a_item)
{ {
@ -113,7 +113,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of Delivery Head rows to the cloud /// Endpoint to publish a collection of Delivery Head rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblDeliveryhead")] [HttpPost, Route("publish/tblDeliveryhead")]
public async Task SyncDeliveryHeadAsync(List<Tbldeliveryhead> a_item) public async Task SyncDeliveryHeadAsync(List<Tbldeliveryhead> a_item)
{ {
@ -124,7 +124,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of Delivery Details rows to the cloud /// Endpoint to publish a collection of Delivery Details rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblDeliverydetails")] [HttpPost, Route("publish/tblDeliverydetails")]
public async Task SyncDeliveryDetailsAsync(List<Tbldeliverydetail> a_item) public async Task SyncDeliveryDetailsAsync(List<Tbldeliverydetail> a_item)
{ {
@ -135,7 +135,7 @@ namespace Cloud_Manager.Controllers.SyncControllers
/// Endpoint to publish a collection of Delivery Recipient rows to the cloud /// Endpoint to publish a collection of Delivery Recipient rows to the cloud
/// </summary> /// </summary>
/// <param name="a_item"></param> /// <param name="a_item"></param>
[Authorize]
[HttpPost, Route("publish/tblDeliveryrecipient")] [HttpPost, Route("publish/tblDeliveryrecipient")]
public async Task SyncDeliveryRecipientAsync(List<Tbldeliveryrecipient> a_item) public async Task SyncDeliveryRecipientAsync(List<Tbldeliveryrecipient> a_item)
{ {

33
Cloud_Manager/Controllers/WeatherForecastController.cs

@ -1,33 +0,0 @@
using Microsoft.AspNetCore.Mvc;
namespace Cloud_Manager.Controllers
{
[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(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}

43
Cloud_Manager/Middleware/KeyValidationMiddleware.cs

@ -0,0 +1,43 @@
using Cloud_Manager.Models.Enums;
using Cloud_Manager.Models.Interfaces;
using Cloud_Manager.Models.ServiceRepo;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
namespace Cloud_Manager.Middleware
{
public class KeyValidationMiddleware
{
private readonly RequestDelegate m_next;
public KeyValidationMiddleware(RequestDelegate next)
{
m_next = next;
}
public async Task InvokeAsync(HttpContext a_httpContext, IKeyService a_keyService)
{
string apiKey = a_httpContext.Request.Headers["BISK-API-KEY"]!;
AuthEnums status = a_keyService.ValidateKey(apiKey);
if (AuthEnums.Valid != status && a_httpContext.Request.Path != "/api/KeyGenerator/generate-key")
{
a_httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
await a_httpContext.Response.WriteAsync("API Key status : " + status);
return;
}
await m_next.Invoke(a_httpContext);
}
}
public static class KeyValidationMiddlewareExtensions
{
public static IApplicationBuilder UseKeyValidation(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<KeyValidationMiddleware>();
}
}
}

15
Cloud_Manager/Models/ClientContractModels/Clientapikey.cs

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
namespace Cloud_Manager.Models.ClientContractModels;
public partial class Clientapikey
{
public int Id { get; set; }
public string Key { get; set; } = null!;
public int ContractId { get; set; }
public ulong IsActive { get; set; }
}

1
Cloud_Manager/Models/Enums/AuthEnums.cs

@ -9,6 +9,7 @@
Found, Found,
Expired, Expired,
Invalid, Invalid,
Inactive,
Valid, Valid,
Successful, Successful,
Error Error

30
Cloud_Manager/Models/Interfaces/IKeyService.cs

@ -0,0 +1,30 @@
using Cloud_Manager.Models.ClientContractModels;
using Cloud_Manager.Models.Enums;
namespace Cloud_Manager.Models.Interfaces
{
public interface IKeyService
{
/// <summary>
/// Validates specified API
/// </summary>
/// <returns>AuthEnums.Valid if key is a valid and unexpired token</returns>
AuthEnums ValidateKey(string a_Key);
/// <summary>
/// Generates an API Key based on the specified client
/// </summary>
Task<bool> GenerateKey(Contract a_clientContract);
/// <summary>
///Returns the database Id if the API Key is valid to return the related database id
/// </summary>
/// <param name="a_Key"></param>
int? GetDatabaseIdFromKey(string a_Key);
/// <summary>
/// Gets the branch associated with the specified API if valid
/// </summary>
/// <param name="a_Key"></param>
/// <returns></returns>
string GetBaseBranch(string a_Key);
}
}

18
Cloud_Manager/Models/Interfaces/ITokenService.cs

@ -1,18 +0,0 @@
using Cloud_Manager.Models.ClientContractModels;
using Cloud_Manager.Models.Enums;
namespace Cloud_Manager.Models.Interfaces
{
public interface ITokenService
{
AuthEnums ValidateToken(string a_token);
string GenerateToken(Userauth a_user, Contract a_clientContract, Databasemap a_database, List<string> a_business, bool a_comparison);
int? GetDatabaseIdFromToken(string a_token);
int? GetUserIdFromToken(string a_token);
string? GetUserNameFromToken(string a_token);
string? GetBaseBranch(string a_token);
bool? GetComparison(string a_token);
IEnumerable<string> BranchIds(string a_token);
string? GetAllBranch(string a_token);
}
}

242
Cloud_Manager/Models/ServiceRepo/TokenService.cs

@ -1,199 +1,165 @@
using Cloud_Manager.Models.ClientContractModels; using Cloud_Manager.Models.ClientContractModels;
using Cloud_Manager.Models.Enums; using Cloud_Manager.Models.Enums;
using Cloud_Manager.Models.Interfaces; using Cloud_Manager.Models.Interfaces;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims; using System.Security.Claims;
using System.Text; using System.Text;
namespace Cloud_Manager.Models.ServiceRepo namespace Cloud_Manager.Models.ServiceRepo
{ {
public class TokenService : ITokenService public class TokenService : IKeyService
{ {
private IConfiguration m_configuration { get; } private IConfiguration m_configuration { get; }
public TokenService(IConfiguration a_configuration) private readonly Random m_random;
private BiskilogContext m_context;
public TokenService(IConfiguration a_configuration, BiskilogContext a_context)
{ {
m_configuration = a_configuration; m_configuration = a_configuration;
m_context = a_context;
m_random = new Random();
} }
/// <summary> public AuthEnums ValidateKey(string a_Key)
/// Validates a user access token
/// </summary>
/// <returns>AuthEnums.Valid if token is a valid and unexpired token</returns>
public AuthEnums ValidateToken(string a_token)
{ {
try if (!string.IsNullOrEmpty(a_Key))
{ {
string token = a_token.Substring(6).Trim(); Clientapikey? keyInfo = m_context.Clientapikeys.FirstOrDefault(k => k.Key == a_Key);
var handler = new JwtSecurityTokenHandler(); if (keyInfo != null)
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
if (jwtToken.ValidFrom <= DateTime.Now && jwtToken.ValidTo > DateTime.Now)
return AuthEnums.Valid;
return AuthEnums.Expired;
}
catch (Exception ex)
{ {
return AuthEnums.Invalid; if (keyInfo.IsActive == 0)
} {
//Key is not active
return AuthEnums.Inactive;
} }
/// <summary>
/// Generates an access token based on the user if (TryDecodeKey(a_Key, out int businessId))
/// </summary>
/// <returns>A tokenized string</returns>
public string GenerateToken(Userauth a_user, Contract a_clientContract, Databasemap a_database, List<string> a_business, bool a_comparison)
{ {
try Contract? contract = m_context.Contracts.FirstOrDefault(c => c.ContractId == keyInfo.ContractId && c.BusinessId == businessId && c.StartDate <= DateTime.Now && c.EndDate > DateTime.Now);
if (contract == null)
{ {
//create claims details based on the user information contract = m_context.Contracts.FirstOrDefault(c => c.ContractId == keyInfo.ContractId && c.BusinessId == businessId);
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
new Claim("ContractStart",a_clientContract.StartDate !.Value.ToString()),
new Claim("ContractEnd",a_clientContract.EndDate!.Value.ToString()),
new Claim("UserId", a_user.UserId.ToString()),
new Claim("Username", a_user.Username.ToString()),
new Claim("DbId",a_database.DbNo.ToString()),
new Claim("ComparisonMode",a_comparison.ToString()),
new Claim("BranchId",a_business[0].ToString()),
new Claim("BranchAccess",string.Join(", ", a_business.ToArray())),
new Claim("ClientId", a_user.ClientId.ToString()),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(m_configuration["Jwt:Key"]!)); //If contract start date is not past the key should inactive
if (contract?.StartDate > DateTime.Now)
{
return AuthEnums.Inactive;
}
var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //Anyother reason contract is expired
return AuthEnums.Expired;
}
var token = new JwtSecurityToken(m_configuration["Jwt:Issuer"], m_configuration["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddDays(14), signingCredentials: signIn); //Key is valid and contract not expired
return $"{new JwtSecurityTokenHandler().WriteToken(token)}"; return AuthEnums.Valid;
}
} }
catch (Exception ex) else
{ {
Console.WriteLine(ex.Message); return AuthEnums.NotFound;
return AuthEnums.Error.ToString();
} }
} }
/// <summary>
///Deserializes the token string if valid to return the specified user role id in the token string return AuthEnums.Invalid;
/// </summary> }
/// <param name="a_token"></param>
/// <returns>RoleId</returns> public async Task<bool> GenerateKey(Contract a_clientContract)
public int? GetDatabaseIdFromToken(string a_token)
{ {
if (ValidateToken(a_token) == AuthEnums.Valid) const string prefix = "AI";
const char delimiter = '@';
const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder key = new StringBuilder(32);
key.Append(prefix);
key.Append(a_clientContract.BusinessId);
key.Append(delimiter);
for (int i = key.Length; i < 32; i++)
{ {
string token = a_token.Substring(6).Trim(); key.Append(chars[m_random.Next(chars.Length)]);
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
return int.Parse(jwtToken.Claims.First(claim => claim.Type == "DbId").Value);
}
return null;
} }
/// <summary>
///Deserializes the token string if valid to return the specified user id in the token string Clientapikey clientapikey = new Clientapikey();
/// </summary> clientapikey.Key = key.ToString();
/// <param name="a_token"></param> clientapikey.ContractId = a_clientContract.ContractId;
/// <returns>UserId</returns>
public int? GetUserIdFromToken(string a_token) m_context.Clientapikeys.Add(clientapikey);
if (await m_context.SaveChangesAsync() > 0)
{ {
if (ValidateToken(a_token) == AuthEnums.Valid) return true;
}
else
{ {
string token = a_token.Substring(6).Trim(); return false;
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
return int.Parse(jwtToken.Claims.First(claim => claim.Type == "UserId").Value);
} }
return null;
} }
/// <summary>
///Deserializes the token string if valid to return the specified username in the token string public int? GetDatabaseIdFromKey(string a_Key)
/// </summary> {
/// <param name="a_token"></param> if (ValidateKey(a_Key) == AuthEnums.Valid)
/// <returns>Username</returns>
public string? GetUserNameFromToken(string a_token)
{ {
if (ValidateToken(a_token) == AuthEnums.Valid) if (TryDecodeKey(a_Key, out int businessId))
{ {
string token = a_token.Substring(6).Trim(); Clientapikey? keyInfo = m_context.Clientapikeys.FirstOrDefault(k => k.Key == a_Key);
var handler = new JwtSecurityTokenHandler(); Contract? contract = m_context.Contracts.FirstOrDefault(c => c.ContractId == keyInfo.ContractId && c.BusinessId == businessId && c.StartDate <= DateTime.Now && c.EndDate > DateTime.Now);
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
return jwtToken.Claims.First(claim => claim.Type == "Username").Value; Databasemap? databaseMap = m_context.Databasemaps.FirstOrDefault(c => c.ClientId == contract.ClientId);
return databaseMap?.DbNo;
}
} }
return null; return null;
} }
/// <summary>
///Deserializes the token string if valid to return the specified branchId in the token string public string GetBaseBranch(string a_Key)
/// </summary>
/// <param name="a_token"></param>
/// <returns>Username</returns>
public string? GetBaseBranch(string a_token)
{ {
if (ValidateToken(a_token) == AuthEnums.Valid) if (ValidateKey(a_Key) == AuthEnums.Valid)
{ {
string token = a_token.Substring(6).Trim(); if (TryDecodeKey(a_Key, out int businessId))
var handler = new JwtSecurityTokenHandler(); {
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token); Clientapikey? keyInfo = m_context.Clientapikeys.FirstOrDefault(k => k.Key == a_Key);
return jwtToken.Claims.First(claim => claim.Type == "BranchId").Value; Contract? contract = m_context.Contracts.FirstOrDefault(c => c.ContractId == keyInfo.ContractId && c.BusinessId == businessId && c.StartDate <= DateTime.Now && c.EndDate > DateTime.Now);
}
return null;
}
public bool? GetComparison(string a_token) if (contract != null)
{ {
if (ValidateToken(a_token) == AuthEnums.Valid) Clientbusiness? clientbusiness = m_context.Clientbusinesses.FirstOrDefault(cb => cb.ClientId == contract.ClientId && cb.BusinessId == businessId);
if (clientbusiness != null)
{ {
string token = a_token.Substring(6).Trim(); return clientbusiness.BusinessExternalId;
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
return bool.Parse(jwtToken.Claims.First(claim => claim.Type == "ComparisonMode").Value);
} }
return null;
} }
/// <summary>
///Deserializes the token string if valid to return the specified list of branches a user has access to in the token string
/// </summary>
/// <param name="a_token"></param>
/// <returns>Username</returns>
public string? GetAllBranch(string a_token)
{
if (ValidateToken(a_token) == AuthEnums.Valid)
{
string token = a_token.Substring(6).Trim();
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token);
return jwtToken.Claims.First(claim => claim.Type == "BranchAccess").Value;
} }
return null;
} }
/// <summary> return String.Empty;
/// Return a specified list of branches a user has access if comparison mode is set otherwise returns only the }
/// active branch on the list public static bool TryDecodeKey(string a_key, out int o_businessId)
/// </summary>
/// <param name="a_token"></param>
/// <returns></returns>
public IEnumerable<string> BranchIds(string a_token)
{ {
List<string> branchIds = new List<string>(); char delimiter = '@';
if (ValidateToken(a_token) == AuthEnums.Valid) o_businessId = 0;
// Check if the key has the expected length and starts with the expected prefix
if (a_key.Length == 32 && a_key.StartsWith("AI"))
{ {
bool comparison = GetComparison(a_token)!.Value; // Find the index of the delimiter
if (comparison) int delimiterIndex = a_key.IndexOf(delimiter, 2);
// Check if the delimiter is found and there are characters after it
if (delimiterIndex != -1 && delimiterIndex < a_key.Length - 1)
{ {
string? branches = GetAllBranch(a_token); // Attempt to parse the embedded integer value
if (branches != null) if (int.TryParse(a_key.Substring(2, delimiterIndex - 2), out o_businessId))
{ {
string[] branchArray = branches!.Split(); return true; // Successfully decoded
branchIds.AddRange(branchArray);
}
} }
else
{
string? baseBranch = GetBaseBranch(a_token);
branchIds.Add(baseBranch!);
} }
} }
return branchIds.AsEnumerable();
return false; // Failed to decode
} }
} }
} }

31
Cloud_Manager/Program.cs

@ -7,6 +7,10 @@ using Cloud_Manager.Models.Interfaces;
using Cloud_Manager; using Cloud_Manager;
using Cloud_Manager.Services; using Cloud_Manager.Services;
using Cloud_Manager.Models.ServiceRepo; using Cloud_Manager.Models.ServiceRepo;
using Cloud_Manager.Models.Enums;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Cloud_Manager.Middleware;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -23,7 +27,7 @@ builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddDbContext<BiskAcdbContext>(); builder.Services.AddDbContext<BiskAcdbContext>();
builder.Services.AddScoped<ICompanyInfo, CompanyService>(); builder.Services.AddScoped<ICompanyInfo, CompanyService>();
builder.Services.AddScoped<IAuthService, AuthenticationService>(); builder.Services.AddScoped<IAuthService, AuthenticationService>();
builder.Services.AddScoped<ITokenService, TokenService>(); builder.Services.AddScoped<IKeyService, TokenService>();
builder.Services.AddScoped<IConnectionService, ConnectionService>(); builder.Services.AddScoped<IConnectionService, ConnectionService>();
builder.Services.AddScoped<IProduct, ProductRepo>(); builder.Services.AddScoped<IProduct, ProductRepo>();
builder.Services.AddScoped<ISalesInterface, SalesService>(); builder.Services.AddScoped<ISalesInterface, SalesService>();
@ -35,24 +39,21 @@ builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
});
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SecureSwagger v1"));
app.UseHttpsRedirection(); var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SecureSwagger v1"));
}else
{
app.UseHttpsRedirection();
}
app.UseKeyValidation();
app.UseCors("CorsPolicy");
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization();
app.MapControllers(); app.MapControllers();

58
Cloud_Manager/Services/AuthenticationService.cs

@ -9,9 +9,9 @@ namespace Cloud_Manager.Services
public class AuthenticationService : IAuthService public class AuthenticationService : IAuthService
{ {
private readonly BiskilogContext m_context; private readonly BiskilogContext m_context;
private readonly ITokenService m_tokenService; private readonly IKeyService m_tokenService;
public AuthenticationService(BiskilogContext a_context, ITokenService a_tokenService) public AuthenticationService(BiskilogContext a_context, IKeyService a_tokenService)
{ {
m_context = a_context; m_context = a_context;
m_tokenService = a_tokenService; m_tokenService = a_tokenService;
@ -32,36 +32,10 @@ namespace Cloud_Manager.Services
return AuthEnums.NotFound; return AuthEnums.NotFound;
} }
} }
/// <summary>
/// Autenticates a user and returns a tokenized string
/// </summary>
/// <param name="a_username"></param>
/// <param name="a_password"></param>
/// <returns>strings</returns>
public async Task<string> AuthenticateClient(string a_username, string a_password) public Task<string> AuthenticateClient(string a_username, string a_password)
{ {
var user = await GetUserAsync(a_username, a_password); throw new NotImplementedException();
if (user == null)
{
return null;
}
user.LastLogin = DateTime.Now;
m_context.Userauths.Update(user);
m_context.SaveChanges();
Databasemap databasemap = GetClientDB(user.ClientId);
List<int> businessIds = GetSiteaccesspermission(user.ClientId, user.UserId).Select(t => t.BusinessId).ToList();
Contract? contract = GetContract(user.ClientId, businessIds);
List<string> businesses = GetClientbusiness(user.ClientId, user.UserId).Select(t => t.BusinessExternalId).ToList();
if (contract == null)
return AuthEnums.Invalid.ToString();
return m_tokenService.GenerateToken(user, contract, databasemap, businesses, false);
} }
/// <summary> /// <summary>
@ -118,29 +92,5 @@ namespace Cloud_Manager.Services
{ {
return m_context.Siteaccesspermissions.Where(t => t.ClientId == a_clientId && t.UserId == a_userId).ToList(); return m_context.Siteaccesspermissions.Where(t => t.ClientId == a_clientId && t.UserId == a_userId).ToList();
} }
private async Task<Userauth> GetUserAsync(string username, string password)
{
//Todo have complete implementation after means of creating user is done
//try
//{
// string pa = await m_context.Userauths.Where(u => u.Username == username).Select(u => u.Password).FirstAsync();
// bool verified = BCrypt.Net.BCrypt.Verify(password, pa);
// if (verified)
// {
//TODO have a complete implementation
return await m_context.Userauths.FirstAsync(u => u.Username == username && u.Passsword == password);
// }
// else
// {
// return null;
// }
//}catch(Exception ex)
//{
// //possible is user not found
// return null;
//}
}
} }
} }

48
Cloud_Manager/Services/CompanyService.cs

@ -12,12 +12,12 @@ namespace Cloud_Manager.Services
public class CompanyService : ICompanyInfo public class CompanyService : ICompanyInfo
{ {
private readonly BiskAcdbContext m_context; private readonly BiskAcdbContext m_context;
private readonly ITokenService m_tokenService; private readonly IKeyService m_tokenService;
private readonly HttpContext m_httpContext; private readonly HttpContext m_httpContext;
private Tblcompanydetail m_companyInfo { get; set; } private Tblcompanydetail m_companyInfo { get; set; }
private IEnumerable<Tblbranch> m_companyBranches { get; set; } private IEnumerable<Tblbranch> m_companyBranches { get; set; }
public CompanyService(BiskAcdbContext a_context, ITokenService a_tokenService, IHttpContextAccessor a_httpContextAccessor) public CompanyService(BiskAcdbContext a_context, IKeyService a_tokenService, IHttpContextAccessor a_httpContextAccessor)
{ {
m_context = a_context; m_context = a_context;
m_tokenService = a_tokenService; m_tokenService = a_tokenService;
@ -56,8 +56,8 @@ namespace Cloud_Manager.Services
} }
public async Task SyncBranches(List<Tblbranch> a_items) public async Task SyncBranches(List<Tblbranch> a_items)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_items); string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -72,10 +72,10 @@ namespace Cloud_Manager.Services
} }
public DateTime GetLastSyncDate(string a_tablename) public DateTime GetLastSyncDate(string a_tablename)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string activeBranch = m_tokenService.GetBaseBranch(token)!; string activeBranch = m_tokenService.GetBaseBranch(apiKey)!;
DateTime? lastSync = m_context.Tblsyncinfos.FirstOrDefault(p => p.TableName == a_tablename && p.BranchId == activeBranch!)?.LastSyncDate; DateTime? lastSync = m_context.Tblsyncinfos.FirstOrDefault(p => p.TableName == a_tablename && p.BranchId == activeBranch!)?.LastSyncDate;
if (lastSync != null) if (lastSync != null)
@ -88,10 +88,10 @@ namespace Cloud_Manager.Services
public void SetLastSyncDate(string a_tableName, DateTime a_timestamp) public void SetLastSyncDate(string a_tableName, DateTime a_timestamp)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string activeBranch = m_tokenService.GetBaseBranch(token)!; string activeBranch = m_tokenService.GetBaseBranch(apiKey)!;
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
{ {
m_context.Database.OpenConnection(); m_context.Database.OpenConnection();
@ -108,8 +108,8 @@ namespace Cloud_Manager.Services
public async Task SyncSystemRoles(List<Systemuserrole> a_roles) public async Task SyncSystemRoles(List<Systemuserrole> a_roles)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_roles); string jsonString = JsonSerializer.Serialize(a_roles);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -124,8 +124,8 @@ namespace Cloud_Manager.Services
} }
public async Task SyncCompanyDetails(List<Tblcompanydetail> a_details) public async Task SyncCompanyDetails(List<Tblcompanydetail> a_details)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_details); string jsonString = JsonSerializer.Serialize(a_details);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -141,8 +141,8 @@ namespace Cloud_Manager.Services
public async Task SyncDriverDetails(List<Tbldriver> a_details) public async Task SyncDriverDetails(List<Tbldriver> a_details)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_details); string jsonString = JsonSerializer.Serialize(a_details);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -158,8 +158,8 @@ namespace Cloud_Manager.Services
public async Task SyncTrucks(List<Tbltruck> a_trucks) public async Task SyncTrucks(List<Tbltruck> a_trucks)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_trucks); string jsonString = JsonSerializer.Serialize(a_trucks);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -175,8 +175,8 @@ namespace Cloud_Manager.Services
public async Task SyncTruckAssignments(List<Tbltruckassignment> a_assignments) public async Task SyncTruckAssignments(List<Tbltruckassignment> a_assignments)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_assignments); string jsonString = JsonSerializer.Serialize(a_assignments);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -192,8 +192,8 @@ namespace Cloud_Manager.Services
public async Task SyncTruckMappings(List<TbltruckDrivermapping> a_mapping) public async Task SyncTruckMappings(List<TbltruckDrivermapping> a_mapping)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_mapping); string jsonString = JsonSerializer.Serialize(a_mapping);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -209,8 +209,8 @@ namespace Cloud_Manager.Services
public async Task SyncTruckInventory(List<Tbltruckinventory> a_inventories) public async Task SyncTruckInventory(List<Tbltruckinventory> a_inventories)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_inventories); string jsonString = JsonSerializer.Serialize(a_inventories);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())

47
Cloud_Manager/Services/CustomerService.cs

@ -13,10 +13,10 @@ namespace Cloud_Manager.Services
public class CustomerService : ICustomer public class CustomerService : ICustomer
{ {
private readonly BiskAcdbContext m_context; private readonly BiskAcdbContext m_context;
private readonly ITokenService m_tokenService; private readonly IKeyService m_tokenService;
private readonly HttpContext m_httpContext; private readonly HttpContext m_httpContext;
public CustomerService(BiskAcdbContext a_context, ITokenService a_tokenService, IHttpContextAccessor a_httpContextAccessor) public CustomerService(BiskAcdbContext a_context, IKeyService a_tokenService, IHttpContextAccessor a_httpContextAccessor)
{ {
m_context = a_context; m_context = a_context;
m_tokenService = a_tokenService; m_tokenService = a_tokenService;
@ -24,44 +24,7 @@ namespace Cloud_Manager.Services
} }
public IEnumerable<CustomerAccounts> FetchCustomers() public IEnumerable<CustomerAccounts> FetchCustomers()
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; throw new NotImplementedException();
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "CALL GetCustomers(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", string.Join(", ", accessiblebranches.ToArray())));
m_context.Database.OpenConnection();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return new CustomerAccounts
{
Customer = new Tblcustomer
{
CustomerId = reader.GetString(0),
BranchId = reader.GetString(1),
Firstname = reader.GetString(2),
Surname = reader.GetString(3),
Address = reader.GetString(4),
Telephone = reader.GetString(5),
DateAdded = reader.GetDateTime(6),
Status = reader.GetString(7),
Email = reader.GetString(8),
FinancialStatus = reader.GetString(9),
},
Debt = reader.GetDecimal(10)
};
}
}
}
}
} }
public Task<IEnumerable<CustomerAccounts>> GetCustomers() public Task<IEnumerable<CustomerAccounts>> GetCustomers()
@ -71,8 +34,8 @@ namespace Cloud_Manager.Services
public async Task SyncCustomers(List<Tblcustomer> a_details) public async Task SyncCustomers(List<Tblcustomer> a_details)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_details); string jsonString = JsonSerializer.Serialize(a_details);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())

155
Cloud_Manager/Services/ProductRepo.cs

@ -15,7 +15,7 @@ namespace Cloud_Manager.Services
public class ProductRepo : IProduct public class ProductRepo : IProduct
{ {
private readonly BiskAcdbContext m_context; private readonly BiskAcdbContext m_context;
private readonly ITokenService m_tokenService; private readonly IKeyService m_tokenService;
private readonly HttpContext m_httpContext; private readonly HttpContext m_httpContext;
public event EventHandler ProductsChanged; public event EventHandler ProductsChanged;
@ -23,7 +23,7 @@ namespace Cloud_Manager.Services
public event EventHandler BrandsChanged; public event EventHandler BrandsChanged;
public event EventHandler CategoriesChanged; public event EventHandler CategoriesChanged;
public ProductRepo(BiskAcdbContext a_context, ITokenService a_tokenService, IHttpContextAccessor a_httpContextAccessor) public ProductRepo(BiskAcdbContext a_context, IKeyService a_tokenService, IHttpContextAccessor a_httpContextAccessor)
{ {
m_context = a_context; m_context = a_context;
m_tokenService = a_tokenService; m_tokenService = a_tokenService;
@ -35,124 +35,35 @@ namespace Cloud_Manager.Services
/// <returns></returns> /// <returns></returns>
public IEnumerable<ProductItem> GetProducts(string a_productKey = "") public IEnumerable<ProductItem> GetProducts(string a_productKey = "")
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; throw new NotImplementedException();
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "CALL GetProducts(@p0)";
command.Parameters.Add(new MySqlParameter("@p0", string.Join(", ", accessiblebranches.ToArray())));
m_context.Database.OpenConnection();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
List<ProductUnits> pUnits = new List<ProductUnits>();
yield return new ProductItem
{
Product = new Tblproduct
{
Pcode = reader.GetString(0),
ProductName = reader.GetString(1),
Pdesc = reader.GetString(2),
BaseUnit = reader.GetString(3),
Costprice = reader.GetDecimal(4),
Status = reader.GetString(5),
Price = reader.GetDecimal(6),
BranchId = reader.GetString(7),
},
BaseUnit = reader.GetString(3),
Stock = new Tblinventory
{
Quantity = reader.GetInt32(8)
},
Restocklevel = new Restocklevel
{
WarnLevel = reader.GetInt32(9),
Unit = reader.GetString(10),
},
Units = GetAltUnits(reader)
};
}
}
}
}
} }
private List<ProductUnits> GetAltUnits(DbDataReader a_reader) private List<ProductUnits> GetAltUnits(DbDataReader a_reader)
{ {
List<ProductUnits> pUnits = new List<ProductUnits>(); throw new NotImplementedException();
for (int i = 1; i < 5; i++)
{
if (!a_reader.IsDBNull(a_reader.GetOrdinal($"AltUnit{i}")))
{
pUnits.Add(new ProductUnits
{
UnitCode = a_reader.GetFieldValue<string>($"AltUnit{i}"),
QuantityUnit = a_reader.GetFieldValue<int>($"AltUnit{i}QTY"),
PriceUnit = a_reader.GetFieldValue<decimal>($"AltUnit{i}Price"),
DistinctiveCode = a_reader.GetFieldValue<string>($"AltUnit{i}distinctiveCode")
});
}
else
{
return pUnits;
}
}
return pUnits;
} }
public IEnumerable<Unitofmeasure> GetUnitofmeasures() public IEnumerable<Unitofmeasure> GetUnitofmeasures()
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; throw new NotImplementedException();
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
return m_context.Unitofmeasures.Where(b => accessiblebranches.Contains(b.BranchId));
}
return new List<Unitofmeasure>();
} }
public IEnumerable<Tblbrand> GetBrands(string a_brandKey = "") public IEnumerable<Tblbrand> GetBrands(string a_brandKey = "")
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; throw new NotImplementedException();
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
return m_context.Tblbrands.Where(b => accessiblebranches.Contains(b.BranchId));
}
return new List<Tblbrand>();
} }
public IEnumerable<Tblcategory> GetCategories(string a_categoryKey = "") public IEnumerable<Tblcategory> GetCategories(string a_categoryKey = "")
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; throw new NotImplementedException();
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
return m_context.Tblcategories.Where(b => accessiblebranches.Contains(b.BranchId));
}
return new List<Tblcategory>();
} }
public async Task SyncProducts(List<Tblproduct> a_item) public async Task SyncProducts(List<Tblproduct> a_item)
{ {
try try
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_item); string jsonString = JsonSerializer.Serialize(a_item);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -173,8 +84,8 @@ namespace Cloud_Manager.Services
public async Task SyncInventory(List<Tblinventory> a_item) public async Task SyncInventory(List<Tblinventory> a_item)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_item); string jsonString = JsonSerializer.Serialize(a_item);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -190,8 +101,8 @@ namespace Cloud_Manager.Services
public async Task SyncInventoryEntries(List<Tblinventoryentry> a_item) public async Task SyncInventoryEntries(List<Tblinventoryentry> a_item)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_item); string jsonString = JsonSerializer.Serialize(a_item);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -207,8 +118,8 @@ namespace Cloud_Manager.Services
public async Task SyncPriceChanges(List<Tblpricechange> a_items) public async Task SyncPriceChanges(List<Tblpricechange> a_items)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_items); string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -224,8 +135,8 @@ namespace Cloud_Manager.Services
public async Task SyncProductAltUnit(List<Productaltunit> a_items) public async Task SyncProductAltUnit(List<Productaltunit> a_items)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_items); string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -241,8 +152,8 @@ namespace Cloud_Manager.Services
public async Task SyncRestockAsync(List<Restocklevel> a_items) public async Task SyncRestockAsync(List<Restocklevel> a_items)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_items); string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -258,8 +169,8 @@ namespace Cloud_Manager.Services
public async Task SyncUnitOfMeasureAsync(List<Unitofmeasure> a_items) public async Task SyncUnitOfMeasureAsync(List<Unitofmeasure> a_items)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_items); string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -275,8 +186,8 @@ namespace Cloud_Manager.Services
public async Task SyncStockAsync(List<Tbstock> a_items) public async Task SyncStockAsync(List<Tbstock> a_items)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_items); string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -292,8 +203,8 @@ namespace Cloud_Manager.Services
public async Task SyncBrandsAsync(List<Tblbrand> a_items) public async Task SyncBrandsAsync(List<Tblbrand> a_items)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_items); string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -309,8 +220,8 @@ namespace Cloud_Manager.Services
public async Task SyncCategoriesAsync(List<Tblcategory> a_items) public async Task SyncCategoriesAsync(List<Tblcategory> a_items)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_items); string jsonString = JsonSerializer.Serialize(a_items);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -325,10 +236,10 @@ namespace Cloud_Manager.Services
} }
public DateTime GetLastSyncDate(string a_tablename) public DateTime GetLastSyncDate(string a_tablename)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string activeBranch = m_tokenService.GetBaseBranch(token)!; string activeBranch = m_tokenService.GetBaseBranch(apiKey)!;
DateTime? lastSync = m_context.Tblsyncinfos.FirstOrDefault(p => p.TableName == a_tablename && p.BranchId == activeBranch!)?.LastSyncDate; DateTime? lastSync = m_context.Tblsyncinfos.FirstOrDefault(p => p.TableName == a_tablename && p.BranchId == activeBranch!)?.LastSyncDate;
if (lastSync != null) if (lastSync != null)
@ -341,10 +252,10 @@ namespace Cloud_Manager.Services
public void SetLastSyncDate(string a_tableName, DateTime a_timestamp) public void SetLastSyncDate(string a_tableName, DateTime a_timestamp)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string activeBranch = m_tokenService.GetBaseBranch(token)!; string activeBranch = m_tokenService.GetBaseBranch(apiKey)!;
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
{ {
m_context.Database.OpenConnection(); m_context.Database.OpenConnection();

233
Cloud_Manager/Services/SalesService.cs

@ -14,7 +14,7 @@ namespace Cloud_Manager.Services
public class SalesService : ISalesInterface public class SalesService : ISalesInterface
{ {
private readonly BiskAcdbContext m_context; private readonly BiskAcdbContext m_context;
private readonly ITokenService m_tokenService; private readonly IKeyService m_tokenService;
private readonly HttpContext m_httpContext; private readonly HttpContext m_httpContext;
private readonly IHubContext<SalesHub, ISalesHub> m_salesHub; private readonly IHubContext<SalesHub, ISalesHub> m_salesHub;
@ -22,7 +22,7 @@ namespace Cloud_Manager.Services
public event EventHandler FetchComplete; public event EventHandler FetchComplete;
public event EventHandler FetchStart; public event EventHandler FetchStart;
public SalesService(BiskAcdbContext a_context, ITokenService a_tokenService, public SalesService(BiskAcdbContext a_context, IKeyService a_tokenService,
IHttpContextAccessor a_httpContextAccessor, IHubContext<SalesHub, ISalesHub> a_salesHub) IHttpContextAccessor a_httpContextAccessor, IHubContext<SalesHub, ISalesHub> a_salesHub)
{ {
m_context = a_context; m_context = a_context;
@ -31,151 +31,11 @@ namespace Cloud_Manager.Services
m_salesHub = a_salesHub; m_salesHub = a_salesHub;
} }
public Task FetchRecentTransaction(int a_limit)
{
throw new NotImplementedException();
}
public IEnumerable<SaleItem> GetRecentTransaction()
{
throw new NotImplementedException();
}
public IEnumerable<SaleItem> GetTransactions(DateTime a_start, DateTime a_end)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "CALL GetTransactionsByDate(@p0,@p1,@p2)";
command.Parameters.Add(new MySqlParameter("@p0", a_start.ToString("yyyy-MM-dd")));
command.Parameters.Add(new MySqlParameter("@p1", a_end.ToString("yyyy-MM-dd")));
command.Parameters.Add(new MySqlParameter("@p2", string.Join(", ", accessiblebranches.ToArray())));
m_context.Database.OpenConnection();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return new SaleItem
{
Transno = reader.GetString(0),
Total = (decimal)reader.GetDouble(1),
Date = reader.GetDateTime(2),
Cashier = reader.GetString(3),
BranchId = reader.GetString(4),
Customer = reader.GetString(5),
Status = reader.GetString(6),
};
}
}
}
}
}
public Task FetchTransaction(DateTime a_start, DateTime a_end)
{
throw new NotImplementedException();
}
public Task FetchReceipt(string a_receiptId)
{
throw new NotImplementedException();
}
public IEnumerable<SaleItem> GetReceipt(string a_receiptId)
{
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "CALL GetTransactionsById(@p0,@p1)";
command.Parameters.Add(new MySqlParameter("@p0", a_receiptId));
command.Parameters.Add(new MySqlParameter("@p1", string.Join(", ", accessiblebranches.ToArray())));
m_context.Database.OpenConnection();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return new SaleItem
{
Transno = reader.GetString(0),
Total = (decimal)reader.GetDouble(1),
Date = reader.GetDateTime(2),
Cashier = reader.GetString(3),
BranchId = reader.GetString(4),
Customer = reader.GetString(5),
Status = reader.GetString(6),
};
}
}
// Close the connection explicitly
m_context.Database.CloseConnection();
}
}
}
public Task<IEnumerable<Tblcart>> GetReceiptDetail(string a_receiptId)
{
List<Tblcart> details = new List<Tblcart>();
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
using (var command = m_context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "CALL GetReceiptDetails(@p0,@p1)";
command.Parameters.Add(new MySqlParameter("@p0", a_receiptId));
command.Parameters.Add(new MySqlParameter("@p1", string.Join(", ", accessiblebranches.ToArray())));
m_context.Database.OpenConnection();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
details.Add(new Tblcart
{
Transno = a_receiptId,
Id = reader.GetString(0),
Quantity = reader.GetInt32(1),
Date = reader.GetDateTime(2),
Price = reader.GetDecimal(3),
Cashier = reader.GetString(4),
Status = reader.GetString(5),
Total = (decimal)reader.GetDouble(6),
Unit = reader.GetString(7),
Costprice = reader.GetDecimal(8),
BranchId = reader.GetString(9),
CountId = reader.GetString(10),
Tendered = reader.GetDecimal(11),
Balance = reader.GetDecimal(12),
ValueAddTax = reader.GetDecimal(13)
});
}
}
}
}
return Task.FromResult(details.AsEnumerable());
}
public async Task SyncCart(List<Tblcart> a_item) public async Task SyncCart(List<Tblcart> a_item)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_item); string jsonString = JsonSerializer.Serialize(a_item);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -191,10 +51,10 @@ namespace Cloud_Manager.Services
public DateTime GetLastSyncDate(string a_tablename) public DateTime GetLastSyncDate(string a_tablename)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string activeBranch = m_tokenService.GetBaseBranch(token)!; string activeBranch = m_tokenService.GetBaseBranch(apiKey)!;
DateTime? lastSync = m_context.Tblsyncinfos.FirstOrDefault(p => p.TableName == a_tablename && p.BranchId == activeBranch!)?.LastSyncDate; DateTime? lastSync = m_context.Tblsyncinfos.FirstOrDefault(p => p.TableName == a_tablename && p.BranchId == activeBranch!)?.LastSyncDate;
if (lastSync != null) if (lastSync != null)
@ -207,10 +67,10 @@ namespace Cloud_Manager.Services
public void SetLastSyncDate(string a_tableName, DateTime a_timestamp) public void SetLastSyncDate(string a_tableName, DateTime a_timestamp)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string activeBranch = m_tokenService.GetBaseBranch(token)!; string activeBranch = m_tokenService.GetBaseBranch(apiKey)!;
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
{ {
m_context.Database.OpenConnection(); m_context.Database.OpenConnection();
@ -227,8 +87,8 @@ namespace Cloud_Manager.Services
public async Task SyncCancelledTransaction(List<Tblcancelledtransaction> a_item) public async Task SyncCancelledTransaction(List<Tblcancelledtransaction> a_item)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_item); string jsonString = JsonSerializer.Serialize(a_item);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -244,8 +104,8 @@ namespace Cloud_Manager.Services
public async Task SyncCreditPurchase(List<Creditpurchase> a_item) public async Task SyncCreditPurchase(List<Creditpurchase> a_item)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_item); string jsonString = JsonSerializer.Serialize(a_item);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -261,8 +121,8 @@ namespace Cloud_Manager.Services
public async Task SyncCustomerAccount(List<Customeraccount> a_customerAccounts) public async Task SyncCustomerAccount(List<Customeraccount> a_customerAccounts)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_customerAccounts); string jsonString = JsonSerializer.Serialize(a_customerAccounts);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -278,8 +138,8 @@ namespace Cloud_Manager.Services
public async Task SyncCustomerPurchase(List<Tblcustomerpurchase> a_customerPurchase) public async Task SyncCustomerPurchase(List<Tblcustomerpurchase> a_customerPurchase)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_customerPurchase); string jsonString = JsonSerializer.Serialize(a_customerPurchase);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -295,8 +155,8 @@ namespace Cloud_Manager.Services
public async Task SyncDiscountLogs(List<Tbldiscountlog> a_discountLog) public async Task SyncDiscountLogs(List<Tbldiscountlog> a_discountLog)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_discountLog); string jsonString = JsonSerializer.Serialize(a_discountLog);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -312,8 +172,8 @@ namespace Cloud_Manager.Services
public async Task SyncDeliveryDetails(List<Tbldeliverydetail> a_details) public async Task SyncDeliveryDetails(List<Tbldeliverydetail> a_details)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_details); string jsonString = JsonSerializer.Serialize(a_details);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -329,8 +189,8 @@ namespace Cloud_Manager.Services
public async Task SyncDeliveryHead(List<Tbldeliveryhead> a_heads) public async Task SyncDeliveryHead(List<Tbldeliveryhead> a_heads)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_heads); string jsonString = JsonSerializer.Serialize(a_heads);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -346,8 +206,8 @@ namespace Cloud_Manager.Services
public async Task SyncDeliveryRecipients(List<Tbldeliveryrecipient> a_recipients) public async Task SyncDeliveryRecipients(List<Tbldeliveryrecipient> a_recipients)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_recipients); string jsonString = JsonSerializer.Serialize(a_recipients);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -363,8 +223,8 @@ namespace Cloud_Manager.Services
public async Task SyncInvoice(List<Tblinvoice> a_invoice) public async Task SyncInvoice(List<Tblinvoice> a_invoice)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_invoice); string jsonString = JsonSerializer.Serialize(a_invoice);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())
@ -377,5 +237,42 @@ namespace Cloud_Manager.Services
} }
} }
} }
#region NotImplemented
public Task FetchRecentTransaction(int a_limit)
{
throw new NotImplementedException();
}
public Task FetchTransaction(DateTime a_start, DateTime a_end)
{
throw new NotImplementedException();
}
public IEnumerable<SaleItem> GetTransactions(DateTime a_start, DateTime a_end)
{
throw new NotImplementedException();
}
public IEnumerable<SaleItem> GetRecentTransaction()
{
throw new NotImplementedException();
}
public Task FetchReceipt(string a_receiptId)
{
throw new NotImplementedException();
}
public IEnumerable<SaleItem> GetReceipt(string a_receiptId)
{
throw new NotImplementedException();
}
public Task<IEnumerable<Tblcart>> GetReceiptDetail(string a_receiptId)
{
throw new NotImplementedException();
}
#endregion
} }
} }

18
Cloud_Manager/Services/UserService.cs

@ -12,10 +12,10 @@ namespace Cloud_Manager.Services
public class UserService : IUser public class UserService : IUser
{ {
private readonly BiskAcdbContext m_context; private readonly BiskAcdbContext m_context;
private readonly ITokenService m_tokenService; private readonly IKeyService m_tokenService;
private readonly HttpContext m_httpContext; private readonly HttpContext m_httpContext;
public UserService(BiskAcdbContext a_context, ITokenService a_tokenService, IHttpContextAccessor a_httpContextAccessor) public UserService(BiskAcdbContext a_context, IKeyService a_tokenService, IHttpContextAccessor a_httpContextAccessor)
{ {
m_context = a_context; m_context = a_context;
m_tokenService = a_tokenService; m_tokenService = a_tokenService;
@ -23,15 +23,7 @@ namespace Cloud_Manager.Services
} }
public IEnumerable<Tbluser> FetchUsers() public IEnumerable<Tbluser> FetchUsers()
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; throw new NotImplementedException();
if (AuthEnums.Valid == m_tokenService.ValidateToken(token))
{
IEnumerable<string> accessiblebranches = m_tokenService.BranchIds(token);
return m_context.Tblusers.Where(b => accessiblebranches.Contains(b.BranchId));
}
return new List<Tbluser>();
} }
public Task<IEnumerable<Tbluser>> GetUsers() public Task<IEnumerable<Tbluser>> GetUsers()
@ -41,8 +33,8 @@ namespace Cloud_Manager.Services
public async Task SyncUserAsync(List<Tbluser> a_users) public async Task SyncUserAsync(List<Tbluser> a_users)
{ {
string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!;
if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey))
{ {
string jsonString = JsonSerializer.Serialize(a_users); string jsonString = JsonSerializer.Serialize(a_users);
using (var command = m_context.Database.GetDbConnection().CreateCommand()) using (var command = m_context.Database.GetDbConnection().CreateCommand())

Loading…
Cancel
Save