UpdateUser updates a user.
(ctx context.Context, currentUser *UserMessage, patch *UpdateUserMessage)
| 418 | |
| 419 | // UpdateUser updates a user. |
| 420 | func (s *Store) UpdateUser(ctx context.Context, currentUser *UserMessage, patch *UpdateUserMessage) (*UserMessage, error) { |
| 421 | set := qb.Q() |
| 422 | if v := patch.Delete; v != nil { |
| 423 | set.Comma("deleted = ?", *v) |
| 424 | } |
| 425 | if v := patch.Name; v != nil { |
| 426 | set.Comma("name = ?", *v) |
| 427 | } |
| 428 | if v := patch.PasswordHash; v != nil { |
| 429 | set.Comma("password_hash = ?", *v) |
| 430 | if patch.Profile == nil { |
| 431 | patch.Profile = currentUser.Profile |
| 432 | patch.Profile.LastChangePasswordTime = timestamppb.New(time.Now()) |
| 433 | } |
| 434 | } |
| 435 | if v := patch.Phone; v != nil { |
| 436 | set.Comma("phone = ?", *v) |
| 437 | } |
| 438 | if v := patch.MFAConfig; v != nil { |
| 439 | mfaConfigBytes, err := protojson.Marshal(v) |
| 440 | if err != nil { |
| 441 | return nil, err |
| 442 | } |
| 443 | set.Comma("mfa_config = ?", mfaConfigBytes) |
| 444 | } |
| 445 | if v := patch.Profile; v != nil { |
| 446 | profileBytes, err := protojson.Marshal(v) |
| 447 | if err != nil { |
| 448 | return nil, err |
| 449 | } |
| 450 | set.Comma("profile = ?", profileBytes) |
| 451 | } |
| 452 | |
| 453 | if set.Len() == 0 { |
| 454 | return currentUser, nil |
| 455 | } |
| 456 | |
| 457 | sql, args, err := qb.Q().Space(`UPDATE principal SET ? WHERE id = ? |
| 458 | RETURNING id, deleted, email, name, password_hash, mfa_config, phone, profile, created_at`, |
| 459 | set, currentUser.ID).ToSQL() |
| 460 | if err != nil { |
| 461 | return nil, errors.Wrapf(err, "failed to build sql") |
| 462 | } |
| 463 | |
| 464 | tx, err := s.GetDB().BeginTx(ctx, nil) |
| 465 | if err != nil { |
| 466 | return nil, err |
| 467 | } |
| 468 | defer tx.Rollback() |
| 469 | |
| 470 | updatedUser, err := scanPrincipalRow(ctx, tx, sql, args) |
| 471 | if err != nil { |
| 472 | return nil, err |
| 473 | } |
| 474 | |
| 475 | if err := tx.Commit(); err != nil { |
| 476 | return nil, err |
| 477 | } |