diff --git a/models/user/user.go b/models/user/user.go index 1508b2420..efc9fb296 100644 --- a/models/user/user.go +++ b/models/user/user.go @@ -827,8 +827,9 @@ func validateUser(u *User) error { return ValidateEmail(u.Email) } -func updateUser(ctx context.Context, u *User, changePrimaryEmail bool) error { - if err := validateUser(u); err != nil { +func updateUser(ctx context.Context, u *User, changePrimaryEmail bool, cols ...string) error { + err := validateUser(u) + if err != nil { return err } @@ -860,15 +861,35 @@ func updateUser(ctx context.Context, u *User, changePrimaryEmail bool) error { }); err != nil { return err } + } else { // check if primary email in email_address table + primaryEmailExist, err := e.Where("uid=? AND is_primary=?", u.ID, true).Exist(&EmailAddress{}) + if err != nil { + return err + } + + if !primaryEmailExist { + if _, err = e.Insert(&EmailAddress{ + Email: u.Email, + UID: u.ID, + IsActivated: true, + IsPrimary: true, + }); err != nil { + return err + } + } } - _, err := e.ID(u.ID).AllCols().Update(u) + if len(cols) == 0 { + _, err = e.ID(u.ID).AllCols().Update(u) + } else { + _, err = e.ID(u.ID).Cols(cols...).Update(u) + } return err } // UpdateUser updates user's information. -func UpdateUser(u *User, emailChanged bool) error { - return updateUser(db.DefaultContext, u, emailChanged) +func UpdateUser(u *User, emailChanged bool, cols ...string) error { + return updateUser(db.DefaultContext, u, emailChanged, cols...) } // UpdateUserCols update user according special columns diff --git a/services/auth/source/ldap/source_sync.go b/services/auth/source/ldap/source_sync.go index 78aa90aaa..a7f06fcc9 100644 --- a/services/auth/source/ldap/source_sync.go +++ b/services/auth/source/ldap/source_sync.go @@ -143,6 +143,7 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error { log.Trace("SyncExternalUsers[%s]: Updating user %s", source.authSource.Name, usr.Name) usr.FullName = fullName + emailChanged := usr.Email != su.Mail usr.Email = su.Mail // Change existing admin flag only if AdminFilter option is set if len(source.AdminFilter) > 0 { @@ -154,7 +155,7 @@ func (source *Source) Sync(ctx context.Context, updateExisting bool) error { } usr.IsActive = true - err = user_model.UpdateUserCols(db.DefaultContext, usr, "full_name", "email", "is_admin", "is_restricted", "is_active") + err = user_model.UpdateUser(usr, emailChanged, "full_name", "email", "is_admin", "is_restricted", "is_active") if err != nil { log.Error("SyncExternalUsers[%s]: Error updating user %s: %v", source.authSource.Name, usr.Name, err) }