-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
44 lines (36 loc) · 1.13 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
package middleware
import (
"context"
"net/http"
"strings"
"github.com/keratin/authn-go/authn"
)
var userCtxKey = &contextKey{"user"}
type contextKey struct {
name string
}
// AuthnMiddleware decodes the session token and packs the session into the context.
func AuthnMiddleware(auth *authn.Client) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
w.Header().Set("Content-Type", "application/json")
ctx := r.Context()
authorization := r.Header.Get("Authorization")
token := strings.TrimPrefix(authorization, "Bearer ")
decodedToken, err := auth.SubjectFrom(token)
if err != nil {
next.ServeHTTP(w, r)
return
}
ctx = context.WithValue(ctx, userCtxKey, decodedToken)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
}
// IsAuthenticated returns wether or not the user is authenticated.
// REQUIRES Middleware to have run.
func IsAuthenticated(ctx context.Context) bool {
return ctx.Value(userCtxKey) != nil
}