Skip to content

Commit

Permalink
Code Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobsen9026 committed Sep 20, 2024
1 parent 472050c commit 7eeb89d
Show file tree
Hide file tree
Showing 180 changed files with 793 additions and 773 deletions.
4 changes: 2 additions & 2 deletions BLAZAM.Tests/FileSystem/FileSystemBaseTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public void Writable_ReturnsTrue_WhenFileHasWritePermission()
// string path = Path.GetTempFileName();
// var fileSystemBase = new FileSystemBase("C:\\Windows\\setuperr.log");



// // Act
// bool writable = fileSystemBase.Writable;
Expand All @@ -91,7 +91,7 @@ public void Writable_ReturnsTrue_WhenDirHasWritePermission()
// Arrange
string path = Path.GetTempFileName();
var fileSystemBase = new FileSystemBase(System.IO.Path.GetDirectoryName(path));


// Act
bool writable = fileSystemBase.Writable;
Expand Down
4 changes: 2 additions & 2 deletions BLAZAM.Tests/Jobs/JobTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public void Steps_Cancelled_After_Error_When_Stop_Enabled()
var result = testJob.Run();

// Assert
Assert.True(testJob.Steps[1].Result == JobResult.Failed && testJob.Steps[2].Result==JobResult.Cancelled && testJob.Steps[3].Result== JobResult.Cancelled);
Assert.True(testJob.Steps[1].Result == JobResult.Failed && testJob.Steps[2].Result == JobResult.Cancelled && testJob.Steps[3].Result == JobResult.Cancelled);
}
[Fact]
public void Nested_Job_Runs()
Expand Down Expand Up @@ -94,7 +94,7 @@ public void Job_Elapsed_Time_Functional()
&& testJob.EndTime != DateTime.MinValue
&& testJob.ElapsedTime.HasValue
&& testJob.ElapsedTime.Value.TotalMilliseconds > 500
) ;
);
}

}
Expand Down
4 changes: 2 additions & 2 deletions BLAZAM.Tests/Mocks/Mock_UpdateService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ internal class Mock_UpdateService : UpdateService
ApplicationRoot = new SystemDirectory("C:\\temp"),
RunningProcess = Process.GetCurrentProcess(),
RunningVersion = new ApplicationVersion("0.0.1"),
TempDirectory = new SystemDirectory("C:\\temp")
},null)
TempDirectory = new SystemDirectory("C:\\temp")
}, null)
{

SelectedBranch = ApplicationReleaseBranches.Stable;
Expand Down
2 changes: 1 addition & 1 deletion BLAZAM.Tests/Updates/UpdateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace BLAZAM.Tests.Updates
{
public class UpdateTests
{
readonly Mock_UpdateService _updateService = new();
private readonly Mock_UpdateService _updateService = new();
//[Fact]
//public async void Update_Returns_Data()
//{
Expand Down
12 changes: 6 additions & 6 deletions BLAZAM.Tests/Updates/VersionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,20 @@ namespace BLAZAM.Tests.Updates
{
public class VersionTests
{
ApplicationVersion basicLow = new ApplicationVersion("0.5.1");
ApplicationVersion basicHigh = new ApplicationVersion("0.5.2");
ApplicationVersion longLow = new ApplicationVersion("0.5.1.2023.2.2.1053");
ApplicationVersion longHigh = new ApplicationVersion("0.5.2.2023.2.3.1053");
private ApplicationVersion basicLow = new ApplicationVersion("0.5.1");
private ApplicationVersion basicHigh = new ApplicationVersion("0.5.2");
private ApplicationVersion longLow = new ApplicationVersion("0.5.1.2023.2.2.1053");
private ApplicationVersion longHigh = new ApplicationVersion("0.5.2.2023.2.3.1053");

[Fact]
public void Basic_Comparison_Valid()
{
Assert.True(basicLow.CompareTo(basicHigh)<0);
Assert.True(basicLow.CompareTo(basicHigh) < 0);
}
[Fact]
public void Long_Comparison_Returns_LessThanZero_When_Older()
{
Assert.True(longLow.CompareTo(longHigh)< 0);
Assert.True(longLow.CompareTo(longHigh) < 0);
}
[Fact]
public void Long_Basic_Comparison_Returns_LessThanZero_When_Other_Is_Older()
Expand Down
2 changes: 1 addition & 1 deletion BLAZAM/BLAZAM.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<ServerGarbageCollection>false</ServerGarbageCollection>
<AssemblyVersion>1.0.2</AssemblyVersion>
<Version>2024.09.20.1621</Version>
<Version>2024.09.20.1710</Version>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<RootNamespace>BLAZAM</RootNamespace>
<GenerateDocumentationFile>False</GenerateDocumentationFile>
Expand Down
4 changes: 2 additions & 2 deletions BLAZAM/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
global using BLAZAM.Logger;
global using BLAZAM.FileSystem;
global using BLAZAM.FileSystem;
global using BLAZAM.Helpers;
global using BLAZAM.Logger;
global using BLAZAM.Services.Background;


13 changes: 7 additions & 6 deletions BLAZAM/Middleware/ApplicationStatusRedirectMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ internal class ApplicationStatusRedirectMiddleware
{
private readonly RequestDelegate _next;
private readonly ConnMonitor _monitor;
private readonly List<string> _uriIgnoreList = new List<string> { "/static","/css", "/_content","/_blazor","/BLAZAM.styles.css","/_framework" };
private readonly List<string> _uriIgnoreList = new List<string> { "/static", "/css", "/_content", "/_blazor", "/BLAZAM.styles.css", "/_framework" };
private string intendedUri;

public ApplicationStatusRedirectMiddleware(
Expand All @@ -36,7 +36,7 @@ public async Task InvokeAsync(HttpContext context, IAppDatabaseFactory factory)
break;
case ServiceConnectionState.Up:
var dbcontext = factory.CreateDbContext();
if(dbcontext.SeedMismatch)
if (dbcontext.SeedMismatch)
{
Oops.ErrorMessage = "The application database is incompatible with this version of the application";
Oops.DetailsMessage = "The database seed is different from the current version of the application";
Expand All @@ -46,15 +46,15 @@ public async Task InvokeAsync(HttpContext context, IAppDatabaseFactory factory)
}
if (!ApplicationInfo.installationCompleted)
{
SendTo(context,"/install");
SendTo(context, "/install");
}
break;
case ServiceConnectionState.Down:
SendTo(context, "/oops");

break;
}


}
catch
Expand All @@ -70,12 +70,13 @@ public async Task InvokeAsync(HttpContext context, IAppDatabaseFactory factory)
private void SendTo(HttpContext context, string uri)
{
if (intendedUri != uri)
context.Response.Redirect(uri);
context.Response.Redirect(uri);
}

private bool InIgnoreList(string intendedUri)
{
foreach(var uri in _uriIgnoreList) {
foreach (var uri in _uriIgnoreList)
{
if (intendedUri.StartsWith(uri)) return true;
}
return false;
Expand Down
18 changes: 9 additions & 9 deletions BLAZAM/Pages/API/Auth/KeepAlive.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,18 @@ public IActionResult OnGet()
{

var response = new Dictionary<string, string>();
if (HttpContext.User.Identity?.IsAuthenticated==true)
HttpContext.SlideCookieExpiration(ApplicationUserStateService.Instance.GetUserState(HttpContext.User));
else
{
response.Add("expired", "true");
return new JsonResult(response);
}
response.Add("expired", "false");
if (HttpContext.User.Identity?.IsAuthenticated == true)
HttpContext.SlideCookieExpiration(ApplicationUserStateService.Instance.GetUserState(HttpContext.User));
else
{
response.Add("expired", "true");
return new JsonResult(response);
}
response.Add("expired", "false");
return new JsonResult(response);

//return new OkResult();

}

}
Expand Down
8 changes: 4 additions & 4 deletions BLAZAM/Pages/API/Token.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ public class TokenModel : PageModel
{
public JwtSecurityTokenHandler JwtTokenHandler { get; private set; }
public string Token { get; private set; }
public IDatabaseContext Context { get; private set; }
public IDatabaseContext Context { get; private set; }



public TokenModel(IDatabaseContext context)
{
Context = context;
Expand All @@ -38,11 +38,11 @@ public JsonResult OnGet()
var token = new JwtSecurityToken("ExampleServer", "ExampleClients", claims, expires: DateTime.Now.AddSeconds(60), signingCredentials: credentials);
Token = JwtTokenHandler.WriteToken(token);
var userSettings = Context.UserSettings.Where(u => u.UserGUID == this.User.Identity.Name).FirstOrDefault();
if(userSettings != null)
if (userSettings != null)
{
userSettings.APIToken = Token;
}

Context.SaveChanges();
return new JsonResult(userSettings);
}
Expand Down
16 changes: 8 additions & 8 deletions BLAZAM/Pages/Download/Logs.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,19 @@ public class LogsModel : PageModel
{
public IActionResult OnGet()
{
var inMemZip = GenerateZip();
return File(inMemZip.ToArray(),"application/zip");
var inMemZip = GenerateZip();
return File(inMemZip.ToArray(), "application/zip");
}

MemoryStream GenerateZip()
private MemoryStream GenerateZip()
{
MemoryStream memoryStream = new MemoryStream();
ZipArchive zip = new ZipArchive(memoryStream, ZipArchiveMode.Create);
// Recursively add files and subdirectories to the zip archive
//TODO make zip file
// zip.AddToZip(new SystemDirectory(LogPath),LogPath);
ZipArchive zip = new ZipArchive(memoryStream, ZipArchiveMode.Create);
// Recursively add files and subdirectories to the zip archive
//TODO make zip file
// zip.AddToZip(new SystemDirectory(LogPath),LogPath);

return memoryStream;
}
}
}
}
2 changes: 1 addition & 1 deletion BLAZAM/Pages/Error/Error.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public void OnGet()
DetailsMessage = exception.InnerException?.Message;
}
}

}
}
}
19 changes: 10 additions & 9 deletions BLAZAM/Pages/MFACallback.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ AuditLogger logger

