From b64ab7fc96838eb669f0fd62d973003880bef16f Mon Sep 17 00:00:00 2001 From: barhen-pfw Date: Wed, 20 Dec 2023 17:59:12 -0500 Subject: [PATCH 1/2] Initial Commit --- Cloud_Manager/BiskAcdbContext.cs | 10 +- Cloud_Manager/BiskilogContext.cs | 23 ++ .../ClientContractModels/Clientapikey.cs | 15 ++ .../Models/Interfaces/IKeyService.cs | 31 +++ .../Models/Interfaces/ITokenService.cs | 18 -- .../Models/ServiceRepo/TokenService.cs | 183 +------------- Cloud_Manager/Program.cs | 12 +- .../Services/AuthenticationService.cs | 58 +---- Cloud_Manager/Services/CompanyService.cs | 48 ++-- Cloud_Manager/Services/CustomerService.cs | 47 +--- Cloud_Manager/Services/ProductRepo.cs | 155 +++--------- Cloud_Manager/Services/SalesService.cs | 233 +++++------------- Cloud_Manager/Services/UserService.cs | 18 +- 13 files changed, 225 insertions(+), 626 deletions(-) create mode 100644 Cloud_Manager/Models/ClientContractModels/Clientapikey.cs create mode 100644 Cloud_Manager/Models/Interfaces/IKeyService.cs delete mode 100644 Cloud_Manager/Models/Interfaces/ITokenService.cs diff --git a/Cloud_Manager/BiskAcdbContext.cs b/Cloud_Manager/BiskAcdbContext.cs index dc812cf..a8265c4 100644 --- a/Cloud_Manager/BiskAcdbContext.cs +++ b/Cloud_Manager/BiskAcdbContext.cs @@ -11,11 +11,11 @@ public partial class BiskAcdbContext : DbContext { private readonly HttpContext m_httpContext; private readonly IConnectionService m_connection; - private readonly ITokenService m_tokenService; + private readonly IKeyService m_tokenService; public BiskAcdbContext() { } - public BiskAcdbContext(DbContextOptions options, ITokenService tokenService, IConnectionService connection, IHttpContextAccessor a_httpContextAccessor = null) + public BiskAcdbContext(DbContextOptions options, IKeyService tokenService, IConnectionService connection, IHttpContextAccessor a_httpContextAccessor = null) : base(options) { m_tokenService = tokenService; @@ -27,10 +27,10 @@ public partial class BiskAcdbContext : DbContext { if (!optionsBuilder.IsConfigured) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (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); optionsBuilder.UseMySql(connectionString, new MariaDbServerVersion(new Version())); } diff --git a/Cloud_Manager/BiskilogContext.cs b/Cloud_Manager/BiskilogContext.cs index 28d7a91..5df82b0 100644 --- a/Cloud_Manager/BiskilogContext.cs +++ b/Cloud_Manager/BiskilogContext.cs @@ -30,6 +30,7 @@ public partial class BiskilogContext : DbContext public virtual DbSet Siteaccesspermissions { get; set; } public virtual DbSet Userauths { get; set; } + public virtual DbSet Clientapikeys { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -162,7 +163,29 @@ public partial class BiskilogContext : DbContext .HasColumnType("datetime") .HasColumnName("start_date"); }); + modelBuilder.Entity(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(entity => { entity.HasKey(e => e.DbNo).HasName("PRIMARY"); diff --git a/Cloud_Manager/Models/ClientContractModels/Clientapikey.cs b/Cloud_Manager/Models/ClientContractModels/Clientapikey.cs new file mode 100644 index 0000000..c1cc957 --- /dev/null +++ b/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; } +} diff --git a/Cloud_Manager/Models/Interfaces/IKeyService.cs b/Cloud_Manager/Models/Interfaces/IKeyService.cs new file mode 100644 index 0000000..5ac7a51 --- /dev/null +++ b/Cloud_Manager/Models/Interfaces/IKeyService.cs @@ -0,0 +1,31 @@ +using Cloud_Manager.Models.ClientContractModels; +using Cloud_Manager.Models.Enums; + +namespace Cloud_Manager.Models.Interfaces +{ + public interface IKeyService + { + /// + /// Validates specified API + /// + /// AuthEnums.Valid if key is a valid and unexpired token + AuthEnums ValidateKey(string a_Key); + + /// + /// Generates an API Key based on the specified client + /// + /// A tokenized string + string GenerateKey(Contract a_clientContract, Databasemap a_database); + /// + ///Returns the API if valid to return the related database id + /// + /// + int? GetDatabaseIdFromKey(string a_Key); + /// + /// Gets the branch associated with the specified API if valid + /// + /// + /// + string GetBaseBranch(string a_Key); + } +} diff --git a/Cloud_Manager/Models/Interfaces/ITokenService.cs b/Cloud_Manager/Models/Interfaces/ITokenService.cs deleted file mode 100644 index c8c9c2d..0000000 --- a/Cloud_Manager/Models/Interfaces/ITokenService.cs +++ /dev/null @@ -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 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 BranchIds(string a_token); - string? GetAllBranch(string a_token); - } -} diff --git a/Cloud_Manager/Models/ServiceRepo/TokenService.cs b/Cloud_Manager/Models/ServiceRepo/TokenService.cs index 8eef96b..74524ff 100644 --- a/Cloud_Manager/Models/ServiceRepo/TokenService.cs +++ b/Cloud_Manager/Models/ServiceRepo/TokenService.cs @@ -9,191 +9,34 @@ using System.Text; namespace Cloud_Manager.Models.ServiceRepo { - public class TokenService : ITokenService + public class TokenService : IKeyService { private IConfiguration m_configuration { get; } - public TokenService(IConfiguration a_configuration) + private BiskilogContext m_context; + public TokenService(IConfiguration a_configuration,BiskilogContext a_context) { m_configuration = a_configuration; + m_context = a_context; } - /// - /// Validates a user access token - /// - /// AuthEnums.Valid if token is a valid and unexpired token - public AuthEnums ValidateToken(string a_token) + public AuthEnums ValidateKey(string a_Key) { - try - { - string token = a_token.Substring(6).Trim(); - var handler = new JwtSecurityTokenHandler(); - 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; - } + throw new NotImplementedException(); } - /// - /// Generates an access token based on the user - /// - /// A tokenized string - public string GenerateToken(Userauth a_user, Contract a_clientContract, Databasemap a_database, List a_business, bool a_comparison) - { - try - { - //create claims details based on the user information - 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"]!)); - - var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); - var token = new JwtSecurityToken(m_configuration["Jwt:Issuer"], m_configuration["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddDays(14), signingCredentials: signIn); - return $"{new JwtSecurityTokenHandler().WriteToken(token)}"; - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - return AuthEnums.Error.ToString(); - } - } - /// - ///Deserializes the token string if valid to return the specified user role id in the token string - /// - /// - /// RoleId - public int? GetDatabaseIdFromToken(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 int.Parse(jwtToken.Claims.First(claim => claim.Type == "DbId").Value); - } - return null; - } - /// - ///Deserializes the token string if valid to return the specified user id in the token string - /// - /// - /// UserId - public int? GetUserIdFromToken(string a_token) + public string GenerateKey(Contract a_clientContract, Databasemap a_database) { - if (ValidateToken(a_token) == AuthEnums.Valid) - { - string token = a_token.Substring(6).Trim(); - var handler = new JwtSecurityTokenHandler(); - JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token); - return int.Parse(jwtToken.Claims.First(claim => claim.Type == "UserId").Value); - } - return null; - } - /// - ///Deserializes the token string if valid to return the specified username in the token string - /// - /// - /// Username - public string? GetUserNameFromToken(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 == "Username").Value; - } - return null; - } - /// - ///Deserializes the token string if valid to return the specified branchId in the token string - /// - /// - /// Username - public string? GetBaseBranch(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 == "BranchId").Value; - } - return null; + throw new NotImplementedException(); } - public bool? GetComparison(string a_token) + public int? GetDatabaseIdFromKey(string a_Key) { - if (ValidateToken(a_token) == AuthEnums.Valid) - { - string token = a_token.Substring(6).Trim(); - var handler = new JwtSecurityTokenHandler(); - JwtSecurityToken jwtToken = (JwtSecurityToken)handler.ReadToken(token); - return bool.Parse(jwtToken.Claims.First(claim => claim.Type == "ComparisonMode").Value); - } - return null; + throw new NotImplementedException(); } - /// - ///Deserializes the token string if valid to return the specified list of branches a user has access to in the token string - /// - /// - /// Username - 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; - } - /// - /// 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 IEnumerable BranchIds(string a_token) + + public string GetBaseBranch(string a_Key) { - List branchIds = new List(); - if (ValidateToken(a_token) == AuthEnums.Valid) - { - bool comparison = GetComparison(a_token)!.Value; - if (comparison) - { - string? branches = GetAllBranch(a_token); - if (branches != null) - { - string[] branchArray = branches!.Split(); - branchIds.AddRange(branchArray); - } - } - else - { - string? baseBranch = GetBaseBranch(a_token); - branchIds.Add(baseBranch!); - } - } - return branchIds.AsEnumerable(); + throw new NotImplementedException(); } } } diff --git a/Cloud_Manager/Program.cs b/Cloud_Manager/Program.cs index 6b8e15c..f1b085a 100644 --- a/Cloud_Manager/Program.cs +++ b/Cloud_Manager/Program.cs @@ -23,7 +23,7 @@ builder.Services.AddSingleton(); builder.Services.AddDbContext(); builder.Services.AddScoped(); builder.Services.AddScoped(); -builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); @@ -35,14 +35,6 @@ builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); -builder.Services.AddCors(options => -{ - options.AddPolicy("CorsPolicy", - builder => builder.AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader() - ); -}); var app = builder.Build(); app.UseSwagger(); @@ -50,7 +42,7 @@ app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SecureSwagg app.UseHttpsRedirection(); -app.UseCors("CorsPolicy"); + app.UseAuthentication(); app.UseAuthorization(); diff --git a/Cloud_Manager/Services/AuthenticationService.cs b/Cloud_Manager/Services/AuthenticationService.cs index 2591a9c..ee4342a 100644 --- a/Cloud_Manager/Services/AuthenticationService.cs +++ b/Cloud_Manager/Services/AuthenticationService.cs @@ -9,9 +9,9 @@ namespace Cloud_Manager.Services public class AuthenticationService : IAuthService { 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_tokenService = a_tokenService; @@ -32,36 +32,10 @@ namespace Cloud_Manager.Services return AuthEnums.NotFound; } } - /// - /// Autenticates a user and returns a tokenized string - /// - /// - /// - /// strings - public async Task AuthenticateClient(string a_username, string a_password) + public Task AuthenticateClient(string a_username, string a_password) { - var user = await GetUserAsync(a_username, a_password); - - if (user == null) - { - return null; - } - user.LastLogin = DateTime.Now; - m_context.Userauths.Update(user); - m_context.SaveChanges(); - - - Databasemap databasemap = GetClientDB(user.ClientId); - - List businessIds = GetSiteaccesspermission(user.ClientId, user.UserId).Select(t => t.BusinessId).ToList(); - Contract? contract = GetContract(user.ClientId, businessIds); - List 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); + throw new NotImplementedException(); } /// @@ -118,29 +92,5 @@ namespace Cloud_Manager.Services { return m_context.Siteaccesspermissions.Where(t => t.ClientId == a_clientId && t.UserId == a_userId).ToList(); } - - private async Task 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; - //} - } } } diff --git a/Cloud_Manager/Services/CompanyService.cs b/Cloud_Manager/Services/CompanyService.cs index 13cc9fe..8be4312 100644 --- a/Cloud_Manager/Services/CompanyService.cs +++ b/Cloud_Manager/Services/CompanyService.cs @@ -12,12 +12,12 @@ namespace Cloud_Manager.Services public class CompanyService : ICompanyInfo { private readonly BiskAcdbContext m_context; - private readonly ITokenService m_tokenService; + private readonly IKeyService m_tokenService; private readonly HttpContext m_httpContext; private Tblcompanydetail m_companyInfo { get; set; } private IEnumerable 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_tokenService = a_tokenService; @@ -56,8 +56,8 @@ namespace Cloud_Manager.Services } public async Task SyncBranches(List a_items) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_items); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -72,10 +72,10 @@ namespace Cloud_Manager.Services } public DateTime GetLastSyncDate(string a_tablename) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + 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; if (lastSync != null) @@ -88,10 +88,10 @@ namespace Cloud_Manager.Services public void SetLastSyncDate(string a_tableName, DateTime a_timestamp) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + 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()) { m_context.Database.OpenConnection(); @@ -108,8 +108,8 @@ namespace Cloud_Manager.Services public async Task SyncSystemRoles(List a_roles) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_roles); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -124,8 +124,8 @@ namespace Cloud_Manager.Services } public async Task SyncCompanyDetails(List a_details) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_details); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -141,8 +141,8 @@ namespace Cloud_Manager.Services public async Task SyncDriverDetails(List a_details) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_details); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -158,8 +158,8 @@ namespace Cloud_Manager.Services public async Task SyncTrucks(List a_trucks) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_trucks); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -175,8 +175,8 @@ namespace Cloud_Manager.Services public async Task SyncTruckAssignments(List a_assignments) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_assignments); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -192,8 +192,8 @@ namespace Cloud_Manager.Services public async Task SyncTruckMappings(List a_mapping) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_mapping); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -209,8 +209,8 @@ namespace Cloud_Manager.Services public async Task SyncTruckInventory(List a_inventories) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_inventories); using (var command = m_context.Database.GetDbConnection().CreateCommand()) diff --git a/Cloud_Manager/Services/CustomerService.cs b/Cloud_Manager/Services/CustomerService.cs index aac20cb..25038d7 100644 --- a/Cloud_Manager/Services/CustomerService.cs +++ b/Cloud_Manager/Services/CustomerService.cs @@ -13,10 +13,10 @@ namespace Cloud_Manager.Services public class CustomerService : ICustomer { private readonly BiskAcdbContext m_context; - private readonly ITokenService m_tokenService; + private readonly IKeyService m_tokenService; 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_tokenService = a_tokenService; @@ -24,44 +24,7 @@ namespace Cloud_Manager.Services } public IEnumerable FetchCustomers() { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) - { - IEnumerable 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) - }; - } - } - } - } + throw new NotImplementedException(); } public Task> GetCustomers() @@ -71,8 +34,8 @@ namespace Cloud_Manager.Services public async Task SyncCustomers(List a_details) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_details); using (var command = m_context.Database.GetDbConnection().CreateCommand()) diff --git a/Cloud_Manager/Services/ProductRepo.cs b/Cloud_Manager/Services/ProductRepo.cs index 52161a8..abccec6 100644 --- a/Cloud_Manager/Services/ProductRepo.cs +++ b/Cloud_Manager/Services/ProductRepo.cs @@ -15,7 +15,7 @@ namespace Cloud_Manager.Services public class ProductRepo : IProduct { private readonly BiskAcdbContext m_context; - private readonly ITokenService m_tokenService; + private readonly IKeyService m_tokenService; private readonly HttpContext m_httpContext; public event EventHandler ProductsChanged; @@ -23,7 +23,7 @@ namespace Cloud_Manager.Services public event EventHandler BrandsChanged; 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_tokenService = a_tokenService; @@ -35,124 +35,35 @@ namespace Cloud_Manager.Services /// public IEnumerable GetProducts(string a_productKey = "") { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) - { - IEnumerable 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 pUnits = new List(); - - 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) - }; - } - } - } - } + throw new NotImplementedException(); } private List GetAltUnits(DbDataReader a_reader) { - List pUnits = new List(); - for (int i = 1; i < 5; i++) - { - if (!a_reader.IsDBNull(a_reader.GetOrdinal($"AltUnit{i}"))) - { - pUnits.Add(new ProductUnits - { - UnitCode = a_reader.GetFieldValue($"AltUnit{i}"), - QuantityUnit = a_reader.GetFieldValue($"AltUnit{i}QTY"), - PriceUnit = a_reader.GetFieldValue($"AltUnit{i}Price"), - DistinctiveCode = a_reader.GetFieldValue($"AltUnit{i}distinctiveCode") - }); - } - else - { - return pUnits; - } - } - return pUnits; + throw new NotImplementedException(); } public IEnumerable GetUnitofmeasures() { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) - { - IEnumerable accessiblebranches = m_tokenService.BranchIds(token); - - return m_context.Unitofmeasures.Where(b => accessiblebranches.Contains(b.BranchId)); - } - return new List(); + throw new NotImplementedException(); } public IEnumerable GetBrands(string a_brandKey = "") { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) - { - IEnumerable accessiblebranches = m_tokenService.BranchIds(token); - - return m_context.Tblbrands.Where(b => accessiblebranches.Contains(b.BranchId)); - } - return new List(); + throw new NotImplementedException(); } public IEnumerable GetCategories(string a_categoryKey = "") { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) - { - IEnumerable accessiblebranches = m_tokenService.BranchIds(token); - - return m_context.Tblcategories.Where(b => accessiblebranches.Contains(b.BranchId)); - } - return new List(); + throw new NotImplementedException(); } public async Task SyncProducts(List a_item) { try { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_item); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -173,8 +84,8 @@ namespace Cloud_Manager.Services public async Task SyncInventory(List a_item) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_item); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -190,8 +101,8 @@ namespace Cloud_Manager.Services public async Task SyncInventoryEntries(List a_item) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_item); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -207,8 +118,8 @@ namespace Cloud_Manager.Services public async Task SyncPriceChanges(List a_items) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_items); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -224,8 +135,8 @@ namespace Cloud_Manager.Services public async Task SyncProductAltUnit(List a_items) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_items); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -241,8 +152,8 @@ namespace Cloud_Manager.Services public async Task SyncRestockAsync(List a_items) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_items); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -258,8 +169,8 @@ namespace Cloud_Manager.Services public async Task SyncUnitOfMeasureAsync(List a_items) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_items); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -275,8 +186,8 @@ namespace Cloud_Manager.Services public async Task SyncStockAsync(List a_items) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_items); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -292,8 +203,8 @@ namespace Cloud_Manager.Services public async Task SyncBrandsAsync(List a_items) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_items); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -309,8 +220,8 @@ namespace Cloud_Manager.Services public async Task SyncCategoriesAsync(List a_items) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_items); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -325,10 +236,10 @@ namespace Cloud_Manager.Services } public DateTime GetLastSyncDate(string a_tablename) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + 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; if (lastSync != null) @@ -341,10 +252,10 @@ namespace Cloud_Manager.Services public void SetLastSyncDate(string a_tableName, DateTime a_timestamp) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + 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()) { m_context.Database.OpenConnection(); diff --git a/Cloud_Manager/Services/SalesService.cs b/Cloud_Manager/Services/SalesService.cs index 922caf2..4766770 100644 --- a/Cloud_Manager/Services/SalesService.cs +++ b/Cloud_Manager/Services/SalesService.cs @@ -14,7 +14,7 @@ namespace Cloud_Manager.Services public class SalesService : ISalesInterface { private readonly BiskAcdbContext m_context; - private readonly ITokenService m_tokenService; + private readonly IKeyService m_tokenService; private readonly HttpContext m_httpContext; private readonly IHubContext m_salesHub; @@ -22,7 +22,7 @@ namespace Cloud_Manager.Services public event EventHandler FetchComplete; public event EventHandler FetchStart; - public SalesService(BiskAcdbContext a_context, ITokenService a_tokenService, + public SalesService(BiskAcdbContext a_context, IKeyService a_tokenService, IHttpContextAccessor a_httpContextAccessor, IHubContext a_salesHub) { m_context = a_context; @@ -31,151 +31,11 @@ namespace Cloud_Manager.Services m_salesHub = a_salesHub; } - public Task FetchRecentTransaction(int a_limit) - { - throw new NotImplementedException(); - } - - public IEnumerable GetRecentTransaction() - { - throw new NotImplementedException(); - } - - public IEnumerable GetTransactions(DateTime a_start, DateTime a_end) - { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) - { - IEnumerable 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 GetReceipt(string a_receiptId) - { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) - { - IEnumerable 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> GetReceiptDetail(string a_receiptId) - { - List details = new List(); - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) - { - IEnumerable 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 a_item) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_item); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -191,10 +51,10 @@ namespace Cloud_Manager.Services public DateTime GetLastSyncDate(string a_tablename) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + 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; if (lastSync != null) @@ -207,10 +67,10 @@ namespace Cloud_Manager.Services public void SetLastSyncDate(string a_tableName, DateTime a_timestamp) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + 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()) { m_context.Database.OpenConnection(); @@ -227,8 +87,8 @@ namespace Cloud_Manager.Services public async Task SyncCancelledTransaction(List a_item) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_item); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -244,8 +104,8 @@ namespace Cloud_Manager.Services public async Task SyncCreditPurchase(List a_item) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_item); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -261,8 +121,8 @@ namespace Cloud_Manager.Services public async Task SyncCustomerAccount(List a_customerAccounts) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_customerAccounts); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -278,8 +138,8 @@ namespace Cloud_Manager.Services public async Task SyncCustomerPurchase(List a_customerPurchase) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_customerPurchase); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -295,8 +155,8 @@ namespace Cloud_Manager.Services public async Task SyncDiscountLogs(List a_discountLog) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_discountLog); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -312,8 +172,8 @@ namespace Cloud_Manager.Services public async Task SyncDeliveryDetails(List a_details) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_details); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -329,8 +189,8 @@ namespace Cloud_Manager.Services public async Task SyncDeliveryHead(List a_heads) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_heads); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -346,8 +206,8 @@ namespace Cloud_Manager.Services public async Task SyncDeliveryRecipients(List a_recipients) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_recipients); using (var command = m_context.Database.GetDbConnection().CreateCommand()) @@ -363,8 +223,8 @@ namespace Cloud_Manager.Services public async Task SyncInvoice(List a_invoice) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_invoice); 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 GetTransactions(DateTime a_start, DateTime a_end) + { + throw new NotImplementedException(); + } + + public IEnumerable GetRecentTransaction() + { + throw new NotImplementedException(); + } + + public Task FetchReceipt(string a_receiptId) + { + throw new NotImplementedException(); + } + + public IEnumerable GetReceipt(string a_receiptId) + { + throw new NotImplementedException(); + } + + public Task> GetReceiptDetail(string a_receiptId) + { + throw new NotImplementedException(); + } + #endregion } } diff --git a/Cloud_Manager/Services/UserService.cs b/Cloud_Manager/Services/UserService.cs index b120fe3..e238cab 100644 --- a/Cloud_Manager/Services/UserService.cs +++ b/Cloud_Manager/Services/UserService.cs @@ -12,10 +12,10 @@ namespace Cloud_Manager.Services public class UserService : IUser { private readonly BiskAcdbContext m_context; - private readonly ITokenService m_tokenService; + private readonly IKeyService m_tokenService; 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_tokenService = a_tokenService; @@ -23,15 +23,7 @@ namespace Cloud_Manager.Services } public IEnumerable FetchUsers() { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) - { - IEnumerable accessiblebranches = m_tokenService.BranchIds(token); - - return m_context.Tblusers.Where(b => accessiblebranches.Contains(b.BranchId)); - } - return new List(); + throw new NotImplementedException(); } public Task> GetUsers() @@ -41,8 +33,8 @@ namespace Cloud_Manager.Services public async Task SyncUserAsync(List a_users) { - string token = m_httpContext.Request.Headers[HeaderNames.Authorization]!; - if (AuthEnums.Valid == m_tokenService.ValidateToken(token)) + string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; + if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { string jsonString = JsonSerializer.Serialize(a_users); using (var command = m_context.Database.GetDbConnection().CreateCommand()) -- 2.25.1 From 54f13b6c5e00aed161fd01d859858015f98ec703 Mon Sep 17 00:00:00 2001 From: barhen-pfw Date: Wed, 20 Dec 2023 23:09:19 -0500 Subject: [PATCH 2/2] Added API authentication and implemented middleware validation --- Cloud_Manager/BiskAcdbContext.cs | 2 +- .../Controllers/KeyGeneratorController.cs | 32 +++++ .../SyncCompanyInfoController.cs | 24 ++-- .../SyncControllers/SyncProductsController.cs | 24 ++-- .../SyncControllers/SyncSalesController.cs | 24 ++-- .../Controllers/WeatherForecastController.cs | 33 ----- .../Middleware/KeyValidationMiddleware.cs | 43 ++++++ Cloud_Manager/Models/Enums/AuthEnums.cs | 1 + .../Models/Interfaces/IKeyService.cs | 5 +- .../Models/ServiceRepo/TokenService.cs | 135 +++++++++++++++++- Cloud_Manager/Program.cs | 9 +- 11 files changed, 251 insertions(+), 81 deletions(-) create mode 100644 Cloud_Manager/Controllers/KeyGeneratorController.cs delete mode 100644 Cloud_Manager/Controllers/WeatherForecastController.cs create mode 100644 Cloud_Manager/Middleware/KeyValidationMiddleware.cs diff --git a/Cloud_Manager/BiskAcdbContext.cs b/Cloud_Manager/BiskAcdbContext.cs index a8265c4..0f036a2 100644 --- a/Cloud_Manager/BiskAcdbContext.cs +++ b/Cloud_Manager/BiskAcdbContext.cs @@ -28,7 +28,7 @@ public partial class BiskAcdbContext : DbContext if (!optionsBuilder.IsConfigured) { string apiKey = m_httpContext.Request.Headers["BISK-API-KEY"]!; - if (AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) + if (!String.IsNullOrEmpty(apiKey) && AuthEnums.Valid == m_tokenService.ValidateKey(apiKey)) { int? databaseId = m_tokenService.GetDatabaseIdFromKey(apiKey); string connectionString = m_connection.GetClientConnectionString(databaseId!.Value); diff --git a/Cloud_Manager/Controllers/KeyGeneratorController.cs b/Cloud_Manager/Controllers/KeyGeneratorController.cs new file mode 100644 index 0000000..74ac9da --- /dev/null +++ b/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 GenerateKeyAsync(Contract a_contract) + { + if (await m_keyService.GenerateKey(a_contract)) + { + return Ok("Key generated"); + } + else + { + return BadRequest(); + } + } + } +} diff --git a/Cloud_Manager/Controllers/SyncControllers/SyncCompanyInfoController.cs b/Cloud_Manager/Controllers/SyncControllers/SyncCompanyInfoController.cs index 945a05b..f576451 100644 --- a/Cloud_Manager/Controllers/SyncControllers/SyncCompanyInfoController.cs +++ b/Cloud_Manager/Controllers/SyncControllers/SyncCompanyInfoController.cs @@ -24,14 +24,14 @@ namespace Cloud_Manager.Controllers.SyncControllers m_companyInfo = a_companyInfo; } // GET: api/ - [Authorize] + [HttpGet, Route("lastsyncdate/{a_tableName}")] public DateTime GetLastSyncDate(string a_tableName) { return m_salesService.GetLastSyncDate(a_tableName); } // Post: api/ - [Authorize] + [HttpPost, Route("setsyncdate")] 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 /// /// - [Authorize] + [HttpPost, Route("publish/SystemRoles")] public async Task SyncSyatemRolesAsync(List a_item) { @@ -53,7 +53,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TblDriver rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblDriver")] public async Task SyncDriversAsync(List a_item) { @@ -64,7 +64,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of CompanyDetails rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblcompanydetails")] public async Task SyncCompanyAsync(List a_item) { @@ -75,7 +75,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TblUsers rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblusers")] public async Task SyncUsersAsync(List a_item) { @@ -86,7 +86,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of Trucks rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tbltrucks")] public async Task SyncTrucksAsync(List a_item) { @@ -97,7 +97,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TblBranch rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblbranch")] public async Task SyncBranchAsync(List a_item) { @@ -108,7 +108,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TblCustomers rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblcustomers")] public async Task SyncCustomersAsync(List a_item) { @@ -119,7 +119,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TblTruck Inventory rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tbltruckinventory")] public async Task SyncTruckInventoryAsync(List a_item) { @@ -130,7 +130,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TblTruckAssignment rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblTruckAssignment")] public async Task SyncTruckAssignmentSync(List a_item) { @@ -141,7 +141,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TblDriverMapping rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tbldrivermappings")] public async Task SyncTruckDriverMappingSync(List a_item) { diff --git a/Cloud_Manager/Controllers/SyncControllers/SyncProductsController.cs b/Cloud_Manager/Controllers/SyncControllers/SyncProductsController.cs index 9deb571..23fe7c5 100644 --- a/Cloud_Manager/Controllers/SyncControllers/SyncProductsController.cs +++ b/Cloud_Manager/Controllers/SyncControllers/SyncProductsController.cs @@ -17,14 +17,14 @@ namespace Cloud_Manager.Controllers.SyncControllers m_productService = a_productService; } // GET: api/ - [Authorize] + [HttpGet, Route("lastsyncdate/{a_tableName}")] public DateTime GetLastSyncDate(string a_tableName) { return m_productService.GetLastSyncDate(a_tableName); } // Post: api/ - [Authorize] + [HttpPost, Route("setsyncdate")] 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 /// /// - [Authorize] + [HttpPost, Route("publish/tblProducts")] public async Task SyncProductsAsync(List a_item) { @@ -46,7 +46,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TblInventory rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblInventory")] public async Task SyncInventoryAsync(List a_item) { @@ -57,7 +57,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of Restock rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblRestock")] public async Task SyncRestockAsync(List a_item) { @@ -68,7 +68,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TblInventoryEntries rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblInventoryentry")] public async Task SyncInventoryEntriesAsync(List a_item) { @@ -79,7 +79,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of PriceChanges rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tlpricechanges")] public async Task SyncPriceChangesAsync(List a_item) { @@ -90,7 +90,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of ProductAltUnit rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblProductAltUnit")] public async Task SyncProductAltUnitAsync(List a_item) { @@ -101,7 +101,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TbStock rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblStock")] public async Task SyncStockAsync(List a_item) { @@ -112,7 +112,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TblBrands rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblbrands")] public async Task SyncBrandsAsync(List a_item) { @@ -123,7 +123,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TblCategory rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblCategories")] public async Task SyncCategoriesAsync(List a_item) { @@ -134,7 +134,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of UnitOfMeasure rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblunitofmeasure")] public async Task SyncUnitMeasureAsync(List a_item) { diff --git a/Cloud_Manager/Controllers/SyncControllers/SyncSalesController.cs b/Cloud_Manager/Controllers/SyncControllers/SyncSalesController.cs index 526a73e..20f6677 100644 --- a/Cloud_Manager/Controllers/SyncControllers/SyncSalesController.cs +++ b/Cloud_Manager/Controllers/SyncControllers/SyncSalesController.cs @@ -18,14 +18,14 @@ namespace Cloud_Manager.Controllers.SyncControllers m_salesService = a_salesService; } // GET: api/ - [Authorize] + [HttpGet, Route("lastsyncdate/{a_tableName}")] public DateTime GetLastSyncDate(string a_tableName) { return m_salesService.GetLastSyncDate(a_tableName); } // Post: api/ - [Authorize] + [HttpPost, Route("setsyncdate")] 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 /// /// - [Authorize] + [HttpPost, Route("publish/tblCart")] public async Task SyncSalesAsync(List a_item) { @@ -47,7 +47,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TblCancelledTransation rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblcancelledtransaction")] public async Task SyncCancelledTransactionAsync(List a_item) { @@ -58,7 +58,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of TblInvoice rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblinvoice")] public async Task SyncInvoiceAsync(List a_item) { @@ -69,7 +69,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of CreditPurchase rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblCreditpurchase")] public async Task SyncCreditPurchaseAsync(List a_item) { @@ -80,7 +80,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of Customer Account rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblCustomerAccount")] public async Task SyncCustomerAccountAsync(List a_item) { @@ -91,7 +91,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of Customer Purchase rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/CustomerPurchase")] public async Task SyncCustomerPurchaseAsync(List a_item) { @@ -102,7 +102,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of Discount logs rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/DiscountLogs")] public async Task SyncDiscountLogsAsync(List a_item) { @@ -113,7 +113,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of Delivery Head rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblDeliveryhead")] public async Task SyncDeliveryHeadAsync(List a_item) { @@ -124,7 +124,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of Delivery Details rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblDeliverydetails")] public async Task SyncDeliveryDetailsAsync(List a_item) { @@ -135,7 +135,7 @@ namespace Cloud_Manager.Controllers.SyncControllers /// Endpoint to publish a collection of Delivery Recipient rows to the cloud /// /// - [Authorize] + [HttpPost, Route("publish/tblDeliveryrecipient")] public async Task SyncDeliveryRecipientAsync(List a_item) { diff --git a/Cloud_Manager/Controllers/WeatherForecastController.cs b/Cloud_Manager/Controllers/WeatherForecastController.cs deleted file mode 100644 index e5b1097..0000000 --- a/Cloud_Manager/Controllers/WeatherForecastController.cs +++ /dev/null @@ -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 _logger; - - public WeatherForecastController(ILogger logger) - { - _logger = logger; - } - - [HttpGet(Name = "GetWeatherForecast")] - public IEnumerable 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(); - } - } -} \ No newline at end of file diff --git a/Cloud_Manager/Middleware/KeyValidationMiddleware.cs b/Cloud_Manager/Middleware/KeyValidationMiddleware.cs new file mode 100644 index 0000000..66b88e0 --- /dev/null +++ b/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(); + } + } +} diff --git a/Cloud_Manager/Models/Enums/AuthEnums.cs b/Cloud_Manager/Models/Enums/AuthEnums.cs index 574b761..e6338b3 100644 --- a/Cloud_Manager/Models/Enums/AuthEnums.cs +++ b/Cloud_Manager/Models/Enums/AuthEnums.cs @@ -9,6 +9,7 @@ Found, Expired, Invalid, + Inactive, Valid, Successful, Error diff --git a/Cloud_Manager/Models/Interfaces/IKeyService.cs b/Cloud_Manager/Models/Interfaces/IKeyService.cs index 5ac7a51..597e212 100644 --- a/Cloud_Manager/Models/Interfaces/IKeyService.cs +++ b/Cloud_Manager/Models/Interfaces/IKeyService.cs @@ -14,10 +14,9 @@ namespace Cloud_Manager.Models.Interfaces /// /// Generates an API Key based on the specified client /// - /// A tokenized string - string GenerateKey(Contract a_clientContract, Databasemap a_database); + Task GenerateKey(Contract a_clientContract); /// - ///Returns the API if valid to return the related database id + ///Returns the database Id if the API Key is valid to return the related database id /// /// int? GetDatabaseIdFromKey(string a_Key); diff --git a/Cloud_Manager/Models/ServiceRepo/TokenService.cs b/Cloud_Manager/Models/ServiceRepo/TokenService.cs index 74524ff..8279d85 100644 --- a/Cloud_Manager/Models/ServiceRepo/TokenService.cs +++ b/Cloud_Manager/Models/ServiceRepo/TokenService.cs @@ -1,8 +1,10 @@ using Cloud_Manager.Models.ClientContractModels; using Cloud_Manager.Models.Enums; using Cloud_Manager.Models.Interfaces; +using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; +using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; @@ -12,31 +14,152 @@ namespace Cloud_Manager.Models.ServiceRepo public class TokenService : IKeyService { private IConfiguration m_configuration { get; } + private readonly Random m_random; private BiskilogContext m_context; - public TokenService(IConfiguration a_configuration,BiskilogContext a_context) + public TokenService(IConfiguration a_configuration, BiskilogContext a_context) { m_configuration = a_configuration; m_context = a_context; + m_random = new Random(); } public AuthEnums ValidateKey(string a_Key) { - throw new NotImplementedException(); + if (!string.IsNullOrEmpty(a_Key)) + { + Clientapikey? keyInfo = m_context.Clientapikeys.FirstOrDefault(k => k.Key == a_Key); + if (keyInfo != null) + { + if (keyInfo.IsActive == 0) + { + //Key is not active + return AuthEnums.Inactive; + } + + if (TryDecodeKey(a_Key, out int businessId)) + { + 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) + { + contract = m_context.Contracts.FirstOrDefault(c => c.ContractId == keyInfo.ContractId && c.BusinessId == businessId); + + //If contract start date is not past the key should inactive + if (contract?.StartDate > DateTime.Now) + { + return AuthEnums.Inactive; + } + + //Anyother reason contract is expired + return AuthEnums.Expired; + } + + //Key is valid and contract not expired + return AuthEnums.Valid; + } + } + else + { + return AuthEnums.NotFound; + } + } + + return AuthEnums.Invalid; } - public string GenerateKey(Contract a_clientContract, Databasemap a_database) + public async Task GenerateKey(Contract a_clientContract) { - throw new NotImplementedException(); + 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++) + { + key.Append(chars[m_random.Next(chars.Length)]); + } + + Clientapikey clientapikey = new Clientapikey(); + clientapikey.Key = key.ToString(); + clientapikey.ContractId = a_clientContract.ContractId; + + m_context.Clientapikeys.Add(clientapikey); + + if (await m_context.SaveChangesAsync() > 0) + { + return true; + } + else + { + return false; + } } public int? GetDatabaseIdFromKey(string a_Key) { - throw new NotImplementedException(); + if (ValidateKey(a_Key) == AuthEnums.Valid) + { + if (TryDecodeKey(a_Key, out int businessId)) + { + Clientapikey? keyInfo = m_context.Clientapikeys.FirstOrDefault(k => k.Key == a_Key); + Contract? contract = m_context.Contracts.FirstOrDefault(c => c.ContractId == keyInfo.ContractId && c.BusinessId == businessId && c.StartDate <= DateTime.Now && c.EndDate > DateTime.Now); + + Databasemap? databaseMap = m_context.Databasemaps.FirstOrDefault(c => c.ClientId == contract.ClientId); + + return databaseMap?.DbNo; + } + } + return null; } public string GetBaseBranch(string a_Key) { - throw new NotImplementedException(); + if (ValidateKey(a_Key) == AuthEnums.Valid) + { + if (TryDecodeKey(a_Key, out int businessId)) + { + Clientapikey? keyInfo = m_context.Clientapikeys.FirstOrDefault(k => k.Key == a_Key); + 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) + { + Clientbusiness? clientbusiness = m_context.Clientbusinesses.FirstOrDefault(cb => cb.ClientId == contract.ClientId && cb.BusinessId == businessId); + if (clientbusiness != null) + { + return clientbusiness.BusinessExternalId; + } + } + } + } + return String.Empty; + } + public static bool TryDecodeKey(string a_key, out int o_businessId) + { + char delimiter = '@'; + 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")) + { + // Find the index of the delimiter + 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) + { + // Attempt to parse the embedded integer value + if (int.TryParse(a_key.Substring(2, delimiterIndex - 2), out o_businessId)) + { + return true; // Successfully decoded + } + } + } + + return false; // Failed to decode } } } diff --git a/Cloud_Manager/Program.cs b/Cloud_Manager/Program.cs index f1b085a..4d97138 100644 --- a/Cloud_Manager/Program.cs +++ b/Cloud_Manager/Program.cs @@ -7,6 +7,10 @@ using Cloud_Manager.Models.Interfaces; using Cloud_Manager; using Cloud_Manager.Services; 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); @@ -35,16 +39,17 @@ builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); + + var app = builder.Build(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SecureSwagger v1")); app.UseHttpsRedirection(); - +app.UseKeyValidation(); app.UseAuthentication(); -app.UseAuthorization(); app.MapControllers(); -- 2.25.1