forked from nytimes/gizmo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
154 lines (129 loc) · 3.44 KB
/
service.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
package readinglist
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
"cloud.google.com/go/trace"
"github.com/NYTimes/gizmo/server/kit"
"github.com/go-kit/kit/endpoint"
httptransport "github.com/go-kit/kit/transport/http"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
type service struct {
db DB
tracer *trace.Client
}
// ensure we implement the gRPC service
var _ ReadingListServiceServer = &service{}
func NewService(db DB) (kit.Service, error) {
ctx := context.Background()
pid := os.Getenv("GCP_PROJECT_ID")
tracer, err := trace.NewClient(ctx, pid)
if err != nil {
return nil, errors.Wrap(err, "unable to init trace client")
}
return &service{
db: db,
tracer: tracer,
}, nil
}
func (s *service) HTTPOptions() []httptransport.ServerOption {
return nil
}
// override the default gorilla router and select the stdlib
func (s *service) HTTPRouterOptions() []kit.RouterOption {
return []kit.RouterOption{
kit.RouterSelect("stdlib"),
}
}
// tracing HTTP requests
func (s *service) HTTPMiddleware(h http.Handler) http.Handler {
if s.tracer != nil {
return s.tracer.HTTPHandler(h)
}
return h
}
// the go-kit middleware is used for checking user authentication and
// injecting the current user into the request context.
func (s *service) Middleware(ep endpoint.Endpoint) endpoint.Endpoint {
return endpoint.Endpoint(func(ctx context.Context, r interface{}) (interface{}, error) {
start := time.Now()
defer func() {
kit.LogMsg(ctx,
fmt.Sprintf("complete in %0.8f seconds", time.Since(start).Seconds()))
}()
usr, err := getUserFromMD(ctx)
if usr == "" || err != nil {
kit.LogErrorMsg(ctx, err, "unable to get user auth")
// reject if user is not logged in
return nil, kit.NewJSONStatusResponse(
&Message{"please provide a valid oauth token"},
http.StatusUnauthorized,
)
}
// add the user to the request context and continue
return ep(addUser(ctx, usr), r)
})
}
// declare the endpoints for the HTTP server
func (s *service) HTTPEndpoints() map[string]map[string]kit.HTTPEndpoint {
return map[string]map[string]kit.HTTPEndpoint{
"/link": {
"PUT": {
Endpoint: s.putLink,
Decoder: decodePutRequest,
},
},
"/list/{limit:[0-9]+}": {
"GET": {
Endpoint: s.getLinks,
Decoder: decodeGetRequest,
},
},
}
}
// tracing RPC requests
func (s *service) RPCMiddleware() grpc.UnaryServerInterceptor {
if s.tracer != nil {
return s.tracer.GRPCServerInterceptor()
}
return nil
}
func (s *service) RPCServiceDesc() *grpc.ServiceDesc {
return &_ReadingListService_serviceDesc
}
func (s *service) RPCOptions() []grpc.ServerOption {
return nil
}
const userKey = "oauth-user"
func getUserFromMD(ctx context.Context) (string, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return "", errors.New("no request metadata")
}
infos, ok := md["x-endpoint-api-userinfo"]
if !ok || len(infos) == 0 {
return "", errors.New("no user info")
}
js, err := base64.StdEncoding.DecodeString(infos[0])
if err != nil {
return "", errors.Wrap(err, "invalid user info")
}
usr := struct {
ID string `json:"id"`
}{}
err = json.Unmarshal(js, &usr)
return usr.ID, errors.Wrap(err, "unable to decode user info")
}
func addUser(ctx context.Context, usr string) context.Context {
return context.WithValue(ctx, userKey, usr)
}
func getUser(ctx context.Context) string {
return ctx.Value(userKey).(string)
}