-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth_context.go
67 lines (58 loc) · 1.72 KB
/
auth_context.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
package main
import (
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
)
type authContext struct {
UID string
PrivateKey *rsa.PrivateKey
Password string
AuthEndpoint string
TokenEndpoint string
OAuthClientID string
OAuthClientSecret string
}
func fromPrincipalSecret(secret []byte) (*authContext, error) {
data := make(map[string]interface{})
if err := json.Unmarshal(secret, &data); err != nil {
return nil, err
}
uid := data["uid"].(string)
authEndpoint := data["login_endpoint"].(string)
if pk, ok := data["private_key"]; ok {
privateKey, _ := parsePrivateKey([]byte(pk.(string)))
return &authContext{UID: uid, PrivateKey: privateKey, AuthEndpoint: authEndpoint}, nil
} else if password, ok := data["password"]; ok {
return &authContext{UID: uid, Password: password.(string), AuthEndpoint: authEndpoint}, nil
}
return nil, nil
}
func fromPrivateKey(username string, pkBytes []byte, authEndpoint string) (*authContext, error) {
pk, err := parsePrivateKey(pkBytes)
if err != nil {
return nil, err
}
return &authContext{UID: username, PrivateKey: pk, AuthEndpoint: authEndpoint}, nil
}
func parsePrivateKey(key []byte) (*rsa.PrivateKey, error) {
var err error
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, errors.New("Failed to parse PEM private key")
}
var parsedKey interface{}
if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
return nil, err
}
}
var pk *rsa.PrivateKey
var ok bool
if pk, ok = parsedKey.(*rsa.PrivateKey); !ok {
return nil, errors.New("Failed to parse PEM private key")
}
return pk, nil
}