diff --git a/src/api/user/default.js b/src/api/user/default.js
index 88c7a4e..cedcf01 100644
--- a/src/api/user/default.js
+++ b/src/api/user/default.js
@@ -229,7 +229,7 @@ export default async function(fastify, options) {
return pMatchHistory(request, reply, fastify, getUserInfo, addMatch, incWinsPong, incLossesPong, incWinsTetris, incLossesTetris);
});
fastify.post('/users/:userId/avatar', { bodyLimit: 5242880, preHandler: [fastify.authenticate] }, async (request, reply) => {
- return pAvatar(request, reply, fastify, getUserInfo, setAvatarId, postImage);
+ return pAvatar(request, reply, fastify, getUserInfo, getAvatarId, setAvatarId, deleteAvatarId, postImage, deleteImage);
});
fastify.post('/ping', { preHandler: [fastify.authenticate] }, async (request, reply) => {
return pPing(request, reply, fastify, setActivityTime);
diff --git a/src/api/user/pAvatar.js b/src/api/user/pAvatar.js
index f90299e..7515052 100644
--- a/src/api/user/pAvatar.js
+++ b/src/api/user/pAvatar.js
@@ -5,7 +5,7 @@ import sharp from 'sharp';
* @param {import('fastify').FastifyReply} reply
* @param {import('fastify').FastifyInstance} fastify
*/
-export async function pAvatar(request, reply, fastify, getUserInfo, setAvatarId, postImage) {
+export async function pAvatar(request, reply, fastify, getUserInfo, getAvatarId, setAvatarId, deleteAvatarId, postImage, deleteImage) {
try {
const userId = request.params.userId;
if (request.user !== userId && request.user !== 'admin') {
@@ -35,6 +35,12 @@ export async function pAvatar(request, reply, fastify, getUserInfo, setAvatarId,
const fileName = `avatar_${userId}.webp`;
const imageId = postImage.run(fileName, mimeType, webpBuffer);
+ const oldImageId = getAvatarId.get(userId);
+ if (oldImageId.avatarId !== -1) {
+ deleteImage.run(oldImageId.avatarId);
+ deleteAvatarId.run(userId);
+ }
+
setAvatarId.run(imageId.lastInsertRowid, userId);
return reply.code(200).send({ msg: "Avatar uploaded successfully" });
diff --git a/src/front/index.html b/src/front/index.html
index dbd12eb..96203cc 100644
--- a/src/front/index.html
+++ b/src/front/index.html
@@ -39,7 +39,7 @@