From 8d747990990d44bc2e6b5391a02a922a4c26342d Mon Sep 17 00:00:00 2001 From: "DESKTOP-GENO133\\IvanPlex" Date: Sun, 14 Jan 2024 09:54:13 -0700 Subject: [PATCH] replaced IConfiguration injection with IConfigHelper --- Controllers/AdminController.cs | 9 +- Controllers/HomeController.cs | 2 +- Controllers/VehicleController.cs | 18 ++-- .../Implementations/UserConfigDataAccess.cs | 3 +- Helper/ConfigHelper.cs | 86 +++++++++++++------ Logic/LoginLogic.cs | 16 ++++ Middleware/Authen.cs | 8 +- Views/Home/Index.cshtml | 10 +-- Views/Vehicle/_CollisionRecords.cshtml | 7 +- Views/Vehicle/_Gas.cshtml | 11 +-- Views/Vehicle/_GasModal.cshtml | 7 +- Views/Vehicle/_ServiceRecords.cshtml | 7 +- Views/Vehicle/_TaxRecords.cshtml | 7 +- Views/Vehicle/_UpgradeRecords.cshtml | 7 +- Views/Vehicle/_VehicleHistory.cshtml | 9 +- wwwroot/js/garage.js | 1 + 16 files changed, 137 insertions(+), 71 deletions(-) diff --git a/Controllers/AdminController.cs b/Controllers/AdminController.cs index e41a530..2e7c29e 100644 --- a/Controllers/AdminController.cs +++ b/Controllers/AdminController.cs @@ -1,4 +1,5 @@ -using CarCareTracker.Logic; +using CarCareTracker.Helper; +using CarCareTracker.Logic; using CarCareTracker.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -12,10 +13,12 @@ namespace CarCareTracker.Controllers { private ILoginLogic _loginLogic; private IUserLogic _userLogic; - public AdminController(ILoginLogic loginLogic, IUserLogic userLogic) + private IConfigHelper _configHelper; + public AdminController(ILoginLogic loginLogic, IUserLogic userLogic, IConfigHelper configHelper) { _loginLogic = loginLogic; _userLogic = userLogic; + _configHelper = configHelper; } public IActionResult Index() { @@ -38,7 +41,7 @@ namespace CarCareTracker.Controllers } public IActionResult DeleteUser(int userId) { - var result =_userLogic.DeleteAllAccessToUser(userId) && _loginLogic.DeleteUser(userId); + var result =_userLogic.DeleteAllAccessToUser(userId) && _configHelper.DeleteUserConfig(userId) && _loginLogic.DeleteUser(userId); return Json(result); } } diff --git a/Controllers/HomeController.cs b/Controllers/HomeController.cs index e6b8f26..981177d 100644 --- a/Controllers/HomeController.cs +++ b/Controllers/HomeController.cs @@ -52,7 +52,7 @@ namespace CarCareTracker.Controllers [HttpPost] public IActionResult WriteToSettings(UserConfig userConfig) { - var result = _config.SaveUserConfig(User.IsInRole(nameof(UserData.IsRootUser)), GetUserID(), userConfig); + var result = _config.SaveUserConfig(User, userConfig); return Json(result); } public IActionResult Privacy() diff --git a/Controllers/VehicleController.cs b/Controllers/VehicleController.cs index 149fa0f..600c825 100644 --- a/Controllers/VehicleController.cs +++ b/Controllers/VehicleController.cs @@ -27,7 +27,7 @@ namespace CarCareTracker.Controllers private readonly IUpgradeRecordDataAccess _upgradeRecordDataAccess; private readonly IWebHostEnvironment _webEnv; private readonly bool _useDescending; - private readonly IConfiguration _config; + private readonly IConfigHelper _config; private readonly IFileHelper _fileHelper; private readonly IGasHelper _gasHelper; private readonly IReminderHelper _reminderHelper; @@ -49,7 +49,7 @@ namespace CarCareTracker.Controllers IUpgradeRecordDataAccess upgradeRecordDataAccess, IUserLogic userLogic, IWebHostEnvironment webEnv, - IConfiguration config) + IConfigHelper config) { _logger = logger; _dataAccess = dataAccess; @@ -67,7 +67,7 @@ namespace CarCareTracker.Controllers _userLogic = userLogic; _webEnv = webEnv; _config = config; - _useDescending = bool.Parse(config[nameof(UserConfig.UseDescending)]); + _useDescending = config.GetUserConfig(User).UseDescending; } private int GetUserID() { @@ -231,8 +231,8 @@ namespace CarCareTracker.Controllers var fileNameToExport = $"temp/{Guid.NewGuid()}.csv"; var fullExportFilePath = _fileHelper.GetFullFilePath(fileNameToExport, false); var vehicleRecords = _gasRecordDataAccess.GetGasRecordsByVehicleId(vehicleId); - bool useMPG = bool.Parse(_config[nameof(UserConfig.UseMPG)]); - bool useUKMPG = bool.Parse(_config[nameof(UserConfig.UseUKMPG)]); + bool useMPG = _config.GetUserConfig(User).UseMPG; + bool useUKMPG = _config.GetUserConfig(User).UseUKMPG; vehicleRecords = vehicleRecords.OrderBy(x => x.Date).ThenBy(x => x.Mileage).ToList(); var convertedRecords = _gasHelper.GetGasRecordViewModels(vehicleRecords, useMPG, useUKMPG); var exportData = convertedRecords.Select(x => new GasRecordExportModel { Date = x.Date.ToString(), Cost = x.Cost.ToString(), FuelConsumed = x.Gallons.ToString(), FuelEconomy = x.MilesPerGallon.ToString(), Odometer = x.Mileage.ToString() }); @@ -389,8 +389,8 @@ namespace CarCareTracker.Controllers //need it in ascending order to perform computation. result = result.OrderBy(x => x.Date).ThenBy(x => x.Mileage).ToList(); //check if the user uses MPG or Liters per 100km. - bool useMPG = bool.Parse(_config[nameof(UserConfig.UseMPG)]); - bool useUKMPG = bool.Parse(_config[nameof(UserConfig.UseUKMPG)]); + bool useMPG = _config.GetUserConfig(User).UseMPG; + bool useUKMPG = _config.GetUserConfig(User).UseUKMPG; var computedResults = _gasHelper.GetGasRecordViewModels(result, useMPG, useUKMPG); if (_useDescending) { @@ -753,8 +753,8 @@ namespace CarCareTracker.Controllers var upgradeRecords = _upgradeRecordDataAccess.GetUpgradeRecordsByVehicleId(vehicleId); var taxRecords = _taxRecordDataAccess.GetTaxRecordsByVehicleId(vehicleId); var gasRecords = _gasRecordDataAccess.GetGasRecordsByVehicleId(vehicleId); - bool useMPG = bool.Parse(_config[nameof(UserConfig.UseMPG)]); - bool useUKMPG = bool.Parse(_config[nameof(UserConfig.UseUKMPG)]); + bool useMPG = _config.GetUserConfig(User).UseMPG; + bool useUKMPG = _config.GetUserConfig(User).UseUKMPG; vehicleHistory.TotalGasCost = gasRecords.Sum(x => x.Cost); vehicleHistory.TotalCost = serviceRecords.Sum(x => x.Cost) + repairRecords.Sum(x => x.Cost) + upgradeRecords.Sum(x => x.Cost) + taxRecords.Sum(x => x.Cost); var averageMPG = 0.00M; diff --git a/External/Implementations/UserConfigDataAccess.cs b/External/Implementations/UserConfigDataAccess.cs index f2dc4b7..83003b7 100644 --- a/External/Implementations/UserConfigDataAccess.cs +++ b/External/Implementations/UserConfigDataAccess.cs @@ -23,7 +23,8 @@ namespace CarCareTracker.External.Implementations using (var db = new LiteDatabase(dbName)) { var table = db.GetCollection(tableName); - return table.Upsert(userConfigData); + table.Upsert(userConfigData); + return true; }; } public bool DeleteUserConfig(int userId) diff --git a/Helper/ConfigHelper.cs b/Helper/ConfigHelper.cs index ca26486..097430d 100644 --- a/Helper/ConfigHelper.cs +++ b/Helper/ConfigHelper.cs @@ -1,5 +1,6 @@ using CarCareTracker.External.Interfaces; using CarCareTracker.Models; +using Microsoft.Extensions.Caching.Memory; using System.Security.Claims; namespace CarCareTracker.Helper @@ -7,20 +8,31 @@ namespace CarCareTracker.Helper public interface IConfigHelper { UserConfig GetUserConfig(ClaimsPrincipal user); - bool SaveUserConfig(bool isRootUser, int userId, UserConfig configData); + bool SaveUserConfig(ClaimsPrincipal user, UserConfig configData); public bool DeleteUserConfig(int userId); } public class ConfigHelper : IConfigHelper { private readonly IConfiguration _config; private readonly IUserConfigDataAccess _userConfig; - public ConfigHelper(IConfiguration serverConfig, IUserConfigDataAccess userConfig) + private IMemoryCache _cache; + public ConfigHelper(IConfiguration serverConfig, + IUserConfigDataAccess userConfig, + IMemoryCache memoryCache) { _config = serverConfig; _userConfig = userConfig; + _cache = memoryCache; } - public bool SaveUserConfig(bool isRootUser, int userId, UserConfig configData) + public bool SaveUserConfig(ClaimsPrincipal user, UserConfig configData) { + var storedUserId = user.FindFirstValue(ClaimTypes.NameIdentifier); + int userId = 0; + if (storedUserId != null) + { + userId = int.Parse(storedUserId); + } + bool isRootUser = user.IsInRole(nameof(UserData.IsRootUser)); if (isRootUser) { try @@ -46,6 +58,7 @@ namespace CarCareTracker.Helper configData.UserPasswordHash = string.Empty; } File.WriteAllText(StaticHelper.UserConfigPath, System.Text.Json.JsonSerializer.Serialize(configData)); + _cache.Set($"userConfig_{userId}", configData); return true; } catch (Exception ex) @@ -60,46 +73,65 @@ namespace CarCareTracker.Helper UserConfig = configData }; var result = _userConfig.SaveUserConfig(userConfig); + _cache.Set($"userConfig_{userId}", configData); return result; } } public bool DeleteUserConfig(int userId) { + _cache.Remove($"userConfig_{userId}"); var result = _userConfig.DeleteUserConfig(userId); return result; } public UserConfig GetUserConfig(ClaimsPrincipal user) { - var serverConfig = new UserConfig + int userId = 0; + if (user != null) { - EnableCsvImports = bool.Parse(_config[nameof(UserConfig.EnableCsvImports)]), - UseDarkMode = bool.Parse(_config[nameof(UserConfig.UseDarkMode)]), - UseMPG = bool.Parse(_config[nameof(UserConfig.UseMPG)]), - UseDescending = bool.Parse(_config[nameof(UserConfig.UseDescending)]), - EnableAuth = bool.Parse(_config[nameof(UserConfig.EnableAuth)]), - HideZero = bool.Parse(_config[nameof(UserConfig.HideZero)]), - UseUKMPG = bool.Parse(_config[nameof(UserConfig.UseUKMPG)]) - }; - if (!user.Identity.IsAuthenticated) - { - return serverConfig; - } - bool isRootUser = user.IsInRole(nameof(UserData.IsRootUser)); - int userId = int.Parse(user.FindFirstValue(ClaimTypes.NameIdentifier)); - if (isRootUser) - { - return serverConfig; + var storedUserId = user.FindFirstValue(ClaimTypes.NameIdentifier); + if (storedUserId != null) + { + userId = int.Parse(storedUserId); + } } else { - var result = _userConfig.GetUserConfig(userId); - if (result == null) + return new UserConfig(); + } + return _cache.GetOrCreate($"userConfig_{userId}", entry => + { + entry.SlidingExpiration = TimeSpan.FromHours(1); + var serverConfig = new UserConfig + { + EnableCsvImports = bool.Parse(_config[nameof(UserConfig.EnableCsvImports)]), + UseDarkMode = bool.Parse(_config[nameof(UserConfig.UseDarkMode)]), + UseMPG = bool.Parse(_config[nameof(UserConfig.UseMPG)]), + UseDescending = bool.Parse(_config[nameof(UserConfig.UseDescending)]), + EnableAuth = bool.Parse(_config[nameof(UserConfig.EnableAuth)]), + HideZero = bool.Parse(_config[nameof(UserConfig.HideZero)]), + UseUKMPG = bool.Parse(_config[nameof(UserConfig.UseUKMPG)]) + }; + if (!user.Identity.IsAuthenticated) { return serverConfig; - } else - { - return result.UserConfig; } - } + bool isRootUser = user.IsInRole(nameof(UserData.IsRootUser)); + if (isRootUser) + { + return serverConfig; + } + else + { + var result = _userConfig.GetUserConfig(userId); + if (result == null) + { + return serverConfig; + } + else + { + return result.UserConfig; + } + } + }); } } } diff --git a/Logic/LoginLogic.cs b/Logic/LoginLogic.cs index 7d6363c..b709614 100644 --- a/Logic/LoginLogic.cs +++ b/Logic/LoginLogic.cs @@ -19,6 +19,7 @@ namespace CarCareTracker.Logic OperationResponse ResetPasswordByUser(LoginModel credentials); OperationResponse ResetUserPassword(LoginModel credentials); UserData ValidateUserCredentials(LoginModel credentials); + bool CheckIfUserIsValid(int userId); bool CreateRootUserCredentials(LoginModel credentials); bool DeleteRootUserCredentials(); List GetAllUsers(); @@ -36,6 +37,21 @@ namespace CarCareTracker.Logic _tokenData = tokenData; _mailHelper = mailHelper; } + public bool CheckIfUserIsValid(int userId) + { + if (userId == -1) + { + return true; + } + var result = _userData.GetUserRecordById(userId); + if (result == null) + { + return false; + } else + { + return result.Id != 0; + } + } //handles user registration public OperationResponse RegisterNewUser(LoginModel credentials) { diff --git a/Middleware/Authen.cs b/Middleware/Authen.cs index 975b395..5cfdd89 100644 --- a/Middleware/Authen.cs +++ b/Middleware/Authen.cs @@ -113,11 +113,17 @@ namespace CarCareTracker.Middleware } else { + if (!_loginLogic.CheckIfUserIsValid(authCookie.UserData.Id)) + { + return AuthenticateResult.Fail("Cookie points to non-existant user."); + } + //validate if user is still valid var appIdentity = new ClaimsIdentity("Custom"); var userIdentity = new List { new(ClaimTypes.Name, authCookie.UserData.UserName), - new(ClaimTypes.NameIdentifier, authCookie.UserData.Id.ToString()) + new(ClaimTypes.NameIdentifier, authCookie.UserData.Id.ToString()), + new(ClaimTypes.Role, "CookieAuth") }; if (authCookie.UserData.IsAdmin) { diff --git a/Views/Home/Index.cshtml b/Views/Home/Index.cshtml index 2dd47ce..5eddcea 100644 --- a/Views/Home/Index.cshtml +++ b/Views/Home/Index.cshtml @@ -1,6 +1,7 @@ -@inject IConfiguration Configuration +@using CarCareTracker.Helper +@inject IConfigHelper config @{ - var enableAuth = bool.Parse(Configuration[nameof(UserConfig.EnableAuth)]); + var enableAuth = config.GetUserConfig(User).EnableAuth; } @model string @{ @@ -17,7 +18,7 @@ - @if (enableAuth) + @if (User.IsInRole("CookieAuth")) { - @if (enableAuth) + @if (User.IsInRole("CookieAuth")) {