From 2595c708684d63e3e0bdd37565a20b166956a9e6 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 25 Jan 2021 00:36:16 +0100 Subject: [PATCH] ChangeUserName: rename user files back on DB issue (#14447) --- models/user.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/models/user.go b/models/user.go index f35d2e5c6b..f8e0ae8cba 100644 --- a/models/user.go +++ b/models/user.go @@ -922,6 +922,7 @@ func VerifyActiveEmailCode(code, email string) *EmailAddress { // ChangeUserName changes all corresponding setting from old user name to new one. func ChangeUserName(u *User, newUserName string) (err error) { + oldUserName := u.Name if err = IsUsableUsername(newUserName); err != nil { return err } @@ -939,16 +940,24 @@ func ChangeUserName(u *User, newUserName string) (err error) { return err } - if _, err = sess.Exec("UPDATE `repository` SET owner_name=? WHERE owner_name=?", newUserName, u.Name); err != nil { + if _, err = sess.Exec("UPDATE `repository` SET owner_name=? WHERE owner_name=?", newUserName, oldUserName); err != nil { return fmt.Errorf("Change repo owner name: %v", err) } // Do not fail if directory does not exist - if err = os.Rename(UserPath(u.Name), UserPath(newUserName)); err != nil && !os.IsNotExist(err) { + if err = os.Rename(UserPath(oldUserName), UserPath(newUserName)); err != nil && !os.IsNotExist(err) { return fmt.Errorf("Rename user directory: %v", err) } - return sess.Commit() + if err = sess.Commit(); err != nil { + if err2 := os.Rename(UserPath(newUserName), UserPath(oldUserName)); err2 != nil && !os.IsNotExist(err2) { + log.Critical("Unable to rollback directory change during failed username change from: %s to: %s. DB Error: %v. Filesystem Error: %v", oldUserName, newUserName, err, err2) + return fmt.Errorf("failed to rollback directory change during failed username change from: %s to: %s. DB Error: %w. Filesystem Error: %v", oldUserName, newUserName, err, err2) + } + return err + } + + return nil } // checkDupEmail checks whether there are the same email with the user