-
Notifications
You must be signed in to change notification settings - Fork 0
/
change_password.go
65 lines (52 loc) · 1.5 KB
/
change_password.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package account
import (
"context"
"fmt"
"github.com/polyscone/tofu/app"
"github.com/polyscone/tofu/errsx"
)
type ChangePasswordGuard interface {
CanChangePassword(userID string) bool
}
func (s *Service) ChangePassword(ctx context.Context, guard ChangePasswordGuard, userID, oldPassword, newPassword, newPasswordCheck string) error {
var input struct {
userID UserID
oldPassword Password
newPassword Password
newPasswordCheck Password
}
{
if !guard.CanChangePassword(userID) {
return app.ErrForbidden
}
var err error
var errs errsx.Map
newPasswordCheck, _ := NewPassword(newPasswordCheck)
if input.userID, err = s.repo.ParseUserID(userID); err != nil {
errs.Set("user id", err)
}
if input.oldPassword, err = NewPassword(oldPassword); err != nil {
errs.Set("old password", err)
}
if input.newPassword, err = NewPassword(newPassword); err != nil {
errs.Set("new password", err)
} else if !input.newPassword.Equal(newPasswordCheck) {
errs.Set("new password", "passwords do not match")
}
if errs != nil {
return fmt.Errorf("%w: %w", app.ErrMalformedInput, errs)
}
}
user, err := s.repo.FindUserByID(ctx, input.userID.String())
if err != nil {
return fmt.Errorf("find user by id: %w", err)
}
if err := user.ChangePassword(input.oldPassword, input.newPassword, s.hasher); err != nil {
return err
}
if err := s.repo.SaveUser(ctx, user); err != nil {
return fmt.Errorf("save user: %w", err)
}
s.broker.Flush(&user.Events)
return nil
}