-
Notifications
You must be signed in to change notification settings - Fork 3
/
token.go
68 lines (51 loc) · 1.46 KB
/
token.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
package token
import (
"fmt"
"net/http"
"github.com/alexfalkowski/go-service/security/header"
"github.com/alexfalkowski/go-service/security/token"
st "github.com/alexfalkowski/go-service/transport/security/token"
"github.com/alexfalkowski/go-service/transport/strings"
)
// Handler for token.
type Handler struct {
verifier token.Verifier
}
// NewHandler for token.
func NewHandler(verifier token.Verifier) *Handler {
return &Handler{verifier: verifier}
}
func (h *Handler) ServeHTTP(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
if strings.IsObservable(req.URL.Path) {
next(res, req)
return
}
ctx := req.Context()
ctx, err := st.Verify(ctx, h.verifier)
if err != nil {
http.Error(res, "verify token: "+err.Error(), http.StatusUnauthorized)
return
}
next(res, req.WithContext(ctx))
}
// NewRoundTripper for token.
func NewRoundTripper(gen token.Generator, hrt http.RoundTripper) *RoundTripper {
return &RoundTripper{gen: gen, RoundTripper: hrt}
}
// RoundTripper for token.
type RoundTripper struct {
gen token.Generator
http.RoundTripper
}
func (r *RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
ctx, t, err := r.gen.Generate(req.Context())
if err != nil {
return nil, err
}
if len(t) == 0 {
return nil, header.ErrInvalidAuthorization
}
req = req.WithContext(ctx)
req.Header.Add("Authorization", fmt.Sprintf("%s %s", header.BearerAuthorization, string(t)))
return r.RoundTripper.RoundTrip(req)
}