-
Notifications
You must be signed in to change notification settings - Fork 0
/
savepassword.go
94 lines (78 loc) · 2.37 KB
/
savepassword.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package commands
import (
"crypto/rand"
"crypto/sha256"
"fmt"
"math/big"
"github.com/Goldwin/ies-pik-cms/pkg/auth/dto"
"github.com/Goldwin/ies-pik-cms/pkg/auth/entities"
. "github.com/Goldwin/ies-pik-cms/pkg/common/commands"
)
const (
SavePasswordErrorInvalidInput CommandErrorCode = 20401
SavePasswordErrorFailedToVerifyAccount CommandErrorCode = 20402
)
type SavePasswordCommand struct {
Email entities.EmailAddress
Password []byte
}
func (cmd SavePasswordCommand) Execute(ctx CommandContext) CommandExecutionResult[dto.PasswordResult] {
account, err := ctx.AccountRepository().GetAccount(cmd.Email)
if err != nil {
return CommandExecutionResult[dto.PasswordResult]{
Status: ExecutionStatusFailed,
Error: CommandErrorDetail{
Code: SavePasswordErrorFailedToVerifyAccount,
Message: fmt.Sprintf("Failed to Verify Account: %s", err.Error()),
},
}
}
if account == nil {
_, err = ctx.AccountRepository().AddAccount(entities.Account{
Email: entities.EmailAddress(cmd.Email),
Roles: []entities.Role{},
})
if err != nil {
return CommandExecutionResult[dto.PasswordResult]{
Status: ExecutionStatusFailed,
Error: CommandErrorDetail{
Code: SavePasswordErrorFailedToVerifyAccount,
Message: fmt.Sprintf("Failed to Verify Account: %s", err.Error()),
},
}
}
}
password := entities.PasswordDetail{
EmailAddress: entities.EmailAddress(cmd.Email),
}
salt, err := rand.Int(rand.Reader, big.NewInt(999999))
if err != nil {
return CommandExecutionResult[dto.PasswordResult]{
Status: ExecutionStatusFailed,
Error: CommandErrorDetail{
Code: GenerateOtpErrorFailedToGenOtp,
Message: fmt.Sprintf("Failed to Save Password: %s", err.Error()),
},
}
}
password.Salt = salt.Bytes()
passwordAndSalt := append(cmd.Password, password.Salt...)
passwordHash := sha256.Sum256(passwordAndSalt)
password.PasswordHash = passwordHash[:]
err = ctx.PasswordRepository().Save(password)
if err != nil {
return CommandExecutionResult[dto.PasswordResult]{
Status: ExecutionStatusFailed,
Error: CommandErrorDetail{
Code: SavePasswordErrorFailedToVerifyAccount,
Message: fmt.Sprintf("Failed to Save Password: %s", err.Error()),
},
}
}
return CommandExecutionResult[dto.PasswordResult]{
Status: ExecutionStatusSuccess,
Result: dto.PasswordResult{
Email: string(password.EmailAddress),
},
}
}