forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware_key_exists.go
66 lines (53 loc) · 1.75 KB
/
middleware_key_exists.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
package main
import "net/http"
import (
"github.com/Sirupsen/logrus"
"github.com/gorilla/context"
)
// KeyExists will check if the key being used to access the API is in the request data,
// and then if the key is in the storage engine
type KeyExists struct {
TykMiddleware
}
// New creates a new HttpHandler for the alice middleware package
func (k KeyExists) New() func(http.Handler) http.Handler {
aliceHandler := func(h http.Handler) http.Handler {
thisHandler := func(w http.ResponseWriter, r *http.Request) {
if k.Spec.UseOauth2 {
// Skip this step and let Oauth2 Handler do it's thing
h.ServeHTTP(w, r)
return
}
authHeaderValue := r.Header.Get(k.Spec.APIDefinition.Auth.AuthHeaderName)
if authHeaderValue == "" {
// No header value, fail
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": r.RemoteAddr,
}).Info("Attempted access with malformed header, no auth header found.")
handler := ErrorHandler{k.TykMiddleware}
handler.HandleError(w, r, "Authorisation field missing", 400)
return
}
// Check if API key valid
keyExists, thisSessionState := authManager.IsKeyAuthorised(authHeaderValue)
if !keyExists {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": r.RemoteAddr,
"key": authHeaderValue,
}).Info("Attempted access with non-existent key.")
handler := ErrorHandler{k.TykMiddleware}
handler.HandleError(w, r, "Key not authorised", 403)
return
}
// Set session state on context, we will need it later
context.Set(r, SessionData, thisSessionState)
context.Set(r, AuthHeaderValue, authHeaderValue)
// Request is valid, carry on
h.ServeHTTP(w, r)
}
return http.HandlerFunc(thisHandler)
}
return aliceHandler
}