/
middleware.go
326 lines (273 loc) · 11.9 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
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
package main
import (
"errors"
"expvar"
"fmt"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/felixge/httpsnoop"
"github.com/tomasen/realip"
"golang.org/x/time/rate"
"github.com/sum28it/green-light/internal/data"
"github.com/sum28it/green-light/internal/validator"
)
// recoverPanic is middleware that recovers from a panic by responding with a 500 Internal Server
// Error before closing the connection. It will also log the error using our custom Logger at
// the ERROR level.
func (app *application) recoverPanic(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Create a deferred function (which will always be run in the event of a panic as
// Go unwinds the stack).
defer func() {
// Use the builtin recover function to check if there has been a panic or not.
if err := recover(); err != nil {
// If there was a panic, set a "Connection: close" header on the response. This
// acts a trigger to make Go's HTTP server automatically close the current
// connection after a response has been sent.
w.Header().Set("Connection:", "close")
// The value returned by recover() has the type interface{}, so we use
// fmt.Errorf() to normalize it into an error and call our
// serverErrorResponse() helper. In turn, this will log the error using our
// custom Logger type at the ERROR level and send the client a
// 500 Internal Server Error response.
app.serverErrorResponse(w, r, fmt.Errorf("%s", err))
}
}()
next.ServeHTTP(w, r)
})
}
func (app *application) rateLimit(next http.Handler) http.Handler {
// Define a client struct to hold the rate limiter and last seen time for reach client
type client struct {
limiter *rate.Limiter
lastSeen time.Time
}
// Declare a mutex and a map to hold pointers to a client struct.
var (
mu sync.Mutex
clients = make(map[string]*client)
)
// Launch a background goroutine which removes old entries from the clients map once every
// minute.
go func() {
for {
time.Sleep(time.Minute)
// Lock the mutex to prevent any rate limiter checks from happening while the cleanup
// is taking place.
mu.Lock()
// Loop through all clients. if they haven't been seen within the last three minutes,
// then delete the corresponding entry from the clients map.
for ip, client := range clients {
if time.Since(client.lastSeen) > 3*time.Minute {
delete(clients, ip)
}
}
// Importantly, unlock the mutex when the cleanup is complete.
mu.Unlock()
}
}()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Only carry out the check if rate limited is enabled.
if app.config.limiter.enabled {
// Use the realip.FromRequest function to get the client's real IP address.
ip := realip.FromRequest(r)
// Lock the mutex to prevent this code from being executed concurrently.
mu.Lock()
// Check to see if the IP address already exists in the map. If it doesn't,
// then initialize a new rate limiter and add the IP address and limiter to the map.
if _, found := clients[ip]; !found {
// Use the requests-per-second and burst values from the app.config struct.
clients[ip] = &client{
limiter: rate.NewLimiter(rate.Limit(app.config.limiter.rps), app.config.limiter.burst)}
}
// Update the last seen time for the client.
clients[ip].lastSeen = time.Now()
// Call the limiter.Allow() method on the rate limiter for the current IP address.
// If the request isn't allowed, unlock the mutex and send a 429 Too Many Requests
// response.
if !clients[ip].limiter.Allow() {
mu.Unlock()
app.rateLimitExceededResponse(w, r)
return
}
// Very importantly, unlock the mutex before calling the next handler in the chain.
// Notice that we DON'T use defer to unlock the mutex, as that would mean that the mutex
// isn't unlocked until all handlers downstream of this middleware have also returned.
mu.Unlock()
}
next.ServeHTTP(w, r)
})
}
func (app *application) authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Add the "Vary: Authorization" header to the response. This indicates to any caches
// that the response may vary based on the value of the Authorization header in the request.
w.Header().Set("Vary", "Authorization")
// Retrieve the value of the Authorization header from teh request. This will return the
// empty string "" if there is no such header found.
authorizationHeader := r.Header.Get("Authorization")
// If there is no Authorization header found, use the contextSetUser() helper to add
// an AnonymousUser to the request context. Then we call the next handler in the chain
// and return without executing any of the code below.
if authorizationHeader == "" {
r = app.contextSetUser(r, data.AnonymousUser)
next.ServeHTTP(w, r)
return
}
// Otherwise, we expect the value of the Authorization header to be in the format
// "Bearer <token>". We try to split this into its constituent parts, and if the header
// isn't in the expected format we return a 401 Unauthorized response using the
// invalidAuthenticationTokenResponse helper.
headerParts := strings.Split(authorizationHeader, " ")
if len(headerParts) != 2 || headerParts[0] != "Bearer" {
app.invalidAuthenticationTokenResponse(w, r)
return
}
// Extract the actual authentication toekn from the header parts
token := headerParts[1]
// Validate the token to make sure it is in a sensible format.
v := validator.New()
// If the token isn't valid, use the invalidAuthenticationtokenResponse
// helper to send a response, rather than the failedValidatedResponse helper.
if data.ValidateTokenPlaintext(v, token); !v.Valid() {
app.invalidAuthenticationTokenResponse(w, r)
return
}
// Retrieve the details of the user associated with the authentication token.
// call invalidAuthenticationTokenResponse if no matching record was found.
user, err := app.models.Users.GetForToken(data.ScopeAuthentication, token)
if err != nil {
switch {
case errors.Is(err, data.ErrRecordNotFound):
app.invalidAuthenticationTokenResponse(w, r)
default:
app.serverErrorResponse(w, r, err)
}
return
}
// Call the contextSetUser healer to add the user information to the request context.
r = app.contextSetUser(r, user)
// Call next handler in chain
next.ServeHTTP(w, r)
})
}
// requireAuthenticatedUser checks that the user is not anonymous (i.e., they are authenticated).
func (app *application) requireAuthenticatedUser(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Use the contextGetUser helper to retrieve the user information from the request context.
user := app.contextGetUser(r)
// If the user is anonymous, then call authenticationRequiredResponse to inform the client
// that they should be authenticated before trying again.
if user.IsAnonymous() {
app.authenticationRequiredResponse(w, r)
return
}
next.ServeHTTP(w, r)
}
}
// requiredActivatedUser checks that the user is both authenticated and activated.
func (app *application) requireActivatedUser(next http.HandlerFunc) http.HandlerFunc {
// Rather than returning this http.HandlerFunc we assign it to the variable fn.
fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := app.contextGetUser(r)
// Check that a user is activated
if !user.Activated {
app.inactiveAccountResponse(w, r)
return
}
next.ServeHTTP(w, r)
})
// Wrap fn with the requireAuthenticatedUser middleware before returning it.
return app.requireAuthenticatedUser(fn)
}
func (app *application) requirePermissions(code string, next http.HandlerFunc) http.HandlerFunc {
fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Retrieve the user from the request context.
user := app.contextGetUser(r)
// Get the slice of permission for the user
permissions, err := app.models.Permissions.GetAllForUser(user.ID)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
// Check if the slice includes the required permission. If it doesn't, then return a 403
// Forbidden response.
if !permissions.Include(code) {
app.notPermittedResponse(w, r)
return
}
// Otherwise, they have the required permission so we call the next handler in the chain.
next.ServeHTTP(w, r)
})
// Wrap this with the requireActivatedUser middleware before returning
return app.requireActivatedUser(fn)
}
// enableCORS sets the Vary: Origin and Access-Control-Allow-Origin response headers in order to
// enabled CORS for trusted origins.
func (app *application) enableCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Add the "Vary: Origin" header.
w.Header().Set("Vary", "Origin")
// Add the "Vary: Access-Control-Request-Method" header.
w.Header().Set("Vary", "Access-Control-Request-Method")
// Get the value of the request's Origin header.
origin := r.Header.Get("Origin")
// On run this if there's an Origin request header present.
if origin != "" {
// Loop through the list of trusted origins, checking to see if the request
// origin exactly matches one of them. If there are no trusted origins, then the
// loop won't be iterated.
for i := range app.config.cors.trustedOrigins {
if origin == app.config.cors.trustedOrigins[i] {
// If there is a match, then set an "Access-Control-Allow-Origin" response
// header with the request origin as the value and break out of the loop.
w.Header().Set("Access-Control-Allow-Origin", origin)
// Check if the request has the HTTP method OPTIONS and contains the
// "Access-Control-Request-Method" header. If it does, then we treat it as a
// preflight request.
if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
// Set the necessary preflight response headers.
w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, PUT, PATCH, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
// Set max cached times for headers for 60 seconds.
w.Header().Set("Access-Control-Max-Age", "60")
// Write the headers along with a 200 OK status and return from the
// middleware with no further action.
w.WriteHeader(http.StatusOK)
return
}
break
}
}
}
next.ServeHTTP(w, r)
})
}
func (app *application) metrics(next http.Handler) http.Handler {
// Initialize the new expvar variables when middleware chain is first build.
totalRequestsReceived := expvar.NewInt("total_requests_received")
totalResponsesSent := expvar.NewInt("total_responses_sent")
totalProcessingTimeMicroseconds := expvar.NewInt("total_processing_time_µs")
totalResponsesSentbyStatus := expvar.NewMap("total_responses_sent_by_status")
// Below runs for every request.
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// use the Add method to increment the number of requests received by 1.
totalRequestsReceived.Add(1)
// Call the httpsnoop.CaptureMetrics function, passing in the next handler in the chain
// along with the existing http.ResponseWriter and http.Request. This returns the metrics
// struct.
metrics := httpsnoop.CaptureMetrics(next, w, r)
// On way back up middleware chain, increment the number of responses sent by 1.
totalResponsesSent.Add(1)
// Get the request processing time in microseconds from httpsnoop and increment the
// cumulative processing time.
totalProcessingTimeMicroseconds.Add(metrics.Duration.Microseconds())
// / Use the Add method to increment the count for the given status code by 1.
// Note, the expvar map is string-keyed, so we need to use the strconv.Itoa
// function to convert the status (an integer) to a string.
totalResponsesSentbyStatus.Add(strconv.Itoa(metrics.Code), 1)
})
}