-
Notifications
You must be signed in to change notification settings - Fork 2
/
token.go
57 lines (46 loc) · 1.12 KB
/
token.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
package apiserver
import (
"net/http"
"strings"
)
const (
BearerToken = "BearerToken"
ServiceAccountToken = "ServiceAccountToken"
)
type Token struct {
Value string
Type string
}
type MissingToken struct{}
func (e MissingToken) Error() string {
return AuthError("missing").Error()
}
func getBearerToken(header string) (*Token, error) {
parts := strings.Split(header, " ")
if len(parts) != 2 {
return nil, AuthError("bearer.invalid")
}
if parts[0] != "Bearer" {
return nil, AuthInvalidTypeError
}
return &Token{parts[1], BearerToken}, nil
}
func getApiToken(apiKey string) (*Token, error) {
return &Token{apiKey, ServiceAccountToken}, nil
}
func GetAuthToken(req *http.Request) (*Token, error) {
authorizationHeader := req.Header.Get("Authorization")
if authorizationHeader != "" {
return getBearerToken(authorizationHeader)
}
apiKey := req.Header.Get("X-API-Key")
if apiKey != "" {
return getApiToken(apiKey)
}
// Temporarily allow sending token via query parameter
token := req.URL.Query().Get("token")
if token != "" {
return getBearerToken("Bearer " + token)
}
return nil, &MissingToken{}
}