Auth: Prevent duplicate usernames when renaming accounts #98

Signed-off-by: Michael Mayer <michael@photoprism.app>
This commit is contained in:
Michael Mayer 2023-03-09 19:56:07 +01:00
parent f8789d7817
commit 654b41afe5
2 changed files with 29 additions and 2 deletions

View file

@ -537,8 +537,16 @@ func (m *User) SetUsername(login string) (err error) {
return nil
}
// UpdateUsername changes the login username and saves it to the database.
// UpdateUsername changes the login name in the database.
func (m *User) UpdateUsername(login string) (err error) {
// Check if the name already exists or has not changed.
if m.UserName == login || m.ID <= 0 {
return nil
} else if user := FindUserByName(login); user != nil {
return fmt.Errorf("user %s already exists", clean.LogQuote(login))
}
// Set new username.
if err = m.SetUsername(login); err != nil {
return err
}

View file

@ -212,7 +212,26 @@ func TestUser_Create(t *testing.T) {
})
}
func TestUser_SetName(t *testing.T) {
func TestUser_UpdateUsername(t *testing.T) {
t.Run("Exists", func(t *testing.T) {
var m = User{
ID: 2,
UserName: "foo",
UserRole: acl.RoleAdmin.String(),
DisplayName: "Admin",
SuperAdmin: false,
CanLogin: true,
}
if err := m.UpdateUsername("admin"); err == nil {
t.Fatal("error expected")
} else {
t.Logf("expected errror: %s", err)
}
})
}
func TestUser_SetUsername(t *testing.T) {
t.Run("photoprism", func(t *testing.T) {
m := FindUserByName("admin")