@@ -119,35 +119,52 @@ export async function updateUser(req, res) {
119119 if ( ! user ) {
120120 return res . status ( 404 ) . json ( { message : `User ${ userId } not found` } ) ;
121121 }
122- const username = dirtyUsername ? checkUsername ( dirtyUsername ) : undefined ;
123- const email = dirtyEmail ? checkEmail ( dirtyEmail ) : undefined ;
124- const password = dirtyPassword ? checkPassword ( dirtyPassword ) : undefined ;
125122
126- if ( username ) {
123+ let username ;
124+ if ( dirtyUsername ) {
125+ username = checkUsername ( dirtyUsername ) ;
127126 const existingUser = await _findUserByUsername ( username ) ;
128127 if ( existingUser && existingUser . id !== userId ) {
129128 return res . status ( 409 ) . json ( { message : "Username already exists" } ) ;
130129 }
130+ } else {
131+ username = user . username ;
131132 }
132133
133- if ( email ) {
134+ let email ;
135+ if ( dirtyEmail ) {
136+ email = checkEmail ( dirtyEmail ) ;
134137 const existingUser = await _findUserByEmail ( email ) ;
135138 if ( existingUser && existingUser . id !== userId ) {
136139 return res . status ( 409 ) . json ( { message : "Email already exists" } ) ;
137140 }
141+ } else {
142+ email = user . email ;
138143 }
139144
140145 let hashedPassword ;
141- if ( password ) {
146+ if ( dirtyPassword ) {
147+ const unhashedPassword = checkPassword ( dirtyPassword ) ;
142148 const salt = bcrypt . genSaltSync ( 10 ) ;
143- hashedPassword = bcrypt . hashSync ( password , salt ) ;
149+ hashedPassword = bcrypt . hashSync ( unhashedPassword , salt ) ;
150+ } else {
151+ hashedPassword = user . password ;
152+ }
153+
154+ let updatedUser = user ;
155+ if (
156+ ! bcrypt . compare ( hashedPassword , user . password ) ||
157+ username !== user . username ||
158+ email !== user . email
159+ ) {
160+ // Only update if there is a change
161+ updatedUser = await _updateUserById (
162+ userId ,
163+ username ,
164+ email ,
165+ hashedPassword ,
166+ ) ;
144167 }
145- const updatedUser = await _updateUserById (
146- userId ,
147- username ,
148- email ,
149- hashedPassword ,
150- ) ;
151168 return res . status ( 200 ) . json ( {
152169 message : `Updated data for user ${ userId } ` ,
153170 data : formatUserResponse ( updatedUser ) ,
0 commit comments