WIP: refactor

This commit is contained in:
Michał Zieliski
2024-06-18 19:40:16 +02:00
parent c2a98e0386
commit a0a228f86d
24 changed files with 1415 additions and 1654 deletions

View File

@@ -3,105 +3,105 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using WebAPI.Models;
using static Google.Apis.Drive.v3.FilesResource;
namespace WebAPI.Controllers
namespace WebAPI.Controllers;
[ApiController]
[Route("api/[controller]")]
public class AdminController : Controller
{
[ApiController]
[Route("api/[controller]")]
public class AdminController : Controller
{
private readonly GoogleDriveHelper _googleDriveHelper;
private readonly IConfiguration _configuration;
private readonly LogsController _logsController;
private readonly GoogleDriveHelper _googleDriveHelper;
private readonly IConfiguration _configuration;
private readonly LogsController _logsController;
public AdminController(
GoogleDriveHelper googleDriveHelper,
IConfiguration configuration,
LogsController logsController)
public AdminController(
GoogleDriveHelper googleDriveHelper,
IConfiguration configuration,
LogsController logsController)
{
_googleDriveHelper = googleDriveHelper;
_configuration = configuration;
_logsController = logsController;
}
[HttpGet]
[Route("BackupDatabase/{apiKey}")]
[AllowAnonymous]
public IActionResult BackupDatabase(string apiKey)
{
if (Request.Host.Value != _configuration["apiLocalUrl"] || apiKey != _configuration["apiKey"])
{
_googleDriveHelper = googleDriveHelper;
_configuration = configuration;
_logsController = logsController;
return Unauthorized();
}
[HttpGet]
[Route("BackupDatabase/{apiKey}")]
[AllowAnonymous]
public IActionResult BackupDatabase(string apiKey)
try
{
if (Request.Host.Value != _configuration["apiLocalUrl"] || apiKey != _configuration["apiKey"])
const string databaseName = "diunabi-morska";
var localDatabasePath = $"{_configuration["dbBackupFile"]}-{DateTime.UtcNow.Day}.bak";
const string formatMediaName = $"DatabaseToolkitBackup_{databaseName}";
const string formatName = $"Full Backup of {databaseName}";
var connection = new SqlConnection(_configuration.GetConnectionString("SQLDatabase"));
const string sql = """
BACKUP DATABASE @databaseName
TO DISK = @localDatabasePath
WITH FORMAT,
MEDIANAME = @formatMediaName,
NAME = @formatName
""";
connection.Open();
var command = new SqlCommand(sql, connection);
command.CommandType = CommandType.Text;
command.CommandTimeout = 7200;
command.Parameters.AddWithValue("@databaseName", databaseName);
command.Parameters.AddWithValue("@localDatabasePath", localDatabasePath);
command.Parameters.AddWithValue("@formatMediaName", formatMediaName);
command.Parameters.AddWithValue("@formatName", formatName);
command.ExecuteNonQuery();
var body = new Google.Apis.Drive.v3.Data.File
{
return Unauthorized();
Name = Path.GetFileName(localDatabasePath),
Parents = new List<string?> { _configuration["GDriveBackupDirectory"] },
MimeType = "application/octet-stream"
};
var fsSource = new FileStream(localDatabasePath, FileMode.Open, FileAccess.Read);
if (_googleDriveHelper.Service is null)
{
throw new Exception("Google Drive API not initialized");
}
try
{
var databaseName = "diunabi-morska";
var localDatabasePath = $"{_configuration["dbBackupFile"]}-{DateTime.UtcNow.Day}.bak";
var formatMediaName = $"DatabaseToolkitBackup_{databaseName}";
var formatName = $"Full Backup of {databaseName}";
var request = _googleDriveHelper.Service.Files.Create(body, fsSource, body.MimeType);
request.Fields = "id";
var connection = new SqlConnection(_configuration.GetConnectionString("SQLDatabase"));
var sql = @"BACKUP DATABASE @databaseName
TO DISK = @localDatabasePath
WITH FORMAT,
MEDIANAME = @formatMediaName,
NAME = @formatName";
connection.Open();
var command = new SqlCommand(sql, connection);
command.CommandType = CommandType.Text;
command.CommandTimeout = 7200;
command.Parameters.AddWithValue("@databaseName", databaseName);
command.Parameters.AddWithValue("@localDatabasePath", localDatabasePath);
command.Parameters.AddWithValue("@formatMediaName", formatMediaName);
command.Parameters.AddWithValue("@formatName", formatName);
command.ExecuteNonQuery();
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File
{
Name = Path.GetFileName(localDatabasePath),
Parents = new List<string?> { _configuration["GDriveBackupDirectory"] },
MimeType = "application/octet-stream"
};
var fsSource = new FileStream(localDatabasePath, FileMode.Open, FileAccess.Read);
if (_googleDriveHelper.Service is null)
{
throw new Exception("Google Drive API not initialized");
}
var request = _googleDriveHelper.Service.Files.Create(body, fsSource, body.MimeType);
request.Fields = "id";
request.Upload();
request.Upload();
_logsController.AddEntry(new LogEntry
{
Title = "Backup success",
Type = LogEntryType.info,
LogType = LogType.backup,
CreatedAt = DateTime.UtcNow
});
return Ok();
}
catch (Exception e)
_logsController.AddEntry(new LogEntry
{
_logsController.AddEntry(new LogEntry
{
Title = "Backup error",
Type = LogEntryType.error,
LogType = LogType.backup,
Message = e.ToString(),
CreatedAt = DateTime.UtcNow
});
return BadRequest(e.ToString());
}
Title = "Backup success",
Type = LogEntryType.info,
LogType = LogType.backup,
CreatedAt = DateTime.UtcNow
});
return Ok();
}
catch (Exception e)
{
_logsController.AddEntry(new LogEntry
{
Title = "Backup error",
Type = LogEntryType.error,
LogType = LogType.backup,
Message = e.ToString(),
CreatedAt = DateTime.UtcNow
});
return BadRequest(e.ToString());
}
}
}

