forked from remind101/empire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
access_tokens.go
117 lines (93 loc) · 2.42 KB
/
access_tokens.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
package empire
import (
"errors"
"github.com/dgrijalva/jwt-go"
)
// AccessToken represents a token that allow access to the api.
type AccessToken struct {
Token string
User *User
}
type accessTokensService struct {
Secret []byte // Secret used to sign jwt tokens.
}
// AccessTokensCreate "creates" the token by jwt signing it and setting the
// Token value.
func (s *accessTokensService) AccessTokensCreate(token *AccessToken) (*AccessToken, error) {
signed, err := SignToken(s.Secret, token)
if err != nil {
return token, err
}
token.Token = signed
return token, nil
}
func (s *accessTokensService) AccessTokensFind(token string) (*AccessToken, error) {
at, err := ParseToken(s.Secret, token)
if err != nil {
switch err.(type) {
case *jwt.ValidationError:
return nil, nil
default:
return at, err
}
}
if at != nil {
at.Token = token
}
return at, nil
}
// SignToken jwt signs the token and adds the signature to the Token field.
func SignToken(secret []byte, token *AccessToken) (string, error) {
t := accessTokenToJwt(token)
return t.SignedString(secret)
}
// ParseToken parses a string token, verifies it, and returns an AccessToken
// instance.
func ParseToken(secret []byte, token string) (*AccessToken, error) {
t, err := jwtParse(secret, token)
if err != nil {
return nil, err
}
if !t.Valid {
return nil, nil
}
return jwtToAccessToken(t)
}
func accessTokenToJwt(token *AccessToken) *jwt.Token {
t := jwt.New(jwt.SigningMethodHS256)
t.Claims["User"] = struct {
Name string
GitHubToken string
}{
Name: token.User.Name,
GitHubToken: token.User.GitHubToken,
}
return t
}
// jwtToAccessTokens maps a jwt.Token to an AccessToken.
func jwtToAccessToken(t *jwt.Token) (*AccessToken, error) {
var token AccessToken
// TODO Should probably return an error here if a user isn't present.
if u, ok := t.Claims["User"].(map[string]interface{}); ok {
var user User
if n, ok := u["Name"].(string); ok {
user.Name = n
} else {
return &token, errors.New("missing name")
}
if gt, ok := u["GitHubToken"].(string); ok {
user.GitHubToken = gt
} else {
return &token, errors.New("missing github token")
}
token.User = &user
} else {
return &token, errors.New("missing user")
}
return &token, nil
}
func jwtParse(secret []byte, token string) (*jwt.Token, error) {
return jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
return secret, nil
})
}