MarkEmailPrimary marks the email address of the given user as primary. It returns ErrEmailNotExist when the email is not found for the user, and ErrEmailNotActivated when the email is not activated.
(ctx context.Context, userID int64, email string)
| 1158 | // returns ErrEmailNotExist when the email is not found for the user, and |
| 1159 | // ErrEmailNotActivated when the email is not activated. |
| 1160 | func (s *UsersStore) MarkEmailPrimary(ctx context.Context, userID int64, email string) error { |
| 1161 | var emailAddress EmailAddress |
| 1162 | err := s.db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).First(&emailAddress).Error |
| 1163 | if err != nil { |
| 1164 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 1165 | return ErrEmailNotExist{args: errutil.Args{"email": email}} |
| 1166 | } |
| 1167 | return errors.Wrap(err, "get email address") |
| 1168 | } |
| 1169 | |
| 1170 | if !emailAddress.IsActivated { |
| 1171 | return ErrEmailNotVerified{args: errutil.Args{"email": email}} |
| 1172 | } |
| 1173 | |
| 1174 | user, err := s.GetByID(ctx, userID) |
| 1175 | if err != nil { |
| 1176 | return errors.Wrap(err, "get user") |
| 1177 | } |
| 1178 | |
| 1179 | return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 1180 | // Make sure the former primary email doesn't disappear. |
| 1181 | err = tx.FirstOrCreate( |
| 1182 | &EmailAddress{ |
| 1183 | UserID: user.ID, |
| 1184 | Email: user.Email, |
| 1185 | IsActivated: user.IsActive, |
| 1186 | }, |
| 1187 | &EmailAddress{ |
| 1188 | UserID: user.ID, |
| 1189 | Email: user.Email, |
| 1190 | }, |
| 1191 | ).Error |
| 1192 | if err != nil { |
| 1193 | return errors.Wrap(err, "upsert former primary email address") |
| 1194 | } |
| 1195 | |
| 1196 | return tx.Model(&User{}). |
| 1197 | Where("id = ?", user.ID). |
| 1198 | Updates(map[string]any{ |
| 1199 | "email": email, |
| 1200 | "updated_unix": tx.NowFunc().Unix(), |
| 1201 | }, |
| 1202 | ).Error |
| 1203 | }) |
| 1204 | } |
| 1205 | |
| 1206 | // DeleteEmail deletes the email address of the given user. |
| 1207 | func (s *UsersStore) DeleteEmail(ctx context.Context, userID int64, email string) error { |