forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
access_token.go
60 lines (48 loc) · 1.06 KB
/
access_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
58
59
60
package coreconfig
import (
"encoding/base64"
"encoding/json"
"strings"
)
type TokenInfo struct {
Username string `json:"user_name"`
Email string `json:"email"`
UserGUID string `json:"user_id"`
}
func NewTokenInfo(accessToken string) (info TokenInfo) {
tokenJSON, err := DecodeAccessToken(accessToken)
if err != nil {
return TokenInfo{}
}
info = TokenInfo{}
err = json.Unmarshal(tokenJSON, &info)
if err != nil {
return TokenInfo{}
}
return info
}
func DecodeAccessToken(accessToken string) (tokenJSON []byte, err error) {
tokenParts := strings.Split(accessToken, " ")
if len(tokenParts) < 2 {
return
}
token := tokenParts[1]
encodedParts := strings.Split(token, ".")
if len(encodedParts) < 3 {
return
}
encodedTokenJSON := encodedParts[1]
return base64Decode(encodedTokenJSON)
}
func base64Decode(encodedData string) ([]byte, error) {
return base64.StdEncoding.DecodeString(restorePadding(encodedData))
}
func restorePadding(seg string) string {
switch len(seg) % 4 {
case 2:
seg = seg + "=="
case 3:
seg = seg + "="
}
return seg
}