-
Notifications
You must be signed in to change notification settings - Fork 0
/
tba.go
87 lines (78 loc) · 2.01 KB
/
tba.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
package netsuiteodbc
import (
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
"sync"
"time"
)
const nonceLength = 15
// NewConnectionStringer creates a new ConnectionStringer used for connecting to a NetSuite ODBC database with TBA
func NewConnectionStringer(config Config) *ConnectionStringer {
t := &ConnectionStringer{
config: config,
now: time.Now,
randBytes: rand.Reader,
}
t.params, t.err = connStringToParameterMap(config.ConnectionString)
return t
}
// ConnectionStringer implements unixodbc.ConnectionStringFactory, generating connection strings for connecting
// to a NetSuite ODBC database
type ConnectionStringer struct {
err error
config Config
params parameterMap
now func() time.Time
randBytes io.Reader
mu sync.Mutex
}
// ConnectionString generates a connection string with a dynamic token used for credentials
func (s *ConnectionStringer) ConnectionString(ctx context.Context) (string, error) {
if s.err != nil {
return "", s.err
}
token, err := s.Token()
if err != nil {
return "", err
}
params := parameterMap{
"UID": "TBA",
"PWD": token,
}
for k, v := range s.params {
params[k] = v
}
return params.String(), nil
}
func (s *ConnectionStringer) Nonce() (string, error) {
s.mu.Lock() // lock to prevent concurrent access to rand.Reader
defer s.mu.Unlock()
b := make([]byte, nonceLength)
if _, err := io.ReadFull(s.randBytes, b); err != nil {
return "", err
} else {
return base64.StdEncoding.EncodeToString(b), nil
}
}
func (s *ConnectionStringer) Token() (string, error) {
nonce, err := s.Nonce()
if err != nil {
return "", err
}
base := fmt.Sprintf("%s&%s&%s&%s&%d",
s.config.AccountId,
s.config.ConsumerKey,
s.config.TokenId,
nonce,
s.now().Unix())
secret := []byte(s.config.ConsumerSecret + "&" + s.config.TokenSecret)
h := hmac.New(sha256.New, secret)
h.Write([]byte(base))
signature := base64.StdEncoding.EncodeToString(h.Sum(nil))
return base + "&" + signature + "&HMAC-SHA256", nil
}