/
authentication.go
99 lines (85 loc) · 2 KB
/
authentication.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
95
96
97
98
99
package anypoint
import (
"time"
"github.com/Axway/agent-sdk/pkg/util/log"
)
// Auth represents the authentication information.
type Auth interface {
Stop()
GetToken() string
GetOrgID() string
}
// auth represents the authentication information.
type auth struct {
token string
user *User
client AuthClient
stopChan chan struct{}
}
// NewAuth creates a new authentication token
func NewAuth(client AuthClient) (Auth, error) {
a := &auth{
stopChan: make(chan struct{}),
}
token, user, lifetime, err := client.GetAccessToken()
if err != nil {
return nil, err
}
a.token = token
a.user = user
a.client = client
a.startRefreshToken(lifetime)
return a, nil
}
// Stop terminates the background access token refresh.
func (a *auth) Stop() {
a.stopChan <- struct{}{}
}
// startRefreshToken starts the background token refresh.
func (a *auth) startRefreshToken(lifetime time.Duration) {
if lifetime <= 0 {
return
}
// Refresh the token at 75% of lifetime and allow for changing interval
threshold := 0.75
interval := time.Duration(float64(lifetime.Nanoseconds()) * threshold)
timer := time.NewTimer(interval)
go func() {
for {
select {
case <-timer.C:
log.Debug("refreshing access token")
token, user, lifetime, err := a.client.GetAccessToken()
if err != nil {
// In an error scenario retry every 10 seconds
log.Error(err)
timer = time.NewTimer(10 * time.Second)
continue
}
a.token = token
a.user = user
if lifetime <= 0 {
break
} else {
interval = time.Duration(float64(lifetime.Nanoseconds()) * threshold)
timer = time.NewTimer(interval)
}
case <-a.stopChan:
log.Debug("stopping access token refresh")
timer.Stop()
break
}
}
}()
}
// GetToken returns the access token
func (a *auth) GetToken() string {
return a.token
}
// GetOrgID returns the organization ID of the currently authenticated user.
func (a *auth) GetOrgID() string {
if a.user != nil {
return a.user.Organization.ID
}
return ""
}