View File

@@ -1,72 +1,58 @@
using Google.Apis.Auth;
using Google.Apis.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client.Platforms.Features.DesktopOs.Kerberos;
using Microsoft.IdentityModel.Tokens;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WebAPI.Models;
namespace WebAPI.Controllers
namespace WebAPI.Controllers;
[ApiController]
[Route("api/[controller]")]
// [Authorize]
public class AuthController : Controller
{
[ApiController]
[Route("api/[controller]")]
// [Authorize]
public class AuthController : Controller
private readonly AppDbContext _db;
private readonly IConfiguration _configuration;
public AuthController(
AppDbContext db, IConfiguration configuration)
{ _db = db; _configuration = configuration; }
[HttpPost]
[Route("apiToken")]
public async Task<IActionResult> ApiToken([FromBody] string credential)
{
private readonly AppDbContext db;
private readonly IConfiguration configuration;
public AuthController(
AppDbContext _db, IConfiguration _configuration)
{ db = _db; configuration = _configuration; }
[HttpPost]
[Route("apiToken")]
public async Task<IActionResult> apiToken([FromBody] string credential)
var settings = new GoogleJsonWebSignature.ValidationSettings
{
var settings = new GoogleJsonWebSignature.ValidationSettings()
{
Audience = new List<string> { configuration.GetValue<string>("GoogleClientId")! }
};
var payload = await GoogleJsonWebSignature.ValidateAsync(credential, settings);
var user = db.Users.Where(x => x.Email == payload.Email).FirstOrDefault();
if (user != null)
{
return Ok(JWTGenerator(user));
}
else
{
return Unauthorized();
}
}
Audience = new List<string> { _configuration.GetValue<string>("GoogleClientId")! }
};
var payload = await GoogleJsonWebSignature.ValidateAsync(credential, settings);
var user = _db.Users.FirstOrDefault(x => x.Email == payload.Email);
return user != null ? (IActionResult)Ok(JwtGenerator(user)) : Unauthorized();
}
private dynamic JWTGenerator(User user)
private dynamic JwtGenerator(User user)
{
var key = Encoding.ASCII.GetBytes(_configuration.GetValue<string>("Secret")!);
var expirationTime = DateTime.UtcNow.AddMinutes(5);
var tokenDescriptor = new SecurityTokenDescriptor
{
var key = Encoding.ASCII.GetBytes(configuration.GetValue<string>("Secret")!);
var expirationTime = DateTime.UtcNow.AddMinutes(5);
var tokenDescriptor = new SecurityTokenDescriptor
Subject = new ClaimsIdentity(new[]
{
Subject = new ClaimsIdentity(new[]
{
new Claim("Id", Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Jti,
Guid.NewGuid().ToString())
}),
Expires = expirationTime,
SigningCredentials = new SigningCredentials
(new SymmetricSecurityKey(key),
Guid.NewGuid().ToString())
}),
Expires = expirationTime,
SigningCredentials = new SigningCredentials
(new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha512Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwtToken = tokenHandler.WriteToken(token);
var stringToken = tokenHandler.WriteToken(token);
return new { token = stringToken, id = user.Id, expirationTime };
}
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var stringToken = tokenHandler.WriteToken(token);
return new { token = stringToken, id = user.Id, expirationTime };
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -2,72 +2,58 @@ using System.Globalization;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebAPI.Models;
namespace WebAPI.Controllers
namespace WebAPI.Controllers;
public class LogsController : Controller
{
public class LogsController : Controller
private readonly SpreadsheetsResource.ValuesResource? _googleSheetValues;
private readonly IConfiguration _configuration;
public LogsController(
GoogleSheetsHelper googleSheetsHelper,
IConfiguration configuration)
{
private SpreadsheetsResource.ValuesResource? googleSheetValues;
private GoogleDriveHelper googleDriveHelper;
private readonly IConfiguration configuration;
public LogsController(
GoogleSheetsHelper _googleSheetsHelper,
GoogleDriveHelper _googleDriveHelper,
IConfiguration _configuration)
{
if (_googleSheetsHelper.Service is not null) {
googleSheetValues = _googleSheetsHelper.Service.Spreadsheets.Values;
}
googleDriveHelper = _googleDriveHelper;
configuration = _configuration;
if (googleSheetsHelper.Service is not null) {
_googleSheetValues = googleSheetsHelper.Service.Spreadsheets.Values;
}
_configuration = configuration;
}
public void AddEntry(LogEntry entry)
{
if (_googleSheetValues is null) {
throw new Exception("Google Sheets API not initialized");
}
public void AddEntry(LogEntry entry)
var type = entry.LogType switch
{
if (googleSheetValues is null) {
throw new Exception("Google Sheets API not initialized");
}
String type;
switch (entry.LogType) {
case LogType.import:
type = "Import";
break;
case LogType.backup:
type = "Backup";
break;
case LogType.process:
type = "Process";
break;
case LogType.powerBI:
type = "PowerBIAccess";
break;
default:
type = "Other"; // should never happen
break;
}
var response = googleSheetValues.Get(configuration["appLogsFile"], $"{type}!A:A").Execute();
var data = response.Values;
int row = 1;
if (data != null) {
row = data.Count + 1;
}
var range = $"{type}!A{row}:D{row}";
List<object> logRow = new List<object>
{
entry.CreatedAt.ToString(new CultureInfo("pl-PL")),
entry.Type.ToString(),
entry.Title!,
entry.Message!
};
ValueRange valueRange = new ValueRange() { Values = new IList<object>[] { logRow }};
var updateRequest = googleSheetValues.Update(valueRange, configuration["appLogsFile"], range);
updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
updateRequest.Execute();
LogType.import => "Import",
LogType.backup => "Backup",
LogType.process => "Process",
LogType.powerBI => "PowerBIAccess",
_ => "Other"
};
var response = _googleSheetValues.Get(_configuration["appLogsFile"], $"{type}!A:A").Execute();
var data = response.Values;
var row = 1;
if (data != null) {
row = data.Count + 1;
}
var range = $"{type}!A{row}:D{row}";
var logRow = new List<object>
{
entry.CreatedAt.ToString(new CultureInfo("pl-PL")),
entry.Type.ToString(),
entry.Title!,
entry.Message!
};
var valueRange = new ValueRange { Values = new IList<object>[] { logRow }};
var updateRequest = _googleSheetValues.Update(valueRange, _configuration["appLogsFile"], range);
updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
updateRequest.Execute();
}
}

View File

@@ -1,26 +1,25 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace WebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class PingController : Controller
{
private readonly IConfiguration _configuration;
public PingController(
IConfiguration configuration)
{
_configuration = configuration;
}
namespace WebAPI.Controllers;
[HttpGet]
[Route("Ping")]
[AllowAnonymous]
public IActionResult Ping()
{
return Ok(_configuration["PONG"]);
}
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class PingController : Controller
{
private readonly IConfiguration _configuration;
public PingController(
IConfiguration configuration)
{
_configuration = configuration;
}
[HttpGet]
[Route("Ping")]
[AllowAnonymous]
public IActionResult Ping()
{
return Ok(_configuration["PONG"]);
}
}