From 3e2d70087dcbadae97ff5841da7d912f42b79706 Mon Sep 17 00:00:00 2001
From: Matheus Barbosa Silva
 <36537004+matheusbsilva137@users.noreply.github.com>
Date: Tue, 4 Jul 2023 11:07:10 -0300
Subject: [PATCH] fix: avatar is reset in the UI when username is changed
 (#29685)

---
 .changeset/green-icons-smash.md               |  5 +++++
 .../lib/server/functions/saveUserIdentity.ts  | 20 +++++++++----------
 2 files changed, 15 insertions(+), 10 deletions(-)
 create mode 100644 .changeset/green-icons-smash.md

diff --git a/.changeset/green-icons-smash.md b/.changeset/green-icons-smash.md
new file mode 100644
index 00000000000..5419c2c3fa5
--- /dev/null
+++ b/.changeset/green-icons-smash.md
@@ -0,0 +1,5 @@
+---
+"@rocket.chat/meteor": patch
+---
+
+fix: Avatar is reset in the UI when username is changed
diff --git a/apps/meteor/app/lib/server/functions/saveUserIdentity.ts b/apps/meteor/app/lib/server/functions/saveUserIdentity.ts
index a7c98664785..37ec3a890bd 100644
--- a/apps/meteor/app/lib/server/functions/saveUserIdentity.ts
+++ b/apps/meteor/app/lib/server/functions/saveUserIdentity.ts
@@ -49,6 +49,16 @@ export async function saveUserIdentity({ _id, name: rawName, username: rawUserna
 	// if coming from old username, update all references
 	if (previousUsername) {
 		if (usernameChanged && typeof rawUsername !== 'undefined') {
+			const fileStore = FileUpload.getStore('Avatars');
+			const previousFile = await fileStore.model.findOneByName(previousUsername);
+			const file = await fileStore.model.findOneByName(username);
+			if (file) {
+				await fileStore.model.deleteFile(file._id);
+			}
+			if (previousFile) {
+				await fileStore.model.updateFileNameById(previousFile._id, username);
+			}
+
 			await Messages.updateAllUsernamesByUserId(user._id, username);
 			await Messages.updateUsernameOfEditByUserId(user._id, username);
 
@@ -64,16 +74,6 @@ export async function saveUserIdentity({ _id, name: rawName, username: rawUserna
 			await Subscriptions.setUserUsernameByUserId(user._id, username);
 
 			await LivechatDepartmentAgents.replaceUsernameOfAgentByUserId(user._id, username);
-
-			const fileStore = FileUpload.getStore('Avatars');
-			const previousFile = await fileStore.model.findOneByName(previousUsername);
-			const file = await fileStore.model.findOneByName(username);
-			if (file) {
-				await fileStore.model.deleteFile(file._id);
-			}
-			if (previousFile) {
-				await fileStore.model.updateFileNameById(previousFile._id, username);
-			}
 		}
 
 		// update other references if either the name or username has changed
-- 
GitLab