fix(backend): *actually* correctly hash images

This commit is contained in:
sam 2024-09-26 22:30:24 +02:00
parent 14e6e35cb7
commit e20a7d3465
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
4 changed files with 11 additions and 12 deletions

View file

@ -1,3 +1,4 @@
using System.Security.Cryptography;
using Foxnouns.Backend.Database;
using Foxnouns.Backend.Jobs;
using Foxnouns.Backend.Services;
@ -23,7 +24,7 @@ public static class AvatarObjectExtensions
CancellationToken ct = default) =>
await objectStorageService.RemoveObjectAsync(UserAvatarUpdateInvocable.Path(id, hash), ct);
public static async Task<Stream> ConvertBase64UriToImage(this string uri, int size, bool crop)
public static async Task<(string Hash, Stream Image)> ConvertBase64UriToImage(this string uri, int size, bool crop)
{
if (!uri.StartsWith("data:image/"))
throw new ArgumentException("Not a data URI", nameof(uri));
@ -53,6 +54,11 @@ public static class AvatarObjectExtensions
var stream = new MemoryStream(64 * 1024);
await image.SaveAsync(stream, new WebpEncoder { Quality = 95, NearLossless = false });
return stream;
stream.Seek(0, SeekOrigin.Begin);
var hash = Convert.ToHexString(await SHA256.HashDataAsync(stream)).ToLower();
stream.Seek(0, SeekOrigin.Begin);
return (hash, stream);
}
}

View file

@ -20,11 +20,7 @@ public class CreateFlagInvocable(DatabaseContext db, ObjectStorageService object
try
{
var image = await Payload.ImageData.ConvertBase64UriToImage(size: 256, crop: false);
image.Seek(0, SeekOrigin.Begin);
var hash = Convert.ToHexString(await SHA256.HashDataAsync(image)).ToLower();
image.Seek(0, SeekOrigin.Begin);
var (hash, image) = await Payload.ImageData.ConvertBase64UriToImage(size: 256, crop: false);
await objectStorageService.PutObjectAsync(Path(hash), image, "image/webp");
var flag = new PrideFlag

View file

@ -31,9 +31,7 @@ public class MemberAvatarUpdateInvocable(DatabaseContext db, ObjectStorageServic
try
{
var image = await newAvatar.ConvertBase64UriToImage(size: 512, crop: true);
var hash = Convert.ToHexString(await SHA256.HashDataAsync(image)).ToLower();
image.Seek(0, SeekOrigin.Begin);
var (hash, image) = await newAvatar.ConvertBase64UriToImage(size: 512, crop: true);
var prevHash = member.Avatar;
await objectStorageService.PutObjectAsync(Path(id, hash), image, "image/webp");

View file

@ -31,8 +31,7 @@ public class UserAvatarUpdateInvocable(DatabaseContext db, ObjectStorageService
try
{
var image = await newAvatar.ConvertBase64UriToImage(size: 512, crop: true);
var hash = Convert.ToHexString(await SHA256.HashDataAsync(image)).ToLower();
var (hash, image) = await newAvatar.ConvertBase64UriToImage(size: 512, crop: true);
image.Seek(0, SeekOrigin.Begin);
var prevHash = user.Avatar;