forked from SSHcom/privx-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
opts.go
121 lines (103 loc) · 2.53 KB
/
opts.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//
// Copyright (c) 2020 SSH Communications Security Inc.
//
// All rights reserved.
//
package oauth
import (
"encoding/base64"
"io"
"os"
"github.com/BurntSushi/toml"
)
// Option is configuration applied to the client
type Option func(*tAuth) *tAuth
// Access setups client access key
func Access(access string) Option {
return func(auth *tAuth) *tAuth {
if access != "" {
auth.access = access
}
return auth
}
}
// Secret setups clients secret key
func Secret(secret string) Option {
return func(auth *tAuth) *tAuth {
if secret != "" {
auth.secret = secret
}
return auth
}
}
// Digest setups client secret digest
func Digest(oauthAccess, oauthSecret string) Option {
return func(auth *tAuth) *tAuth {
if oauthAccess != "" && oauthSecret != "" {
auth.digest = base64.StdEncoding.EncodeToString([]byte(oauthAccess + ":" + oauthSecret))
}
return auth
}
}
// UseConfigFile setup credential from tol file
func UseConfigFile(path string) Option {
return func(auth *tAuth) *tAuth {
type config struct {
AuthClientID string `toml:"oauth_client_id"`
AuthClientSecret string `toml:"oauth_client_secret"`
ClientID string `toml:"api_client_id"`
ClientSecret string `toml:"api_client_secret"`
}
var file struct {
Auth config
}
if path == "" {
return auth
}
f, err := os.Open(path)
if err != nil {
panic(err)
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
panic(err)
}
if err = toml.Unmarshal(data, &file); err != nil {
panic(err)
}
auth = Access(file.Auth.ClientID)(auth)
auth = Secret(file.Auth.ClientSecret)(auth)
auth = Digest(file.Auth.AuthClientID, file.Auth.AuthClientSecret)(auth)
return auth
}
}
// UseEnvironment setup credential from environment variables
func UseEnvironment() Option {
return func(auth *tAuth) *tAuth {
if access, ok := os.LookupEnv("PRIVX_API_CLIENT_ID"); ok {
auth = Access(access)(auth)
}
if access, ok := os.LookupEnv("PRIVX_API_ACCESS_KEY"); ok {
auth = Access(access)(auth)
}
if secret, ok := os.LookupEnv("PRIVX_API_CLIENT_SECRET"); ok {
auth = Secret(secret)(auth)
}
if secret, ok := os.LookupEnv("PRIVX_API_SECRET_KEY"); ok {
auth = Secret(secret)(auth)
}
if authAccess, ok := os.LookupEnv("PRIVX_API_OAUTH_CLIENT_ID"); ok {
if authSecret, ok := os.LookupEnv("PRIVX_API_OAUTH_CLIENT_SECRET"); ok {
auth = Digest(authAccess, authSecret)(auth)
}
}
return auth
}
}
func UseCookies() Option {
return func(auth *tAuth) *tAuth {
auth.useCookies = true
return auth
}
}