forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware_rate_limiting.go
65 lines (53 loc) · 1.83 KB
/
middleware_rate_limiting.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
package main
import "net/http"
import (
"github.com/Sirupsen/logrus"
"github.com/gorilla/context"
)
// RateLimitAndQuotaCheck will check the incomming request and key whether it is within it's quota and
// within it's rate limit, it makes use of the SessionLimiter object to do this
type RateLimitAndQuotaCheck struct {
TykMiddleware
}
// New creates a new HttpHandler for the alice middleware package
func (k RateLimitAndQuotaCheck) New() func(http.Handler) http.Handler {
aliceHandler := func(h http.Handler) http.Handler {
thisHandler := func(w http.ResponseWriter, r *http.Request) {
sessionLimiter := SessionLimiter{}
thisSessionState := context.Get(r, SessionData).(SessionState)
authHeaderValue := context.Get(r, AuthHeaderValue).(string)
forwardMessage, reason := sessionLimiter.ForwardMessage(&thisSessionState)
// Ensure quota and rate data for this session are recorded
authManager.UpdateSession(authHeaderValue, thisSessionState)
log.Debug("SessionState: ", thisSessionState)
if !forwardMessage {
// TODO Use an Enum!
if reason == 1 {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": r.RemoteAddr,
"key": authHeaderValue,
}).Info("Key rate limit exceeded.")
handler := ErrorHandler{k.TykMiddleware}
handler.HandleError(w, r, "Rate limit exceeded", 403)
return
} else if reason == 2 {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": r.RemoteAddr,
"key": authHeaderValue,
}).Info("Key quota limit exceeded.")
handler := ErrorHandler{k.TykMiddleware}
handler.HandleError(w, r, "Quota exceeded", 403)
return
}
// Other reason? Still not allowed
return
}
// Request is valid, carry on
h.ServeHTTP(w, r)
}
return http.HandlerFunc(thisHandler)
}
return aliceHandler
}