-
Notifications
You must be signed in to change notification settings - Fork 787
/
user_auth.go
61 lines (52 loc) · 1.44 KB
/
user_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
package auth
import (
"os"
"strings"
)
const (
usernameSuffix = "_USERNAME"
apiTokenSuffix = "_API_TOKEN"
bearerTokenSuffix = "_BEARER_TOKEN"
DefaultUsername = "dummy"
)
// UsernameEnv builds the username environment variable name
func UsernameEnv(prefix string) string {
prefix = strings.ToUpper(prefix)
return prefix + usernameSuffix
}
// ApiTokenEnv builds the api token environment variable name
func ApiTokenEnv(prefix string) string {
prefix = strings.ToUpper(prefix)
return prefix + apiTokenSuffix
}
// BearerTokenEnv builds the bearer token environment variable name
func BearerTokenEnv(prefix string) string {
prefix = strings.ToUpper(prefix)
return prefix + bearerTokenSuffix
}
// CreateAuthUserFromEnvironment creates a user auth from environment variables
func CreateAuthUserFromEnvironment(prefix string) UserAuth {
user := UserAuth{}
username, set := os.LookupEnv(UsernameEnv(prefix))
if set {
user.Username = username
}
apiToken, set := os.LookupEnv(ApiTokenEnv(prefix))
if set {
user.ApiToken = apiToken
}
bearerToken, set := os.LookupEnv(BearerTokenEnv(prefix))
if set {
user.BearerToken = bearerToken
}
if user.ApiToken != "" || user.Password != "" {
if user.Username == "" {
user.Username = DefaultUsername
}
}
return user
}
// IsInvalid returns true if the user auth has a valid token
func (a *UserAuth) IsInvalid() bool {
return a.BearerToken == "" && (a.ApiToken == "" || a.Username == "")
}