-
Notifications
You must be signed in to change notification settings - Fork 18
/
generate_api_token.go
91 lines (74 loc) · 2.34 KB
/
generate_api_token.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
package connections
import (
"context"
"fmt"
"time"
"code.vegaprotocol.io/vega/wallet/api"
)
type GenerateAPITokenParams struct {
Description string `json:"name"`
ExpiresIn *time.Duration `json:"expireIn"`
Wallet GenerateAPITokenWalletParams `json:"wallet"`
}
type GenerateAPITokenWalletParams struct {
Name string `json:"name"`
Passphrase string `json:"passphrase"`
}
type GenerateAPITokenHandler struct {
walletStore api.WalletStore
tokenStore TokenStore
timeService TimeService
}
func (h *GenerateAPITokenHandler) Handle(ctx context.Context, params GenerateAPITokenParams) (Token, error) {
if params.ExpiresIn != nil && *params.ExpiresIn == 0 {
return "", ErrExpirationDurationMustBeGreaterThan0
}
if params.Wallet.Name == "" {
return "", ErrWalletNameIsRequired
}
if params.Wallet.Passphrase == "" {
return "", ErrWalletPassphraseIsRequired
}
if exist, err := h.walletStore.WalletExists(ctx, params.Wallet.Name); err != nil {
return "", fmt.Errorf("could not verify the wallet exists: %w", err)
} else if !exist {
return "", api.ErrWalletDoesNotExist
}
if err := h.walletStore.UnlockWallet(ctx, params.Wallet.Name, params.Wallet.Passphrase); err != nil {
return "", fmt.Errorf("could not unlock the wallet: %w", err)
}
if _, err := h.walletStore.GetWallet(ctx, params.Wallet.Name); err != nil {
return "", fmt.Errorf("could not retrieve the wallet: %w", err)
}
now := h.timeService.Now().Truncate(time.Second)
var expirationDate *time.Time
if params.ExpiresIn != nil {
ed := now.Add(*params.ExpiresIn).Truncate(time.Second)
expirationDate = &ed
}
tokenDescription := TokenDescription{
Description: params.Description,
Token: GenerateToken(),
CreationDate: now,
ExpirationDate: expirationDate,
Wallet: WalletCredentials{
Name: params.Wallet.Name,
Passphrase: params.Wallet.Passphrase,
},
}
if err := h.tokenStore.SaveToken(tokenDescription); err != nil {
return "", fmt.Errorf("could not save the newly generated token: %w", err)
}
return tokenDescription.Token, nil
}
func NewGenerateAPITokenHandler(
walletStore api.WalletStore,
tokenStore TokenStore,
timeService TimeService,
) *GenerateAPITokenHandler {
return &GenerateAPITokenHandler{
walletStore: walletStore,
tokenStore: tokenStore,
timeService: timeService,
}
}