-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
auth.go
81 lines (66 loc) · 1.72 KB
/
auth.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
package auth
import (
"fmt"
"time"
"github.com/micro/go-micro/v2/auth"
"github.com/micro/go-micro/v2/logger"
)
// Generate generates a service account for and continually
// refreshes the access token.
func Generate(id string, name string, a auth.Auth) error {
// extract the account creds from options, these can be set by flags
accID := a.Options().ID
accSecret := a.Options().Secret
// if no credentials were provided, generate an account
if len(accID) == 0 || len(accSecret) == 0 {
name := fmt.Sprintf("%v-%v", name, id)
opts := []auth.GenerateOption{
auth.WithType("service"),
auth.WithScopes("service"),
}
acc, err := a.Generate(name, opts...)
if err != nil {
return err
}
logger.Debugf("Auth [%v] Authenticated as %v issued by %v", a, name, acc.Issuer)
accID = acc.ID
accSecret = acc.Secret
}
// generate the first token
token, err := a.Token(
auth.WithCredentials(accID, accSecret),
auth.WithExpiry(time.Minute*10),
)
if err != nil {
return err
}
// set the credentials and token in auth options
a.Init(
auth.ClientToken(token),
auth.Credentials(accID, accSecret),
)
// periodically check to see if the token needs refreshing
go func() {
timer := time.NewTicker(time.Second * 15)
for {
<-timer.C
// don't refresh the token if it's not close to expiring
tok := a.Options().Token
if tok.Expiry.Unix() > time.Now().Add(time.Minute).Unix() {
continue
}
// generate the first token
tok, err := a.Token(
auth.WithToken(tok.RefreshToken),
auth.WithExpiry(time.Minute*10),
)
if err != nil {
logger.Warnf("[Auth] Error refreshing token: %v", err)
continue
}
// set the token
a.Init(auth.ClientToken(tok))
}
}()
return nil
}