Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,14 @@ public async Task<OneOf<Success, string>> BackupServerAsync(Guid serverId)
{
return await api.PostAsync("/api/backups/PerformBackup", serverId);
}

public async Task<OneOf<AutoTestBackupConfigDto, string>> FetchAutoTestBackupConfig(Guid configurationId)
{
return await api.PostAsync<AutoTestBackupConfigDto, Guid>("/api/servers/FetchAutoTestConfig", configurationId);
}

public async Task<OneOf<Success, string>> EditAutoTestBackupConfig(AutoTestBackupConfigDto config)
{
return await api.PostAsync("/api/servers/EditAutoTestConfig", config);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
@using Client.UI.Data.Services
@using Modules.Backup.Shared.Dtos

@inject BackupsHttpClientService Service
@inject ISnackbar Snackbar

<MudDialog>
<DialogContent>
<MudCard Elevation="3" Class="pa-4 rounded-2xl mb-5">
<MudCardContent Class="d-flex flex-column align-center">
@if (_config is null)
{
<MudProgressCircular Indeterminate="true" Color="Color.Primary"/>
<MudText Align="Align.Center">Searching for specified server configuration...</MudText>
}
else
{
<MudGrid Justify="Justify.Center" Spacing="4">
<MudItem xs="12" Class="d-flex flex-column justify-center align-center">
<MudCheckBox T="bool" @bind-Value="_config.IsEnabled" Label="Enable Automatic Tests" LabelPlacement="Placement.End"/>
</MudItem>
</MudGrid>
}
</MudCardContent>
</MudCard>

<MudContainer Class="d-flex justify-between pa-4">
<MudButton OnClick="@Close" Variant="Variant.Text" Color="Color.Default" Disabled="@_isSaving">Close
</MudButton>
<MudButton OnClick="@Save" Variant="Variant.Filled" Color="Color.Success" Disabled="@_isSaving">
@if (_isSaving)
{
<MudProgressCircular Indeterminate="true" Color="Color.Primary"/>
}
else
{
<span>Save Config</span>
}
</MudButton>
</MudContainer>
</DialogContent>
</MudDialog>

@code {
[CascadingParameter] private IMudDialogInstance MudDialog { get; set; } = null!;
[Parameter] public Guid ConfigurationId { get; set; }

private AutoTestBackupConfigDto? _config;

private bool _isSaving;

protected override async Task OnInitializedAsync()
{
_isSaving = true;

var result = await Service.FetchAutoTestBackupConfig(ConfigurationId);

result.Switch(
config => _config = config,
error => Snackbar.Add(error, Severity.Error)
);

_isSaving = false;
}

private void Close()
=> MudDialog.Cancel();

private async Task Save()
{
_isSaving = true;

if (_config is null)
{
Snackbar.Add("Config can't be null", Severity.Error);

_isSaving = false;
return;
}

var result = await Service.EditAutoTestBackupConfig(_config);

result.Switch(
_ => Snackbar.Add("Successfully saved configuration", Severity.Success),
error => Snackbar.Add(error, Severity.Error)
);

_isSaving = false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@
<MudMenuItem Disabled="@_isProcessing" OnClick="@(() => PerformServerBackup(context.Id))">
Perform Backup
</MudMenuItem>
<MudMenuItem Disabled="@_isProcessing" OnClick="@(() => EditTestsConfig(context.AutoTestBackupsConfigId))">
Auto Tests Configuration
</MudMenuItem>
</ChildContent>
</MudMenu>
</MudTd>
Expand Down Expand Up @@ -236,4 +239,13 @@
_isProcessing = false;
}

private async Task EditTestsConfig(Guid autoTestConfigId)
{
var parameters = new DialogParameters<EditServerAutoTestConfigurationDialog>
{
{ x => x.ConfigurationId, autoTestConfigId }
};

await DialogService.ShowAsync<EditServerAutoTestConfigurationDialog>($"Server Tests Configuration", parameters);
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"NotifyServiceSettings": {
"Env": "Dev",
"Scheme": "{wsProtocol}",
"DevelopmentPort": "{url.port}",
"Scheme": "https",
"DevelopmentPort": "5000",
"ProductionHost": "production.example.com"
},
"Logging": {
Expand All @@ -22,7 +22,7 @@
"MainAdminEmailAddress": "admin@octo.com"
},
"AllowedHosts": "*",
"AllowedOrigins": "{wsProtocol}://{url.hostname}:{url.port}",
"AllowedOrigins": "https://localhost, https://localhost:5000, https://localhost:5001",
"https_port": 443,
"SeqConfiguration": {
"ApiKey": "",
Expand Down

This file was deleted.

19 changes: 0 additions & 19 deletions DbBackupService/Src/Bootstraper/Server/Server.Api/oldProgram.txt

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,22 @@ namespace Modules.Auth.Application.Services;
internal class TokenValidationService(IUserTokenService tokensRepoService, ILogger<TokenValidationService> logger)
: ITokenValidationService
{
// TODO: Add this to configurable section in admin's configuration panel
private readonly bool _enableTokenLogging = false;

public OneOf<True, False> IsValid(string? token, string? userEmail)
{
logger.LogInformation("Validating token {Token} for user {Email}...", token, userEmail);
if(_enableTokenLogging)
logger.LogInformation("Validating token {Token} for user {Email}...", token, userEmail);

if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(userEmail))
{
logger.LogInformation("Token or Email is empty.");
return new False();
}

logger.LogDebug("Searching DB with passed token...");
if(_enableTokenLogging)
logger.LogDebug("Searching DB with passed token...");
var userToken = tokensRepoService.GetUserTokens(t =>
t.Token == token &&
t.Email?.ToUpper() == userEmail.ToUpper()).FirstOrDefault();
Expand All @@ -42,7 +47,8 @@ public OneOf<True, False> IsValid(string? token, string? userEmail)
return new False();
}

logger.LogInformation("Token {Token} for user {Email} is Valid.", token, userEmail);
if(_enableTokenLogging)
logger.LogInformation("Token {Token} for user {Email} is Valid.", token, userEmail);
return new True();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ public static WebApplication MapServersEndpoints(this WebApplication app)

api.MapPost("TestServerConnection", ServersOperations.TestServerConnection)
.WithSummary("Test server connection and execute test query to check communication with DB");

api.MapPost("FetchAutoTestConfig", ServersOperations.GetAutoTestConfig)
.WithSummary("Get specified server's AutoTest configuration");

api.MapPost("EditAutoTestConfig", ServersOperations.EditAutoTestConfig)
.WithSummary("Edit provided server's AutoTest configuration");

return app;
}
Expand Down Expand Up @@ -179,4 +185,10 @@ public static async Task<IResult> TestServerConnection(
{
return await CallFuncAndReturnIResult(service.TestServerConnection, serverId);
}

public static async Task<IResult> GetAutoTestConfig(HttpContext context, [FromServices] ServersService service, [FromBody] Guid configurationId)
=> await CallFuncAndReturnIResult(service.GetAutoTestConfig, configurationId);

public static async Task<IResult> EditAutoTestConfig(HttpContext context, [FromServices] ServersService service, [FromBody] AutoTestBackupConfigDto config)
=> await CallFuncAndReturnIResult(service.EditAutoTestConfig, config);
}
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ await DeleteOldBackup.Delete(backupPath.DirectoryPath, serverConfig.TimeInDaysTo
Id = Guid.CreateVersion7(),
CreatedOn = DateTime.Now,
ServerConnectionId = db.GetServerId(),
Name = $"{serverConn.ServerHost}:{serverConn.ServerPort}_{serverConn.DbName}",
Name = $"{serverConn.ServerHost} -> {serverConn.ServerPort} -> {serverConn.DbName}",
FilePath = ""
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ public async Task<OneOf<List<ServerConnectionDto>, string>> GetServers(string? i
DbName = server.DbName,
DbType = server.DbType,
DbUser = server.DbUser,
IsTunnelRequired = server.IsTunnelRequired
IsTunnelRequired = server.IsTunnelRequired,
AutoTestBackupsConfigId = server.AutoTestBackupsConfigId
};

var dbTunnel = db.DbServerTunnels.FirstOrDefault(x => x.Id == server.TunnelId);
Expand Down Expand Up @@ -212,6 +213,16 @@ public async Task<OneOf<Success, string>> CreateServer(ServerConnectionDto newSe
IsDisabled = false
};

var serverAutoTestBackupConfig = new AutomaticBackupTestConfig
{
Id = Guid.CreateVersion7(),
// TODO: Change this to global setting that is configurable in admin's config panel
IsEnabled = false,
ServerId = dbServer.Id
};

dbServer.AutoTestBackupsConfigId = serverAutoTestBackupConfig.Id;

// 3. Obsługa tunelu (opcjonalna)
if (newServer.IsTunnelRequired)
{
Expand Down Expand Up @@ -243,7 +254,8 @@ public async Task<OneOf<Success, string>> CreateServer(ServerConnectionDto newSe

// 4. Zapis serwera
db.DbConnections.Add(dbServer);

db.AutomaticBackupTestConfigs.Add(serverAutoTestBackupConfig);

if (string.IsNullOrWhiteSpace(identityName))
return "Can't access username";

Expand Down Expand Up @@ -638,6 +650,9 @@ public async Task<OneOf<Success, string>> DeleteServer(Guid serverId)

var serverBackupConfig = db.Configurations.FirstOrDefault(x => x.ServerId == serverId);
if (serverBackupConfig is not null) db.Configurations.Remove(serverBackupConfig);

var serverAutoTestConfig = db.AutomaticBackupTestConfigs.FirstOrDefault(x => x.ServerId == serverId);
if (serverAutoTestConfig is not null) db.AutomaticBackupTestConfigs.Remove(serverAutoTestConfig);

var backups = db.Backups.Where(x => x.ServerConnectionId == server.Id);
if (backups.Any())
Expand All @@ -657,4 +672,35 @@ public async Task<OneOf<Success, string>> DeleteServer(Guid serverId)

return new Success();
}


public async Task<OneOf<AutoTestBackupConfigDto, string>> GetAutoTestConfig(Guid configId)
{
if (configId == Guid.Empty)
return "Invalid config id";

logger.LogInformation("Checking if config [{ConfigId}] exists...", configId);

var config = await db.AutomaticBackupTestConfigs.FindAsync(configId);
if (config is null)
return "Can't find config";

return new AutoTestBackupConfigDto
{
Id = config.Id,
IsEnabled = config.IsEnabled
};
}

public async Task<OneOf<Success, string>> EditAutoTestConfig(AutoTestBackupConfigDto config)
{
var dbConfig = await db.AutomaticBackupTestConfigs.FindAsync(config.Id);
if (dbConfig is null)
return "Can't find config";

dbConfig.IsEnabled = config.IsEnabled;
await db.SaveChangesAsync();

return new Success();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
logger.LogInformation("Running backup worker in 20 seconds...");
await Task.Delay(TimeSpan.FromSeconds(20), stoppingToken);

logger.LogInformation("Worker will run each 10 seconds from now...");
logger.LogInformation("Worker will run each {Interval} minutes from now...", _interval.Minutes);
while (await timer.WaitForNextTickAsync(stoppingToken))
try
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
public sealed record AutomaticBackupTestConfig
{
public Guid Id { get; init; }
public required string Name { get; set; }
public Guid ServerId { get; set; }
public bool IsEnabled { get; set; } = true;
public bool ShouldTestEveryBackup { get; set; } = true;
public short TestFrequency { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,7 @@ public sealed class ServerBackupsConfiguration
[NotMapped] private string BackupSaveDirectory { get; } = GetBackupDirectory();

private static string GetBackupDirectory()
{
if (OperatingSystem.IsWindows())
return Path.Combine(
Path.GetDirectoryName(Environment.ProcessPath)!,
"backups");

if (OperatingSystem.IsLinux())
return "/backups";

throw new PlatformNotSupportedException("Unsupported OS");
}

=> Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OctoBackup", "Backups");

/// <summary>
/// Create required directories for provided server and database
Expand Down
Loading