fix(backend): correctly hash images

This commit is contained in:
sam 2024-09-26 22:25:47 +02:00
parent a70078995b
commit ff2ba1fb1b
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
3 changed files with 9 additions and 4 deletions

View file

@ -23,7 +23,7 @@ public static class AvatarObjectExtensions
CancellationToken ct = default) => CancellationToken ct = default) =>
await objectStorageService.RemoveObjectAsync(UserAvatarUpdateInvocable.Path(id, hash), ct); await objectStorageService.RemoveObjectAsync(UserAvatarUpdateInvocable.Path(id, hash), ct);
public static async Task<Stream> ConvertBase64UriToAvatar(this string uri) public static async Task<Stream> ConvertBase64UriToImage(this string uri, int size, bool crop)
{ {
if (!uri.StartsWith("data:image/")) if (!uri.StartsWith("data:image/"))
throw new ArgumentException("Not a data URI", nameof(uri)); throw new ArgumentException("Not a data URI", nameof(uri));
@ -40,7 +40,12 @@ public static class AvatarObjectExtensions
var image = Image.Load(rawImage); var image = Image.Load(rawImage);
var processor = new ResizeProcessor( var processor = new ResizeProcessor(
new ResizeOptions { Size = new Size(512), Mode = ResizeMode.Crop, Position = AnchorPositionMode.Center }, new ResizeOptions
{
Size = new Size(size),
Mode = crop ? ResizeMode.Crop : ResizeMode.Max,
Position = AnchorPositionMode.Center
},
image.Size image.Size
); );

View file

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

View file

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