61 lines
1.9 KiB
Go
61 lines
1.9 KiB
Go
package useCases
|
|
|
|
import (
|
|
"RenewCMS/internal/domain/audit"
|
|
"RenewCMS/internal/domain/hash"
|
|
"RenewCMS/internal/domain/mail"
|
|
"RenewCMS/internal/domain/user"
|
|
"context"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type RequestEmailChangeUseCase struct {
|
|
userRepository user.Repository
|
|
hasher hash.Hasher
|
|
issuer emailChangeIssuer
|
|
recorder audit.Recorder
|
|
}
|
|
|
|
type RequestEmailChangeCommand struct {
|
|
UserID uint32
|
|
NewEmail string
|
|
CurrentPassword string
|
|
}
|
|
|
|
func NewRequestEmailChangeUseCase(userRepository user.Repository, hasher hash.Hasher, mailRepository mail.Repository, dispatcher mail.Dispatcher, publicURL string, now func() time.Time, recorder audit.Recorder) *RequestEmailChangeUseCase {
|
|
return &RequestEmailChangeUseCase{userRepository, hasher, emailChangeIssuer{userRepository, hasher, mailRepository, dispatcher, publicURL, now}, recorder}
|
|
}
|
|
|
|
func (u *RequestEmailChangeUseCase) RequestEmailChange(ctx context.Context, command RequestEmailChangeCommand) (string, error) {
|
|
account, err := u.userRepository.Get(command.UserID)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
event := audit.NewEvent(audit.ActionUserRequestEmail, audit.CategoryUsers)
|
|
event.Target = userTarget(account)
|
|
event.Security = true
|
|
|
|
if err := u.refuse(account, command); err != nil {
|
|
recordFailure(ctx, u.recorder, event, err)
|
|
return "", err
|
|
}
|
|
if _, err := u.issuer.issue(account, command.NewEmail); err != nil {
|
|
recordFailure(ctx, u.recorder, event, err)
|
|
return "", err
|
|
}
|
|
u.issuer.sendNotice(account, command.NewEmail)
|
|
u.recorder.Record(ctx, event)
|
|
return command.NewEmail, nil
|
|
}
|
|
|
|
func (u *RequestEmailChangeUseCase) refuse(account user.User, command RequestEmailChangeCommand) error {
|
|
if u.hasher.Compare(account.Password, command.CurrentPassword) != nil {
|
|
return user.ErrWrongPassword
|
|
}
|
|
if strings.EqualFold(strings.TrimSpace(command.NewEmail), account.Email) {
|
|
return user.ErrSameEmail
|
|
}
|
|
return nil
|
|
}
|