forked from prest/middlewares
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middlewares.go
81 lines (71 loc) · 2.2 KB
/
middlewares.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
package middlewares
import (
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"github.com/auth0/go-jwt-middleware"
"github.com/dgrijalva/jwt-go"
"github.com/prest/adapters/postgres"
"github.com/urfave/negroni"
)
// HandlerSet add content type header
func HandlerSet() negroni.Handler {
return negroni.HandlerFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
format := r.URL.Query().Get("_renderer")
recorder := httptest.NewRecorder()
negroniResp := negroni.NewResponseWriter(recorder)
next(negroniResp, r)
renderFormat(w, recorder, format)
})
}
// AccessControl is a middleware to handle permissions on tables in pREST
func AccessControl() negroni.Handler {
return negroni.HandlerFunc(func(rw http.ResponseWriter, rq *http.Request, next http.HandlerFunc) {
mapPath := getVars(rq.URL.Path)
if mapPath == nil {
next(rw, rq)
return
}
permission := permissionByMethod(rq.Method)
if permission == "" {
next(rw, rq)
return
}
if postgres.TablePermissions(mapPath["table"], permission) {
next(rw, rq)
return
}
err := fmt.Errorf("required authorization to table %s", mapPath["table"])
http.Error(rw, err.Error(), http.StatusUnauthorized)
})
}
// JwtMiddleware check if actual request have JWT
func JwtMiddleware(key string) negroni.Handler {
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte(key), nil
},
SigningMethod: jwt.SigningMethodHS256,
})
return negroni.HandlerFunc(jwtMiddleware.HandlerWithNext)
}
// Cors middleware
func Cors(origin []string, headers []string) negroni.Handler {
return negroni.HandlerFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
w.Header().Set(headerAllowOrigin, strings.Join(origin, ","))
w.Header().Set(headerAllowMethods, strings.Join(defaultAllowMethods, ","))
w.Header().Set(headerAllowHeaders, strings.Join(headers, ","))
w.Header().Set(headerAllowCredentials, strconv.FormatBool(true))
if allowed := checkCors(r, origin); !allowed {
w.WriteHeader(http.StatusForbidden)
return
}
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next(w, r)
})
}