-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathaccess.go
227 lines (185 loc) · 4.94 KB
/
access.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package access
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/boltdb/bolt"
"github.com/nilslice/jwt"
"github.com/ponzu-cms/ponzu/system/admin/user"
"github.com/ponzu-cms/ponzu/system/db"
)
const (
apiAccessStore = "__apiAccess"
apiAccessCookie = "_apiAccessToken"
)
// APIAccess is the data for an API access grant
type APIAccess struct {
Key string `json:"key"`
Hash string `json:"hash"`
Salt string `json:"salt"`
Token string `json:"token"`
}
// Config contains settings for token creation and validation
type Config struct {
ExpireAfter time.Duration
ResponseWriter http.ResponseWriter
TokenStore reqHeaderOrHTTPCookie
CustomClaims map[string]interface{}
SecureCookie bool
}
type reqHeaderOrHTTPCookie interface{}
func init() {
db.AddBucket(apiAccessStore)
}
// Grant creates a new APIAccess and saves it to the __apiAccess bucket in the database
// and if an existing APIAccess grant is encountered in the database, Grant attempts
// to update the grant but will fail if unauthorized
func Grant(key, password string, cfg *Config) (*APIAccess, error) {
if key == "" {
return nil, fmt.Errorf("%s", "key must not be empty")
}
if password == "" {
return nil, fmt.Errorf("%s", "password must not be empty")
}
u, err := user.New(key, password)
if err != nil {
return nil, err
}
apiAccess := &APIAccess{
Key: u.Email,
Hash: u.Hash,
Salt: u.Salt,
}
err = apiAccess.setToken(cfg)
if err != nil {
return nil, err
}
err = db.Store().Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(apiAccessStore))
if b == nil {
return fmt.Errorf("failed to get bucket %s", apiAccessStore)
}
if b.Get([]byte(apiAccess.Key)) != nil {
err := updateGrant(key, password, cfg)
if err != nil {
return fmt.Errorf("failed to update APIAccess grant for %s, %v", apiAccess.Key, err)
}
}
j, err := json.Marshal(u)
if err != nil {
return fmt.Errorf("failed to marshal APIAccess to json, %v", err)
}
return b.Put([]byte(apiAccess.Key), j)
})
if err != nil {
return nil, err
}
return apiAccess, nil
}
// IsGranted checks if the user request is authenticated by the token held within
// the provided tokenStore (should be a http.Cookie or http.Header)
func IsGranted(req *http.Request, tokenStore reqHeaderOrHTTPCookie) bool {
token, err := getToken(req, tokenStore)
if err != nil {
log.Println("failed to get token to check API access grant")
return false
}
return jwt.Passes(token)
}
// IsOwner validates the access token and checks the claims within the
// authenticated request's JWT for the key key associated with the grant.
func IsOwner(req *http.Request, tokenStore reqHeaderOrHTTPCookie, key string) bool {
token, err := getToken(req, tokenStore)
if err != nil {
log.Println("failed to get token to check API access owner")
return false
}
if !jwt.Passes(token) {
return false
}
claims := jwt.GetClaims(token)
if claims["access"].(string) != key {
return false
}
return true
}
func updateGrant(key, password string, cfg *Config) error {
var apiAccess APIAccess
err := db.Store().View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(apiAccessStore))
if b == nil {
return fmt.Errorf("failed to get %s bucket to update grant", apiAccessStore)
}
j := b.Get([]byte(key))
return json.Unmarshal(j, &apiAccess)
})
if err != nil {
return fmt.Errorf("failed to get access grant to update grant, %v", err)
}
usr := &user.User{
Email: apiAccess.Key,
Hash: apiAccess.Hash,
Salt: apiAccess.Salt,
}
if !user.IsUser(usr, password) {
return fmt.Errorf(
"unauthorized attempt to update grant for %s", apiAccess.Key,
)
}
return nil
}
func getToken(req *http.Request, tokenStore reqHeaderOrHTTPCookie) (string, error) {
switch tokenStore.(type) {
case http.Cookie:
cookie, err := req.Cookie(apiAccessCookie)
if err != nil {
return "", err
}
return cookie.Value, nil
case http.Header:
bearer := req.Header.Get("Authorization")
return strings.TrimPrefix(bearer, "Bearer "), nil
default:
return "", fmt.Errorf("%s", "unrecognized token store")
}
}
func (a *APIAccess) setToken(cfg *Config) error {
exp := time.Now().Add(cfg.ExpireAfter)
claims := map[string]interface{}{
"exp": exp.Unix(),
"access": a.Key,
}
for k, v := range cfg.CustomClaims {
if _, ok := claims[k]; ok {
return fmt.Errorf(
"custom Config claim [%s] collides with internal claim [%s], %s",
k, k, "please rename custom claim",
)
}
claims[k] = v
}
token, err := jwt.New(claims)
if err != nil {
return err
}
a.Token = token
switch cfg.TokenStore.(type) {
case http.Header:
cfg.ResponseWriter.Header().Add("Authorization", "Bearer "+token)
case http.Cookie:
http.SetCookie(cfg.ResponseWriter, &http.Cookie{
Name: apiAccessCookie,
Value: token,
Expires: exp,
Path: "/",
HttpOnly: true,
Secure: cfg.SecureCookie,
})
default:
return fmt.Errorf("%s", "unrecognized token store")
}
return nil
}