/
api.go
299 lines (249 loc) · 6.85 KB
/
api.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
package jumpi
import (
"context"
"encoding/json"
"errors"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"reflect"
"regexp"
"strings"
"time"
"github.com/codegangsta/negroni"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
func (r Route) Attach(router *mux.Router) {
ro := router.Methods(r.Method).
Path(r.Pattern).
Name(r.Name).
Handler(r.HandlerFunc)
tpl, _ := ro.GetPathTemplate()
log.Printf("api_server: attaching route: %s %s\n", r.Method, tpl)
}
func (r Routes) Attach(router *mux.Router) {
for _, route := range r {
route.Attach(router)
}
}
type logger struct {
*log.Logger
}
func (l *logger) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
start := time.Now()
next(w, r)
res := w.(negroni.ResponseWriter)
session := "-"
if ses := r.Context().Value("session"); ses != nil {
token := ses.(*jwt.Token)
parts := strings.Split(token.Raw, ".")
session = parts[2]
}
user := "-"
if usr := r.Context().Value("user"); usr != nil {
user = usr.(string)
}
useragent := r.Header.Get("User-Agent")
referer := r.Header.Get("Referer")
duration := int64(time.Since(start) / time.Millisecond)
remote := "-"
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
remote = host
}
l.Printf("%s http[%d]: %s %s \"%s %s %s\" %d %d \"%s\" \"%s\" %s %dms\n",
time.Now().UTC().Format(time.RFC3339),
os.Getpid(),
remote,
user,
r.Method,
r.URL,
r.Proto,
res.Status(),
res.Size(),
useragent,
referer,
session,
duration,
)
}
type JSONRequest struct {
obj interface{}
}
type JSONResponse struct {
Status int `json:"status"`
Content interface{} `json:"response,omitempty"`
}
var (
LimitRequest int64 = 4096
)
func ParseJsonRequest(r *http.Request, v interface{}) (*JSONRequest, error) {
body, err := ioutil.ReadAll(io.LimitReader(r.Body, LimitRequest))
if err != nil {
return nil, err
}
if err := r.Body.Close(); err != nil {
return nil, err
}
if err := json.Unmarshal(body, v); err != nil {
return nil, err
}
return &JSONRequest{obj: v}, nil
}
func (jr JSONRequest) Validate() error {
// object needs to be a pointer to a struct
st := reflect.TypeOf(jr.obj)
if st.Kind() != reflect.Ptr {
return errors.New("invalid request")
}
st = st.Elem()
if st.Kind() != reflect.Struct {
return errors.New("invalid request")
}
// iterate over all fields and check if the format is correct, if nothing
// is specified then we just accept the json decoding
for i := 0; i < st.NumField(); i += 1 {
field := st.Field(i)
format := field.Tag.Get("valid")
json_name := field.Tag.Get("json")
if len(json_name) == 0 {
json_name = field.Name
}
if len(format) > 0 && field.Type.Kind() == reflect.String {
val := reflect.ValueOf(jr.obj).Elem().Field(i).Interface()
value, ok := val.(string)
if !ok {
return errors.New("invalid field \"" + json_name + "\"")
}
// check if value complies to format
if matched, err := regexp.MatchString(format, value); err != nil || !matched {
return errors.New("invalid field \"" + json_name + "\"")
}
}
}
return nil
}
func (jr JSONResponse) Write(w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(jr.Status)
if err := json.NewEncoder(w).Encode(jr); err != nil {
return err
}
return nil
}
func ResponseError(w http.ResponseWriter, status int, e error) {
response := JSONResponse{
Status: status,
Content: e.Error(),
}
if err := response.Write(w); err != nil {
log.Fatalf("api_server: unable to send error response: %s\n", err.Error())
}
}
func ContextMiddleware(handler http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// load authenticated session and add user to context (if found)
r = r.WithContext(context.WithValue(r.Context(), "user", nil))
r = r.WithContext(context.WithValue(r.Context(), "session", nil))
if tokens, ok := r.Header["Authorization"]; ok {
var store *Store
for _, t := range tokens {
// try to get store, abort if not successful
if store == nil {
store, _ = GetStore(r)
}
if store == nil {
break
}
// separate from first space, we want a Bearer token
splits := strings.Split(t, " ")
if len(splits) < 2 || splits[0] != "Bearer" {
continue
}
session := &session{store: store}
if ok, token := session.Validate(splits[1]); ok {
username, _ := token.Claims["usr"].(string)
r = r.WithContext(context.WithValue(r.Context(), "user", username))
r = r.WithContext(context.WithValue(r.Context(), "session", token))
break
}
}
}
// pass request to next handler
handler.ServeHTTP(w, r)
}
}
func GetStore(r *http.Request) (*Store, error) {
shandler := r.Context().Value("_store")
if s, ok := shandler.(*Store); ok {
return s, nil
}
log.Printf("api_server: unable to restore store from context: %s %s - %v\n", r.Method, r.URL.Path, shandler)
return nil, errors.New("unable to get store from context")
}
func StackMiddleware(handler http.HandlerFunc, mid ...func(http.Handler) http.HandlerFunc) http.HandlerFunc {
for _, m := range mid {
handler = m(handler)
}
return handler
}
func LoginRequired(handler http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if u := r.Context().Value("user"); u != nil {
handler.ServeHTTP(w, r)
} else {
ResponseError(w, http.StatusUnauthorized, errors.New("Authorization Required"))
}
}
}
func StoreUnlockRequired(handler http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
store, err := GetStore(r)
if err != nil {
ResponseError(w, http.StatusInternalServerError, err)
return
}
if store.IsLocked() {
ResponseError(w, http.StatusPreconditionFailed, errors.New("store is not unlocked"))
return
}
handler.ServeHTTP(w, r)
}
}
func StartAPIServer(root string, store *Store) {
go func() {
router := mux.NewRouter()
router.KeepContext = true // we clean context ourselves in logger
if strings.HasSuffix(root, "/") {
root = root[:len(root)-1]
}
// attach APIv1
apiv1 := router.PathPrefix(root + "/api/v1/").Subrouter()
apiv1.StrictSlash(true)
if _, err := NewAPIv1Router(apiv1); err != nil {
log.Fatal(err)
}
apiv1.KeepContext = true
logger := &logger{log.New(os.Stdout, "", 0)}
n := negroni.New(negroni.NewRecovery(), logger)
n.UseHandler(StackMiddleware(router.ServeHTTP, ContextMiddleware, func(handler http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// store a handler to the DB to the context
r = r.WithContext(context.WithValue(r.Context(), "_store", store))
// pass to next handler on stack
handler.ServeHTTP(w, r)
}
}))
n.Run("127.0.0.1:4200")
}()
}