Skip to content

Commit

Permalink
feat: todo suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
GjozinskiBodan committed Nov 29, 2023
1 parent 7e9796c commit 57146ac
Show file tree
Hide file tree
Showing 19 changed files with 257 additions and 70 deletions.
8 changes: 2 additions & 6 deletions Dal/ApplicationSettingsDa.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,11 @@
using Microsoft.Extensions.Logging;
using Models;
using Models.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Services.Interfaces.Repositories;

namespace Dal
{
public class ApplicationSettingsDa
public class ApplicationSettingsDa : IApplicationSettingsDa
{
private readonly ApplicationDbContext _db;
private static ILogger<ApplicationSettingsDa> _logger;
Expand Down
9 changes: 5 additions & 4 deletions Dal/ApplicationStorage/ApplicationDbContextFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<Applicati
/// <returns></returns>
public ApplicationDbContext CreateDbContext(string[] args)
{

var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseNpgsql("Host=localhost;Port=5434;Database=WasteDetection;Username=postgres;Password=3103;Pooling=true",
db => db.UseNetTopologySuite());

//optionsBuilder.UseNpgsql("Host=localhost;Port=5434;Database=WasteDetection;Username=postgres;Password=3103;Pooling=true",
// db => db.UseNetTopologySuite());
optionsBuilder.UseNpgsql("Host=localhost;Port=5434;Database=waste_detection;Username=postgres;Password=admin;Pooling=true;",
db => db.UseNetTopologySuite()
);

return new ApplicationDbContext(optionsBuilder.Options, null);
}
Expand Down
24 changes: 16 additions & 8 deletions Dal/AuditLogsDa.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,29 +24,33 @@ public async Task<ICollection<AuditLog>> GetAll()
{
try
{
return await _db.AuditLog.OrderByDescending(x => x.AuditDate).
AsNoTracking().
ToListAsync();
return await _db.AuditLog.OrderByDescending(x => x.AuditDate)
.AsNoTracking()
.ToListAsync();
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
throw ex;
}
}

// TODO: Change to Nullable ? if first or default
public async Task<AuditLog> GetAuditData(int auditLogId)
{
try
{
return await _db.AuditLog.Where(z => z.AuditLogId == auditLogId).
FirstOrDefaultAsync();
return await _db.AuditLog.Where(z => z.AuditLogId == auditLogId)
.FirstOrDefaultAsync();
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
throw ex;
}
}

// TODO: Test
public async Task<ICollection<AuditLog>> GetAllFromToDate(DateTime dateFrom, DateTime dateTo)
{
var query = _db.AuditLog.AsQueryable();
Expand All @@ -62,6 +66,8 @@ public async Task<ICollection<AuditLog>> GetAllFromToDate(DateTime dateFrom, Dat

return await query.AsNoTracking().ToListAsync();
}

// TODO: Test
public async Task<ICollection<AuditLog>> GetAllByUsernameFromToDate(string internalUsername, DateTime? dateFrom, DateTime? dateTo, string action, string type)
{
var query = _db.AuditLog.AsQueryable();
Expand All @@ -88,13 +94,15 @@ public async Task<ICollection<AuditLog>> GetAllByUsernameFromToDate(string inter
}
return await query.AsNoTracking().Take(5000).ToListAsync();
}

public async Task<List<string>> GetAuditActions()
{
try
{
return await _db.AuditLog.GroupBy(z => z.AuditAction).Select(z => z.Key).
AsNoTracking().
ToListAsync();
return await _db.AuditLog.GroupBy(z => z.AuditAction)
.Select(z => z.Key)
.AsNoTracking()
.ToListAsync();
}
catch (Exception ex)
{
Expand Down
24 changes: 15 additions & 9 deletions Dal/Helpers/ApplicationSettingsHelper.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Models;
using Services.Interfaces.Repositories;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
Expand All @@ -19,17 +20,21 @@ public ApplicationSettingsHelper(IApplicationSettingsDa applicationSettingsDa)
_cache = new ConcurrentDictionary<string, ApplicationSettings>();
}

// TODO: This should be private
public string GetApplicationSetting(string configurationName, string defaultValue = null)
{
// TODO: Needs try catch , if try catch here it can be removed from all following parametarized get methods
var appSetting =
_cache.GetOrAdd(configurationName,
i => _applicationSettingsDa.GetApplicationConfiguration(configurationName));

var appSetting = _cache.GetOrAdd(configurationName, i => _applicationSettingsDa.GetApplicationConfiguration(configurationName));
if (appSetting != null)
return appSetting.Value;

else if (appSetting == null && defaultValue != null)
if (appSetting == null && defaultValue != null)
return defaultValue;
else
throw new Exception("Application setings error: The settings for " + configurationName + " does not exist");

throw new Exception("Application setings error: The settings for " + configurationName + " does not exist");
}

public string GetApplicationSettingString(string configurationName, string defaultValue = null)
Expand All @@ -41,12 +46,14 @@ public string GetApplicationSettingString(string configurationName, string defau
}
catch (Exception e)
{
// TODO: Review -> Higher probablity of setting not found than invalid cast to string
throw new Exception("Application setings error: Invalid cast to string " + configurationName, e);
}
}

public int GetApplicationSettingInteger(string configurationName, string defaultValue = null)
{
// TODO: Review -> Higher probablity of setting not found than invalid cast to string, add try parse to know if not found or parse error
try
{
var value = GetApplicationSetting(configurationName, defaultValue);
Expand All @@ -60,6 +67,7 @@ public int GetApplicationSettingInteger(string configurationName, string default

public DateTime GetApplicationSettingDateTime(string configurationName, string defaultValue = null)
{
// TODO: Review -> Higher probablity of setting not found than invalid cast to string, add try parse to know if not found or parse error
try
{
var value = GetApplicationSetting(configurationName, defaultValue);
Expand All @@ -73,6 +81,7 @@ public DateTime GetApplicationSettingDateTime(string configurationName, string d

public decimal GetApplicationSettingDecimal(string configurationName, string defaultValue = null)
{
// TODO: Review -> Higher probablity of setting not found than invalid cast to string, add try parse to know if not found or parse error
try
{
var value = GetApplicationSetting(configurationName, defaultValue);
Expand All @@ -84,10 +93,9 @@ public decimal GetApplicationSettingDecimal(string configurationName, string def
}
}



public bool GetApplicationSettingBool(string configurationName, string defaultValue = null)
{
// TODO: Review -> Higher probablity of setting not found than invalid cast to string, add try parse to know if not found or parse error
try
{
var value = GetApplicationSetting(configurationName, defaultValue);
Expand All @@ -98,7 +106,5 @@ public bool GetApplicationSettingBool(string configurationName, string defaultVa
throw new Exception("Application setings error: Invalid cast to bool " + configurationName, e);
}
}


}
}
24 changes: 20 additions & 4 deletions Dal/IntranetPortalUsersTokenDa.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ public IntranetPortalUsersTokenDa(ApplicationDbContext db, ILogger<IntranetPorta
_db = db;
_logger = logger;
}

// TODO: Test
public async Task<Int32> CreateIntranetPortalUserToken(string token, string userId)
{
try
Expand Down Expand Up @@ -57,8 +59,6 @@ public async Task<Int32> UpdateAndHashUserPassword(ApplicationUser user, string
user.PasswordHash = passwordHashed.HashPassword(user, password);
_db.Users.Update(user);



return await _db.SaveChangesAsync();
}
catch (Exception ex)
Expand All @@ -68,6 +68,7 @@ public async Task<Int32> UpdateAndHashUserPassword(ApplicationUser user, string
}
}

// TODO: Test
public async Task<Int32> UpdateIsTokenUsedForUser(string token, string userId)
{
try
Expand All @@ -83,12 +84,15 @@ public async Task<Int32> UpdateIsTokenUsedForUser(string token, string userId)
throw ex;
}
}

// TODO: Change to Nullable
public async Task<ApplicationUser> GetUser(string userId)
{
try
{
return await _db.Users.Where(z => z.Id == userId).
FirstOrDefaultAsync();
return await _db.Users.Where(z => z.Id == userId)
.FirstOrDefaultAsync();
//return await _db.Users.SingleOrDefaultAsync(z => z.Id == userId);
}
catch (Exception ex)
{
Expand All @@ -109,6 +113,18 @@ public async Task<bool> IsTokenNotUsed(string token, string userId)
{
return false;
}

//var intranetPortalUsersToken =
// await _db.IntranetPortalUsersTokens
// .Where(x => x.Token == token
// && x.ApplicationUserId == userId
// && x.isTokenUsed == false)
// .FirstOrDefaultAsync();

//if (intranetPortalUsersToken != null)
// return true;

//return false;
}
catch (Exception ex)
{
Expand Down
1 change: 1 addition & 0 deletions MailSend/MailService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public bool SendMail(SendMailModelDTO sendMailModel)
}
catch (Exception ex)
{
// TODO: 🤔 Review to see if exception should be thrown 🤔🤔🤔
throw ex;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ public UserManagementController(UserManagementDa userManagementDa, ModulesAndAut

public async Task<IActionResult> Index()
{
// TODO: 🧹 Middleware Attribute -> AuthorizeClaim 🧹🧹🧹
/*
if (!User.HasAuthClaim(SD.AuthClaims.UserManagement) || !_modulesAndAuthClaimsHelper.HasModule(SD.Modules.UserManagement))
{
var errorPath = _configuration["ErrorViewsPath:Error403"];
Expand All @@ -44,11 +46,11 @@ public async Task<IActionResult> Index()
return StatusCode(403);
}
}

*/
UserManagementViewModel model = new UserManagementViewModel();
var users = await _userManagementDa.GetAllIntanetPortalUsers();
var roles = await _userManagementDa.GetRoles();
var userRoles = await _userManagementDa.GetUserRoles();
var userRoles = await _userManagementDa.GetUserRoles();
model.Users = users.Select(z => new UserManagementUserViewModel
{
FirstName = z.FirstName,
Expand All @@ -69,8 +71,11 @@ public async Task<IActionResult> Index()
return View(model);
}

[HttpGet]
public async Task<IActionResult> CreateUser()
{
// TODO: 🧹 Middleware Attribute -> AuthorizeClaim 🧹🧹🧹
/*
if (!User.HasAuthClaim(SD.AuthClaims.UserManagementAddUsersAndRoles) || !_modulesAndAuthClaimsHelper.HasModule(SD.Modules.UserManagement))
{
var errorPath = _configuration["ErrorViewsPath:Error403"];
Expand All @@ -83,21 +88,47 @@ public async Task<IActionResult> CreateUser()
return StatusCode(403);
}
}
UserManagementCreateUserViewModel model = new UserManagementCreateUserViewModel();
model.Roles = _userManagementDa.GetRoles().Result.ToList();
model.Claims = _modulesAndAuthClaimsHelper.GetAuthClaims().Result;
model.RoleClaims = _userManagementDa.GetAllRoleClaims().Result;
model.PasswordMinLength = _applicationSettingsHelper.GetApplicationSettingInteger("PasswordMinLength");
model.PasswordMustHaveLetters = _applicationSettingsHelper.GetApplicationSettingBool("PasswordMustHaveLetters");
model.PasswordMustHaveNumbers = _applicationSettingsHelper.GetApplicationSettingBool("PasswordMustHaveNumbers");
model.AllUsers = await _userManagementDa.GetAllIntanetPortalUsers();
*/

// TODO: 🧹 Create Seed for initial load 🧹🧹🧹
#region Get Pass App Settings
int passwordMinLength;
bool passwordMustHaveLetters;
bool passwordMustHaveNumbers;
try
{
passwordMinLength = _applicationSettingsHelper.GetApplicationSettingInteger("PasswordMinLength");
passwordMustHaveLetters = _applicationSettingsHelper.GetApplicationSettingBool("PasswordMustHaveLetters");
passwordMustHaveNumbers = _applicationSettingsHelper.GetApplicationSettingBool("PasswordMustHaveNumbers");
}
catch (Exception ex)
{
passwordMinLength = 3;
passwordMustHaveLetters = false;
passwordMustHaveNumbers = false;
}
#endregion

UserManagementCreateUserViewModel model = new UserManagementCreateUserViewModel()
{
Roles = _userManagementDa.GetRoles().Result.ToList(),
Claims = _modulesAndAuthClaimsHelper.GetAuthClaims().Result,
RoleClaims = _userManagementDa.GetAllRoleClaims().Result,
PasswordMinLength = passwordMinLength,
PasswordMustHaveLetters = passwordMustHaveLetters,
PasswordMustHaveNumbers = passwordMustHaveNumbers,
AllUsers = await _userManagementDa.GetAllIntanetPortalUsers()
};

return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateUser(UserManagementCreateUserViewModel user)
{
// TODO: 🧹 Middleware Attribute -> AuthorizeClaim 🧹🧹🧹
/*
if (!User.HasAuthClaim(SD.AuthClaims.UserManagementAddUsersAndRoles) || !_modulesAndAuthClaimsHelper.HasModule(SD.Modules.UserManagement))
{
var errorPath = _configuration["ErrorViewsPath:Error403"];
Expand All @@ -110,6 +141,8 @@ public async Task<IActionResult> CreateUser(UserManagementCreateUserViewModel us
return StatusCode(403);
}
}
*/
// TODO: ⚠️ !!! Password validation is only front end ⚠️⚠️⚠️
if (ModelState.IsValid)
{
user.UserName = user.UserName?.Trim();
Expand All @@ -128,7 +161,6 @@ public async Task<IActionResult> CreateUser(UserManagementCreateUserViewModel us
}
foreach (var claim in user.ClaimsInsert)
{

_userManagementDa.AddClaimForUser(u.Id, claim);
}
return RedirectToAction(nameof(Index));
Expand All @@ -143,7 +175,7 @@ public async Task<IActionResult> CreateUser(UserManagementCreateUserViewModel us
user.AllUsers = await _userManagementDa.GetAllIntanetPortalUsers();
return View(user);
}

public async Task<IActionResult> EditUser(string id)
{
if (id == null)
Expand Down Expand Up @@ -175,10 +207,10 @@ public async Task<IActionResult> EditUser(string id)
model.IsActive = user.IsActive;
model.PasswordMinLength = _applicationSettingsHelper.GetApplicationSettingInteger("PasswordMinLength");
model.PasswordMustHaveLetters = _applicationSettingsHelper.GetApplicationSettingBool("PasswordMustHaveLetters");
model.PasswordMustHaveNumbers = _applicationSettingsHelper.GetApplicationSettingBool("PasswordMustHaveNumbers");
model.PasswordMustHaveNumbers = _applicationSettingsHelper.GetApplicationSettingBool("PasswordMustHaveNumbers");
model.RolesInsert = roles.Where(z => userRole.Contains(z.Id)).Select(z => z.Id).ToList();
model.Roles = roles.ToList();
model.Claims = await _modulesAndAuthClaimsHelper.GetAuthClaims();
model.Claims = await _modulesAndAuthClaimsHelper.GetAuthClaims();
model.ClaimsInsert = claims.Select(z => z.ClaimValue).ToList();
model.AllUsersExceptCurrent = await _userManagementDa.GetAllIntanetPortalUsersExcludingCurrent(user.Id);

Expand Down
Loading

0 comments on commit 57146ac

Please sign in to comment.