generated from clevergo/pkg-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.go
38 lines (32 loc) · 1010 Bytes
/
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
// Copyright 2020 CleverGo. All rights reserved.
// Use of this source code is governed by a MIT style license that can be found
// in the LICENSE file.
package auth
import (
"context"
"log"
"net/http"
)
type contextKey int
// IdentityKey is the context key of identity.
const IdentityKey contextKey = 1
// GetIdentity retrieves the identity from context.
func GetIdentity(ctx context.Context) Identity {
identity, _ := ctx.Value(IdentityKey).(Identity)
return identity
}
// NewMiddleware returns a middleware with the given authenticator.
func NewMiddleware(authenticator Authenticator) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
identity, err := authenticator.Authenticate(r, w)
if err != nil {
log.Println(err)
authenticator.Challenge(r, w)
} else {
*r = *r.WithContext(context.WithValue(r.Context(), IdentityKey, identity))
}
next.ServeHTTP(w, r)
})
}
}