Skip to content

Commit

Permalink
Fix upload stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
fergalmoran committed Nov 5, 2024
1 parent 97a7e9e commit ecc607c
Show file tree
Hide file tree
Showing 12 changed files with 116 additions and 32 deletions.
24 changes: 22 additions & 2 deletions mixyboos-api/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Bogus;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
Expand Down Expand Up @@ -33,8 +36,6 @@ public AccountController(
_imageCacher = imageCacher;
}

//
// POST: /Account/Register
[HttpPost("register")]
[AllowAnonymous]
public async Task<IActionResult> Register([FromBody] RegisterDTO model) {
Expand Down Expand Up @@ -65,6 +66,25 @@ public async Task<IActionResult> Register([FromBody] RegisterDTO model) {
return BadRequest(ModelState);
}

[HttpDelete("logout")]
public async Task<IActionResult> Logout() {
var cookieName = _config["Auth:CookieName"];
var domainName = _config["Auth:DomainName"];
if (string.IsNullOrEmpty(cookieName)) {
return BadRequest();
}

await HttpContext.SignOutAsync();
Response.Cookies.Delete(cookieName, new CookieOptions {
Domain = domainName,
SameSite = SameSiteMode.Strict,
HttpOnly = true
});

// Response.Cookies[cookieName].Expires = DateTime.Now.AddDays(-1);
return Ok();
}


#region Helpers

Expand Down
12 changes: 8 additions & 4 deletions mixyboos-api/Controllers/UploadController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,15 @@ public UploadController(UserManager<MixyBoosUser> userManager, ISchedulerFactory
}

[HttpPost("image/{id}")]
[RequestFormLimits(MultipartBodyLengthLimit = AudioFileSizeLimit)] //2Gb
[RequestSizeLimit(AudioFileSizeLimit)] //2Gb
[RequestFormLimits(MultipartBodyLengthLimit = ImageFileSizeLimit)] //2Gb
[RequestSizeLimit(ImageFileSizeLimit)] //2Gb
[DisableFormValueModelBinding]
public async Task<IActionResult> UploadImage([FromRoute] string id, IFormFile file,
[FromQuery] string imageSource, [FromQuery] string imageType) {
public async Task<IActionResult> UploadImage([FromRoute] string id,
[FromQuery] string imageSource, [FromQuery] string imageType, IFormFile file) {
if (file is null) {
return BadRequest("No file found in request");
}

var (response, localFile) = await _preProcessUpload(id, file);

if (string.IsNullOrEmpty(localFile)) {
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 6 additions & 5 deletions mixyboos-api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
using MixyBoos.Api.Services.Helpers.Audio;
using MixyBoos.Api.Services.Startup;
using Serilog;
using SixLabors.ImageSharp.Web.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

Expand All @@ -39,8 +40,8 @@
builder.Services.AddSingleton<ImageCacher>();
builder.Services.AddSingleton<ImageHelper>();
builder.Services.AddSingleton<IFileProvider, PhysicalFileProvider>(_ =>
new PhysicalFileProvider(
builder.Configuration["ImageProcessing:ImageRootFolder"] ?? ".pn-cache"));
new PhysicalFileProvider("/"));
// builder.Configuration["ImageProcessing:ImageRootFolder"] ?? ".pn-cache"));

builder.Services.AddDbContext<MixyBoosContext>(options =>
options
Expand All @@ -60,7 +61,7 @@
builder.Services.AddSwaggerGen();
builder.Services.AddControllers();
builder.Services.AddSignalR();

builder.Services.AddImaging(builder.Configuration);
builder.Services.Configure<RouteOptions>(options => {
options.LowercaseUrls = true;
});
Expand All @@ -85,8 +86,7 @@

app.UseCors(corsBuilder => corsBuilder
.WithOrigins("http://localhost:3000")
.WithOrigins("https://mixyboos.dev.fergl.ie:3002")
.WithOrigins("http://mixyboos.dev.fergl.ie:3002")
.WithOrigins("https://mixyboos.dev.fergl.ie:3000")
.WithOrigins("https://www.mixyboos.com")
.WithOrigins("https://mixyboos.com")
.AllowCredentials()
Expand All @@ -111,4 +111,5 @@
.RequireAuthorization()
.WithName("AuthPing");

app.UseImageSharp();
app.Run();
48 changes: 48 additions & 0 deletions mixyboos-api/Services/Auth/SigningCertificateGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace MixyBoos.Api.Services.Auth;

public static class SigningCertificateGenerator {
public static X509Certificate2 CreateEncryptionCertificate() {
if (File.Exists("encryption-certificate.pfx")) {
return new X509Certificate2("encryption-certificate.pfx");
}

using var algorithm = RSA.Create(keySizeInBits: 2048);

var subject = new X500DistinguishedName("CN=Mixboos Encryption Certificate");
var request =
new CertificateRequest(subject, algorithm, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyEncipherment,
critical: true));

var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddYears(2));

File.WriteAllBytes("encryption-certificate.pfx", certificate.Export(X509ContentType.Pfx, string.Empty));

return new X509Certificate2("encryption-certificate.pfx");
}

public static X509Certificate2 CreateSigningCertificate() {
if (File.Exists("signing-certificate.pfx")) {
return new X509Certificate2("signing-certificate.pfx");
}

using var algorithm = RSA.Create(keySizeInBits: 2048);

var subject = new X500DistinguishedName("CN=Mixboos Encryption Certificate");
var request =
new CertificateRequest(subject, algorithm, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature,
critical: true));

var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddYears(2));

File.WriteAllBytes("signing-certificate.pfx", certificate.Export(X509ContentType.Pfx, string.Empty));

return new X509Certificate2("signing-certificate.pfx");
}
}
20 changes: 13 additions & 7 deletions mixyboos-api/Services/Imaging/FileSystemImageProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,26 @@ public bool IsValidRequest(HttpContext context) {
}

public Task<IImageResolver> GetAsync(HttpContext context) {
var imageRootPath = _config["ImageProcessing:ImageRootFolder"];
if (string.IsNullOrEmpty(imageRootPath) || !Directory.Exists(imageRootPath)) {
throw new FileNotFoundException("ImageRootFolder not found");
}

var prefix = _pathPrefixes
.Select(r => context.Request.Path.Value.TrimStartString(r))
.Aggregate((a, b) => $"{a}{b}")
.TrimStart('/');

var filePath = Path.Combine(
_config["ImageProcessing:ImageRootFolder"],
_pathPrefixes.Select(r => context.Request.Path.Value.TrimStartString(r))
.Aggregate((a, b) => $"{a}{b}")
imageRootPath,
prefix
);
var info = _fileProvider.GetFileInfo(filePath);

// Check to see if the file exists.
if (!info.Exists) {
return Task.FromResult<IImageResolver>(null);
}
return Task.FromResult<IImageResolver>(!info.Exists ? null : new ImageResolver(info));

// We don't care about the content type nor cache control max age here.
return Task.FromResult<IImageResolver>(new ImageResolver(info));
}

public ProcessingBehavior ProcessingBehavior { get; }
Expand Down
14 changes: 10 additions & 4 deletions mixyboos-api/Services/Jobs/ProcessUploadedImageJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ public async Task Execute(IJobExecutionContext context) {
var imageSource = data["ImageSource"]?.ToString();
var imageType = data["ImageType"]?.ToString();
var fileLocation = data["FileLocation"]?.ToString();
var outputPath = _config[$"ImageProcessing:{imageSource}Dir"];
var outputPath =
Path.Combine(
_config["ImageProcessing:ImageRootFolder"] ?? throw new InvalidOperationException(),
imageSource ?? throw new InvalidOperationException(),
imageType ?? throw new InvalidOperationException());
if (string.IsNullOrEmpty(outputPath)) {
_logger.LogError("Unable to create output path for {FileLocation}", fileLocation);
return;
Expand All @@ -41,7 +45,9 @@ public async Task Execute(IJobExecutionContext context) {
Directory.CreateDirectory(outputPath);
}

var destinationFile = Path.Combine(outputPath, imageType ?? string.Empty, Path.GetFileName(fileLocation));
var destinationFile = Path.Combine(
outputPath, Path.GetFileName(fileLocation) ?? throw new InvalidOperationException());

if (File.Exists(fileLocation) && Directory.Exists(outputPath)) {
if (File.Exists(destinationFile)) {
File.Delete(destinationFile);
Expand All @@ -54,10 +60,10 @@ public async Task Execute(IJobExecutionContext context) {
fileLocation, destinationFile);

switch (imageSource) {
case "MixImage":
case "mixes":
await _updateMixImageDetails(id, destinationFile);
break;
case "UserImage":
case "users":
await _updateUserImageDetails(id, imageType, destinationFile);
break;
}
Expand Down
8 changes: 8 additions & 0 deletions mixyboos-api/Services/Startup/AuthenticationStartup.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -12,6 +13,13 @@ namespace MixyBoos.Api.Services.Startup;
public static class AuthenticationStartup {
public static IServiceCollection AddMixyboosAuthentication(this IServiceCollection services, IConfiguration config) {
services.AddAuthorization();
services.ConfigureApplicationCookie(options => {
options.Cookie.Name = config["Auth:CookieName"];
options.Cookie.Domain = config["Auth:DomainName"];
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.HttpOnly = true;
});
services
.AddIdentityApiEndpoints<MixyBoosUser>()
.AddEntityFrameworkStores<MixyBoosContext>();
Expand Down
9 changes: 0 additions & 9 deletions mixyboos-api/Services/Startup/ImagingStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,7 @@ public static IServiceCollection AddImaging(this IServiceCollection services, IC
services.AddImageSharp()
.SetRequestParser<QueryCollectionRequestParser>()
.ClearProviders()
.Configure<PhysicalFileSystemCacheOptions>(options => {
options.CacheRootPath = ".img-cache";
})
.Configure<PhysicalFileSystemProviderOptions>(options => {
options.ProviderRootPath = config["ImageProcessing:ImageCacheFolder"] ?? "/tmp";
options.ProcessingBehavior = ProcessingBehavior.All;
})
.SetCache<PhysicalFileSystemCache>()
.AddProvider<FileSystemImageProvider>()
// .AddProvider(PhysicalFileSystemProviderFactory)
.AddProcessor<ResizeWebProcessor>();
return services;
}
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit ecc607c

Please sign in to comment.