public string AuthResponse { get; private set; }

public async Task<IActionResult> OnGet(string? state=null,string? code=null)
public async Task<IActionResult> OnGet(string? state = null, string? code = null)
{
// Duo should have sent a 'state' and 'code' parameter. If either is missing or blank, something is wrong.
if (string.IsNullOrWhiteSpace(state))
Expand All @@ -49,7 +49,7 @@ public async Task<IActionResult> OnGet(string? state=null,string? code=null)
{
throw new DuoException("Required code value was empty");
}
if(User!=null && User.HasClaim(c=>c.Type == ClaimTypes.Rsa))
if (User != null && User.HasClaim(c => c.Type == ClaimTypes.Rsa))
{
if (state == User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Rsa)?.Value)
{
Expand All @@ -64,7 +64,7 @@ public async Task<IActionResult> OnGet(string? state=null,string? code=null)
// Get the Duo client again. This can be either be cached in the session or newly built.
// The only stateful information in the Client is your configuration, so you could even use the same client for multiple
// user authentications if desired.
Client duoClient = _duoClientProvider.GetDuoClient(Request.Scheme+"://"+Request.Host+"/mfacallback");
Client duoClient = _duoClientProvider.GetDuoClient(Request.Scheme + "://" + Request.Host + "/mfacallback");
var username = user.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.WindowsAccountName)?.Value;
// Get a summary of the authentication from Duo. This will trigger an exception if the username does not match.
try
Expand All @@ -77,19 +77,20 @@ public async Task<IActionResult> OnGet(string? state=null,string? code=null)
await _audit.Logon.Login(user.User, HttpContext.Connection.RemoteIpAddress?.ToString());
return new RedirectResult("/");
}
}catch
}
catch
{

return new RedirectResult("/");
}





}






}
else
{
Expand Down
20 changes: 10 additions & 10 deletions BLAZAM/Pages/SSO.cshtml.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
using BLAZAM.Common.Data;
using BLAZAM.Services;
using BLAZAM.Gui.UI.Dashboard.Widgets;
using BLAZAM.Helpers;
using BLAZAM.Server.Data.Services;
using BLAZAM.Services;
using BLAZAM.Services.Audit;
using BLAZAM.Services.Background;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using BLAZAM.Helpers;
using BLAZAM.Gui.UI.Dashboard.Widgets;
using BLAZAM.Services.Audit;

namespace BLAZAM.Server.Pages
{
[IgnoreAntiforgeryToken]
public class SSOModel : PageModel
{
public SSOModel(AppAuthenticationStateProvider auth, NavigationManager _nav,ConnMonitor _monitor,AuditLogger logger)
public SSOModel(AppAuthenticationStateProvider auth, NavigationManager _nav, ConnMonitor _monitor, AuditLogger logger)
{
Auth = auth;
Nav = _nav;
Expand All @@ -30,7 +30,7 @@ public SSOModel(AppAuthenticationStateProvider auth, NavigationManager _nav,Conn
public ConnMonitor Monitor { get; private set; }
public AuditLogger AuditLogger { get; private set; }

public IActionResult OnGet(string returnUrl="")
public IActionResult OnGet(string returnUrl = "")
{
ViewData["Layout"] = "_Layout";
if (returnUrl.IsUrlLocalToHost())
Expand All @@ -47,7 +47,7 @@ public IActionResult OnGet(string returnUrl="")
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public async Task<IActionResult> OnPost([FromFormAttribute]LoginRequest req)
public async Task<IActionResult> OnPost([FromFormAttribute] LoginRequest req)
{
try
{
Expand All @@ -57,15 +57,15 @@ public async Task<IActionResult> OnPost([FromFormAttribute]LoginRequest req)
await HttpContext.SignInAsync(result.AuthenticationState.User);
await AuditLogger.Logon.Login(result.AuthenticationState.User);
}
// return new ObjectResult(result.Status);
// return new ObjectResult(result.Status);

}
catch
catch
{

//return new ObjectResult(ex.Message);
}
if (req.ReturnUrl!=null && req.ReturnUrl.IsUrlLocalToHost())
if (req.ReturnUrl != null && req.ReturnUrl.IsUrlLocalToHost())
{
return Redirect(req.ReturnUrl);
}
Expand Down
8 changes: 4 additions & 4 deletions BLAZAM/Pages/SignIn.cshtml.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
using BLAZAM.Common.Data;
using BLAZAM.Services;
using BLAZAM.Gui.UI.Dashboard.Widgets;
using BLAZAM.Helpers;
using BLAZAM.Server.Data.Services;
using BLAZAM.Services;
using BLAZAM.Services.Audit;
using BLAZAM.Services.Background;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using BLAZAM.Helpers;
using BLAZAM.Gui.UI.Dashboard.Widgets;
using BLAZAM.Services.Audit;

namespace BLAZAM.Server.Pages
{
Expand Down
2 changes: 1 addition & 1 deletion BLAZAM/Pages/Static.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public async Task<IActionResult> OnGet()
return NotFound();
});



}

Expand Down
Loading

0 comments on commit 7eeb89d

Please sign in to comment.