forked from raystack/optimus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.go
59 lines (49 loc) · 1.26 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
package auth
import (
"context"
"github.com/goto/salt/log"
"github.com/goto/salt/oidc"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"github.com/goto/optimus/config"
)
type Auth struct {
logger log.Logger
cfg *oauth2.Config
}
func NewAuth(logger log.Logger, authConfig config.Auth) *Auth {
return &Auth{
logger: logger,
cfg: toAuthConfig(authConfig),
}
}
func (a Auth) GetToken(ctx context.Context) (*oauth2.Token, error) {
token, err := RetrieveFromKeyring(a.cfg.ClientID)
if err == nil {
return token, nil
}
token, err = a.getTokenFromServer(ctx, a.cfg)
if err == nil {
err = StoreInKeyring(a.cfg.ClientID, token)
if err != nil {
a.logger.Debug("not able to save token in keyring")
}
return token, nil
}
return nil, err
}
func (Auth) getTokenFromServer(ctx context.Context, cfg *oauth2.Config) (*oauth2.Token, error) {
source := oidc.NewTokenSource(ctx, cfg, cfg.ClientID)
return source.Token()
}
func toAuthConfig(authConfig config.Auth) *oauth2.Config {
callbackURL := "http://localhost:9090/auth/callback"
cfg := &oauth2.Config{
ClientID: authConfig.ClientID,
ClientSecret: authConfig.ClientSecret,
Endpoint: google.Endpoint,
RedirectURL: callbackURL,
Scopes: []string{"openid email"},
}
return cfg
}