-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathauth.go
More file actions
66 lines (55 loc) · 1.64 KB
/
auth.go
File metadata and controls
66 lines (55 loc) · 1.64 KB
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
package auth
import (
"context"
"errors"
"fmt"
"github.com/99designs/keyring"
"github.com/localstack/lstk/internal/api"
"github.com/localstack/lstk/internal/env"
"github.com/localstack/lstk/internal/output"
)
type Auth struct {
tokenStorage AuthTokenStorage
login LoginProvider
sink output.Sink
allowLogin bool
}
func New(sink output.Sink, platform api.PlatformAPI, storage AuthTokenStorage, allowLogin bool) *Auth {
return &Auth{
tokenStorage: storage,
login: newLoginProvider(sink, platform),
sink: sink,
allowLogin: allowLogin,
}
}
// GetToken tries in order: 1) keyring 2) LOCALSTACK_AUTH_TOKEN env var 3) device flow login
func (a *Auth) GetToken(ctx context.Context) (string, error) {
if token, err := a.tokenStorage.GetAuthToken(); err == nil && token != "" {
return token, nil
}
if token := env.Vars.AuthToken; token != "" {
return token, nil
}
if !a.allowLogin {
return "", fmt.Errorf("authentication required: set LOCALSTACK_AUTH_TOKEN or run in interactive mode")
}
output.EmitInfo(a.sink, "No existing credentials found. Please log in:")
token, err := a.login.Login(ctx)
if err != nil {
output.EmitWarning(a.sink, "Authentication failed.")
return "", err
}
if err := a.tokenStorage.SetAuthToken(token); err != nil {
output.EmitWarning(a.sink, fmt.Sprintf("could not store token in keyring: %v", err))
}
output.EmitSuccess(a.sink, "Login successful.")
return token, nil
}
// Logout removes the stored auth token from the keyring
func (a *Auth) Logout() error {
err := a.tokenStorage.DeleteAuthToken()
if errors.Is(err, keyring.ErrKeyNotFound) {
return nil
}
return err
}