Introduce user.updateUser

Unify updatePassword and updateRealname into a single function. This
allows "user update" to be atomic.
This commit is contained in:
Simon Ser 2021-06-28 18:05:03 +02:00
parent 00538e7028
commit acde97ca37
2 changed files with 33 additions and 25 deletions

View File

@ -775,19 +775,22 @@ func handleUserUpdate(dc *downstreamConn, params []string) error {
return err
}
// copy the user record because we'll mutate it
record := dc.user.User
if password != nil {
hashed, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("failed to hash password: %v", err)
}
if err := dc.user.updatePassword(string(hashed)); err != nil {
return err
}
record.Password = string(hashed)
}
if realname != nil {
if err := dc.user.updateRealname(*realname); err != nil {
return err
record.Realname = *realname
}
if err := dc.user.updateUser(&record); err != nil {
return err
}
sendServicePRIVMSG(dc, fmt.Sprintf("updated user %q", dc.user.Username))

19
user.go
View File

@ -856,17 +856,18 @@ func (u *user) deleteNetwork(id int64) error {
return nil
}
func (u *user) updatePassword(hashed string) error {
u.User.Password = hashed
return u.srv.db.StoreUser(&u.User)
func (u *user) updateUser(record *User) error {
if u.ID != record.ID {
panic("ID mismatch when updating user")
}
func (u *user) updateRealname(realname string) error {
u.User.Realname = realname
if err := u.srv.db.StoreUser(&u.User); err != nil {
realnameUpdated := u.Realname != record.Realname
if err := u.srv.db.StoreUser(record); err != nil {
return fmt.Errorf("failed to update user %q: %v", u.Username, err)
}
u.User = *record
if realnameUpdated {
// Re-connect to networks which use the default realname
var needUpdate []Network
u.forEachNetwork(func(net *network) {
@ -881,9 +882,13 @@ func (u *user) updateRealname(realname string) error {
netErr = err
}
}
if netErr != nil {
return netErr
}
}
return nil
}
func (u *user) stop() {
u.events <- eventStop{}