-
Notifications
You must be signed in to change notification settings - Fork 0
/
rester.go
394 lines (341 loc) · 11.1 KB
/
rester.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// Package rester used to define and compose multiple HTTP REST resources
// The package offers abstractions in order to construct your REST API
// in a friendly and maintainable way, yet offering the flexibility
// for a well more complex solution
package rester
import (
"context"
"errors"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"github.com/go-chi/chi"
"github.com/go-chi/cors"
"github.com/hoenirvili/rester/handler"
"github.com/hoenirvili/rester/permission"
"github.com/hoenirvili/rester/query"
"github.com/hoenirvili/rester/request"
"github.com/hoenirvili/rester/resource"
"github.com/hoenirvili/rester/response"
"github.com/hoenirvili/rester/route"
)
type config struct {
notfound http.HandlerFunc
methodnotallowed http.HandlerFunc
middleware struct {
global []middleware
validator middleware
}
resources map[string]Resource
}
func (c *config) setValidator(m middleware) {
c.middleware.validator = m
}
func (c *config) appendGlobal(m ...middleware) {
c.middleware.global = append(c.middleware.global, m...)
}
// Rester used for constructing and initializing the http router with routes
type Rester struct {
root chi.Router
options Options
config config
}
type middleware func(http.Handler) http.Handler
// New returns a new Rester http.Handler compatible that's ready
// to serve incoming http rest request
func New(opts ...Option) *Rester {
options := Options{
corsOptions: defaultCors,
}
for _, setter := range opts {
setter(&options)
}
r := &Rester{
root: chi.NewRouter(),
options: options,
config: config{
resources: make(map[string]Resource),
},
}
r.appendTokenMiddleware()
return r
}
func (r *Rester) appendTokenMiddleware() {
if r.options.validator == nil {
return
}
middleware := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
claims, err := r.options.validator.Verify(req)
if err != nil {
resp := response.Unauthorized(err.Error())
resp.Render(w)
return
}
p, ok := claims["permissions"]
if !ok {
resp := response.Unauthorized("No 'permissions' key found in the token")
resp.Render(w)
return
}
value, ok := p.(float64)
if !ok {
resp := response.Unauthorized("Invalid permission value")
resp.Render(w)
return
}
claims["permissions"] = permission.Permissions(value)
ctx := req.Context()
for key, value := range claims {
ctx = context.WithValue(ctx, key, value)
}
req = req.WithContext(ctx)
next.ServeHTTP(w, req)
})
}
r.config.setValidator(middleware)
}
func guard(in permission.Permissions, on permission.Permissions) bool {
return in&on != 0
}
// Option defines a setter callback type to set an underlying option value
type Option func(opt *Options)
// Options type holding all underlying options for the rester api
type Options struct {
// validator used for token validation and extraction
validator TokenValidator
// version adds the the api version as the base route
version string
// global middlwares holds a list of middlewares that will
// be used in front of all routes
globalMiddlewares middleware
// corsOptions holds a series of options for setting up cors
corsOptions cors.Options
}
// WithCustomCors set's a custom set of cors for the server
func WithCustomCors(options cors.Options) Option {
return func(opts *Options) { opts.corsOptions = options }
}
var defaultCors = cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
ExposedHeaders: []string{"Link"}, // TODO: maybe remove this
MaxAge: 300, // Maximum value not ignored by any of major browsers
}
// TokenValidator defines ways of interactions with the token
type TokenValidator interface {
// Verify verifies if the request contains the desired token
// This also can verify the expiration time or other claims
// With success this will return the validated claims
Verify(r *http.Request) (map[string]interface{}, error)
}
// WithTokenValidator sets the underlying token validation implementation
// to use to validate and extract token meta-data information to authorize and
// authenticate the
func WithTokenValidator(t TokenValidator) Option {
return func(opts *Options) { opts.validator = t }
}
// WithVersioning appends to the path route the prefix "/version/"
func WithVersioning(version string) Option {
return func(opts *Options) { opts.version = "/" + version }
}
// NotFound defines a handler to respond whenever a route could not be found
func (r *Rester) NotFound(h handler.Handler) {
// append into middleware stack
r.config.notfound = httphandler(h, nil)
}
// UseGlobalMiddleware appends the list of middlewares into the global
// middleware stack to be put in front of every request emitted to the api
func (r *Rester) UseGlobalMiddleware(m ...middleware) {
r.config.appendGlobal(m...)
}
// MethodNotAllowed defines a handler to respond whenever a method is
// not allowed on a route
func (r *Rester) MethodNotAllowed(h handler.Handler) {
// append into middleware stack
r.config.methodnotallowed = httphandler(h, nil)
}
// ServeHTTP based on the incoming request route it to the available resource handler
func (r *Rester) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.root.ServeHTTP(w, req)
}
// Resource defines a way of composing routes into a resource
type Resource interface {
// Routes returns a list of sub-routes of the given resource
Routes() route.Routes
}
// checkPermission checks if the value with the key permission exists and if
// it passes the guard check
func checkPermission(allow permission.Permissions, req request.Request) error {
in := req.Request.Context().Value("permissions").(permission.Permissions)
if !guard(in, allow) {
return errors.New("you don't have permission to access this resource")
}
return nil
}
func (r *Rester) validRoute(route route.Route) {
if route.Handler == nil {
panic("Cannot use a nil handler")
}
if route.URL == "" {
panic("Cannot use an empty URL route")
}
}
func serveFiles(r chi.Router, path string, root http.FileSystem) {
if strings.ContainsAny(path, "{}*") {
panic("serving files does not permit URL parameters")
}
fs := http.StripPrefix(path, http.FileServer(root))
if path != "/" && path[len(path)-1] != '/' {
r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
path += "/"
}
path += "*"
r.Get(path, http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
fs.ServeHTTP(w, r)
},
))
}
// Static serve static files from the location pointed by dir
// This has limited support so don't expect much customization
func (r *Rester) Static(dir string) {
r.root.Group(func(g chi.Router) {
serveFiles(g, "/", http.Dir(dir))
})
}
func (r *Rester) StaticSpa(dir string) {
r.root.Group(func(g chi.Router) {
staticSpaFile(g, "/", dir)
})
}
func staticSpaFile(r chi.Router, public string, static string) {
if strings.ContainsAny(public, "{}*") {
panic("FileServer does not permit URL parameters.")
}
root, _ := filepath.Abs(static)
if _, err := os.Stat(root); os.IsNotExist(err) {
panic("Static Documents Directory Not Found")
}
fs := http.StripPrefix(public, http.FileServer(http.Dir(root)))
if public != "/" && public[len(public)-1] != '/' {
r.Get(public, http.RedirectHandler(public+"/", 301).ServeHTTP)
public += "/"
}
// Register the Get request for the specified path, most likely /*
r.Get(public+"*", func(w http.ResponseWriter, r *http.Request) {
file := strings.Replace(r.RequestURI, public, "/", 1)
// if the requested resource was not found, pass the request to the client
if _, err := os.Stat(root + file); os.IsNotExist(err) {
http.ServeFile(w, r, path.Join(root, "index.html"))
return
}
// if the requested resource was found, serve it
fs.ServeHTTP(w, r)
})
}
// Build builds the internal state of the router making it ready for
// dispatching requests
func (r *Rester) Build() {
r.root.Group(func(g chi.Router) {
if r.options.version == "" {
r.options.version = "/"
}
g.Route(r.options.version, func(router chi.Router) {
router.NotFound(r.config.notfound)
router.MethodNotAllowed(r.config.methodnotallowed)
for _, middleware := range r.config.middleware.global {
router.Use(middleware)
}
router.Use(cors.New(r.options.corsOptions).Handler)
for path, resource := range r.config.resources {
r.resource(router, path, resource)
}
})
})
}
func allowAllRequests(permission.Permissions, request.Request) error { return nil }
func (r *Rester) decideWhichPermissionFunction(p permission.Permissions) func(permission.Permissions, request.Request) error {
fn := allowAllRequests
if p == permission.Anonymous {
return fn
}
// if we did specify a token validation schema, proceed with checking
// the permission return by the validation process in the context
if r.options.validator != nil {
fn = checkPermission
}
return fn
}
type makeHandlerConfig struct {
isRequestAllowed func(permission.Permissions, request.Request) error
route route.Route
}
func makeHandler(c makeHandlerConfig) handler.Handler {
return handler.Handler(func(req request.Request) resource.Response {
if err := c.isRequestAllowed(c.route.Allow, req); err != nil {
return response.Forbidden(err.Error())
}
values := req.URL.Query()
pairs := req.Pairs()
for key := range pairs {
if pairs[key].Required {
if err := pairs.Parse(key, values); err != nil {
return response.BadRequest(err.Error())
}
}
}
return c.route.Handler(req)
})
}
func (r *Rester) resource(g chi.Router, base string, res Resource) {
g.Route(base, func(router chi.Router) {
routes := res.Routes()
for _, route := range routes {
r.validRoute(route)
if route.Allow == 0 {
route.Allow = permission.Anonymous
}
h := makeHandler(makeHandlerConfig{
isRequestAllowed: r.decideWhichPermissionFunction(route.Allow),
route: route,
})
r.method(router, route, h)
}
})
}
func (r *Rester) method(router chi.Router, route route.Route, h handler.Handler) {
switch route.Allow {
case permission.Anonymous:
router.With(route.Middlewares...).MethodFunc(route.Method, route.URL, httphandler(h, route.QueryPairs))
return
default:
if r.options.validator != nil {
router.With(r.config.middleware.validator).
With(route.Middlewares...).
MethodFunc(route.Method, route.URL, httphandler(h, route.QueryPairs))
return
}
router.With(route.Middlewares...).MethodFunc(route.Method, route.URL, httphandler(h, route.QueryPairs))
}
}
// Resource initializes a resource with the all available sub-routes of the resource
func (r *Rester) Resource(base string, resource Resource) {
if _, ok := r.config.resources[base]; ok {
panic("cannot append the same resource " + base + "twice")
}
r.config.resources[base] = resource
}
func httphandler(h handler.Handler, pairs query.Pairs) http.HandlerFunc {
if h == nil {
panic("no handler given for the route")
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
req := request.New(r, pairs)
response := h(req)
response.Render(w)
})
}