This repository was archived by the owner on May 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
78 lines (69 loc) · 1.93 KB
/
middleware.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
package main
import (
"encoding/json"
"log"
"net/http"
"strings"
"golang.org/x/time/rate"
"securecodewarrior.com/ddias/heapoverflow/jwt"
)
type limit struct {
*rate.Limiter
}
func (l *limit) toLimit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !l.Allow() {
http.Error(w, "Rate limiting", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
func middleJSONLogger(fn appHandler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
toEncode := map[string]interface{}{}
w.Header().Set("Content-Type", "application/json")
payload := jwt.DecodePayload(r)
resp, err := fn(w, r)
if err != nil {
toEncode["error"] = err.Error()
toEncode["result"] = nil
w.WriteHeader(http.StatusInternalServerError)
log.Printf("E: %s %s %s %+v %s\n", r.RemoteAddr, r.Method,
r.URL.Path, err, payload.Email)
} else {
toEncode["result"] = resp
log.Printf("C: %s %s %s %s\n", r.RemoteAddr, r.Method, r.URL.Path,
payload.Email)
}
json.NewEncoder(w).Encode(toEncode)
})
}
func (app *app) Validate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if app.isPublic(r) || staticWhiteList(app.staticDir, r.URL.Path) {
next.ServeHTTP(w, r)
return
}
header := r.Header.Get("Authorization")
if header == "" {
http.Error(w, "Missing JWT", http.StatusInternalServerError)
return
}
if !strings.HasPrefix(header, "Bearer ") {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
rawToken := header[len("Bearer "):]
token := jwt.NewFromFile(jwt.Payload{}, app.jwtKeyFile)
if err := token.Decode(rawToken); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := token.Check(); err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}