-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathhandlers.go
More file actions
510 lines (435 loc) · 13.2 KB
/
handlers.go
File metadata and controls
510 lines (435 loc) · 13.2 KB
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"strconv"
"strings"
siridb "github.com/SiriDB/go-siridb-connector"
socketio "github.com/googollee/go-socket.io"
qpack "github.com/transceptor-technology/go-qpack"
msgpack "gopkg.in/vmihailenco/msgpack.v2"
)
// StatusUnprocessableEntity is not available in Go 1.6 and older
const StatusUnprocessableEntity int = 422
type tDb struct {
Dbname string `json:"dbname" qp:"dbname" msgpack:"dbname" csv:"dbname"`
TimePrecision string `json:"timePrecision" qp:"timePrecision" msgpack:"timePrecision" csv:"timePrecision"`
Version string `json:"version" qp:"version" msgpack:"version" csv:"version"`
HTTPServer string `json:"httpServer" qp:"httpServer" msgpack:"httpServer" csv:"httpServer"`
}
type tAuthFetch struct {
User interface{} `json:"user" qp:"user" msgpack:"user" csv:"user"`
AuthRequired bool `json:"authRequired" qp:"authRequired" msgpack:"authRequired" csv:"authRequired"`
}
type tAuthLoginReq struct {
Username string `json:"username" qp:"username" msgpack:"username" csv:"username"`
Password string `json:"password" qp:"password" msgpack:"password" csv:"password"`
}
type tAuthLoginRes struct {
User string `json:"user" qp:"user" msgpack:"user" msgpack:"user" csv:"user"`
}
type tAuthLogoff struct {
User interface{} `json:"user" qp:"user" msgpack:"user" csv:"user"`
}
type tQuery struct {
Query string `json:"query" qp:"query" msgpack:"query" csv:"query"`
Timeout interface{} `json:"timeout" qp:"timeout" msgpack:"timeout" csv:"timeout"`
}
func checkBasicAuth(r *http.Request) (conn *Conn) {
if !base.enableBasicAuth {
return nil
}
username, password, ok := r.BasicAuth()
if !ok {
return nil
}
conn = getConnByUser(username)
if conn != nil {
if password == conn.password {
return conn
}
return nil
}
if base.multiUser {
conn, _ = addConnection(username, password)
}
return conn
}
func getConnBySIO(so *socketio.Conn) (conn *Conn, err error) {
if user, ok := base.ssessions[(*so).ID()]; ok {
conn = getConnByUser(user)
if conn == nil {
err = fmt.Errorf("no connection for user '%s' found, please try to login again", user)
}
} else if base.reqAuth {
err = fmt.Errorf("not authenticated")
} else {
conn = &base.connections[0]
}
return conn, err
}
func getConnByHTTP(w http.ResponseWriter, r *http.Request) *Conn {
var conn *Conn
if conn = checkBasicAuth(r); conn != nil {
return conn
}
sess, err := base.gsessions.SessionStart(w, r)
if err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
} else {
user, ok := sess.Get("user").(string)
if ok {
conn = getConnByUser(user)
if conn == nil {
sendError(
w,
fmt.Sprintf("no connection for user '%s' found, please try to login again", user),
http.StatusUnauthorized)
}
} else if base.reqAuth {
sendError(w, "not authenticated", http.StatusUnauthorized)
} else {
conn = &base.connections[0]
}
}
return conn
}
func sendError(w http.ResponseWriter, err string, code int) {
w.Header().Set("Access-Control-Allow-Origin", "*")
http.Error(w, err, code)
}
func sendCSV(w http.ResponseWriter, data interface{}) {
if s, err := toCsv(data); err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
} else {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/csv; charset=UTF-8")
w.Write([]byte(s))
}
}
func sendJSON(w http.ResponseWriter, data interface{}) {
if b, err := json.Marshal(data); err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
} else {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Write(b)
}
}
func sendQPack(w http.ResponseWriter, data interface{}) {
if b, err := qpack.Pack(data); err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
} else {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/x-qpack; charset=UTF-8")
w.Write(b)
}
}
func sendMsgPack(w http.ResponseWriter, data interface{}) {
if b, err := msgpack.Marshal(data); err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
} else {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/x-msgpack; charset=UTF-8")
w.Write(b)
}
}
func getConnByUser(user string) *Conn {
for _, conn := range base.connections {
if conn.user == user {
return &conn
}
}
return nil
}
func addConnection(username, password string) (*Conn, error) {
var conn Conn
conn.user = username
conn.password = password
conn.client = siridb.NewClient(
conn.user, // user
conn.password, // password
base.dbname, // database
serversToInterface(base.servers), // siridb server(s)
base.logCh, // optional log channel
)
conn.client.Connect()
if conn.client.IsConnected() && conn.client.IsAvailable() {
base.connections = append(base.connections, conn)
} else {
conn.client.Close()
return nil, fmt.Errorf("Cannot login using the username and password")
}
return &conn, nil
}
func handlerNotFound(w http.ResponseWriter, r *http.Request) {
sendError(w, "404 not found", http.StatusNotFound)
}
func onDbInfo(so *socketio.Conn) (int, interface{}) {
db := tDb{
Dbname: base.dbname,
TimePrecision: base.timePrecision,
Version: base.version,
HTTPServer: AppVersion}
return http.StatusOK, db
}
func handlerDbInfo(w http.ResponseWriter, r *http.Request) {
db := tDb{
Dbname: base.dbname,
TimePrecision: base.timePrecision,
Version: base.version,
HTTPServer: AppVersion}
sendData(w, r, db)
}
func sendData(w http.ResponseWriter, r *http.Request, data interface{}) {
contentType := r.Header.Get("Content-type")
switch strings.ToLower(contentType) {
case "application/csv":
sendCSV(w, data)
case "application/json":
sendJSON(w, data)
case "application/x-qpack":
sendQPack(w, data)
case "application/x-msgpack":
sendMsgPack(w, data)
default:
sendError(w, fmt.Sprintf("unsupported content-type: %s", contentType), http.StatusUnsupportedMediaType)
}
}
func readBody(w http.ResponseWriter, r *http.Request, v interface{}) error {
contentType := r.Header.Get("Content-type")
switch strings.ToLower(contentType) {
case "application/csv":
return readCSV(w, r, &v)
case "application/json":
return readJSON(w, r, &v)
case "application/x-qpack":
return readQPack(w, r, &v)
case "application/x-msgpack":
return readMsgPack(w, r, &v)
default:
err := fmt.Errorf("unsupported content-type: %s", contentType)
sendError(w, err.Error(), http.StatusUnsupportedMediaType)
return err
}
}
func onAuthFetch(so *socketio.Conn) (int, interface{}) {
authFetch := tAuthFetch{User: nil, AuthRequired: base.reqAuth}
if user, ok := base.ssessions[(*so).ID()]; ok && getConnByUser(user) != nil {
authFetch.User = user
} else if !base.reqAuth {
authFetch.User = base.connections[0].user
}
return http.StatusOK, authFetch
}
func handlerAuthFetch(w http.ResponseWriter, r *http.Request) {
authFetch := tAuthFetch{User: nil, AuthRequired: base.reqAuth}
sess, err := base.gsessions.SessionStart(w, r)
if err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
return
}
if user, ok := sess.Get("user").(string); ok && getConnByUser(user) != nil {
authFetch.User = user
} else if !base.reqAuth {
authFetch.User = base.connections[0].user
}
sendData(w, r, authFetch)
}
func onAuthLogin(so *socketio.Conn, req *tAuthLoginReq) (int, interface{}) {
if conn := getConnByUser(req.Username); conn != nil {
if req.Password != conn.password {
return StatusUnprocessableEntity, "Username or password incorrect"
}
} else if base.multiUser {
if _, err := addConnection(req.Username, req.Password); err != nil {
return StatusUnprocessableEntity, err.Error()
}
} else {
return StatusUnprocessableEntity, "Multiple user login is not allowed"
}
base.ssessions[(*so).ID()] = req.Username
authLoginRes := tAuthLoginRes{User: req.Username}
return http.StatusOK, authLoginRes
}
func handlerAuthLogin(w http.ResponseWriter, r *http.Request) {
var authLoginReq tAuthLoginReq
sess, err := base.gsessions.SessionStart(w, r)
if err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
return
}
if err := readBody(w, r, &authLoginReq); err != nil {
return // error is send by the readBody function
}
if conn := getConnByUser(authLoginReq.Username); conn != nil {
if authLoginReq.Password != conn.password {
sendError(w, "Username or password incorrect", StatusUnprocessableEntity)
return
}
} else if base.multiUser {
if _, err := addConnection(authLoginReq.Username, authLoginReq.Password); err != nil {
sendError(w, err.Error(), StatusUnprocessableEntity)
return
}
} else {
sendError(w, "Multiple user login is not allowed", StatusUnprocessableEntity)
return
}
sess.Set("user", authLoginReq.Username)
authLoginRes := tAuthLoginRes{User: authLoginReq.Username}
sendData(w, r, authLoginRes)
}
func onAuthLogout(so *socketio.Conn) (int, interface{}) {
authLogoff := tAuthLogoff{User: nil}
delete(base.ssessions, (*so).ID())
return http.StatusOK, authLogoff
}
func handlerAuthLogout(w http.ResponseWriter, r *http.Request) {
authLogoff := tAuthLogoff{User: nil}
sess, err := base.gsessions.SessionStart(w, r)
if err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
return
}
if err = sess.Flush(); err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
return
}
sendData(w, r, authLogoff)
}
func onQuery(so *socketio.Conn, req *tQuery) (int, interface{}) {
conn, err := getConnBySIO(so)
if err != nil {
return http.StatusUnauthorized, err.Error()
}
var timeout uint64
timeout = 30
if req.Timeout != nil {
if timeout, err = strconv.ParseUint(fmt.Sprint(req.Timeout), 10, 16); err != nil {
timeout = 30
}
}
res, err := conn.client.Query(req.Query, uint16(timeout))
if err != nil {
return http.StatusInternalServerError, err.Error()
}
return http.StatusOK, res
}
func handlerQuery(w http.ResponseWriter, r *http.Request) {
if conn := getConnByHTTP(w, r); conn != nil {
var query tQuery
if err := readBody(w, r, &query); err != nil {
return // error is send by the readBody function
}
timeout, ok := query.Timeout.(uint16)
if !ok {
timeout = 30
}
res, err := conn.client.Query(query.Query, timeout)
if err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
return
}
sendData(w, r, res)
}
}
func onInsert(so *socketio.Conn, insert *interface{}) (int, interface{}) {
conn, err := getConnBySIO(so)
if err != nil {
return http.StatusUnauthorized, err.Error()
}
res, err := conn.client.Insert(*insert, base.insertTimeout)
if err != nil {
return http.StatusInternalServerError, err.Error()
}
return http.StatusOK, res
}
func readJSON(w http.ResponseWriter, r *http.Request, v *interface{}) error {
decoder := json.NewDecoder(r.Body)
decoder.UseNumber()
if err := decoder.Decode(v); err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
return err
}
return nil
}
func readMsgPack(w http.ResponseWriter, r *http.Request, v *interface{}) error {
decoder := msgpack.NewDecoder(r.Body)
if err := decoder.Decode(v); err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
return err
}
return nil
}
func resToPlan(w http.ResponseWriter, res interface{}, v *interface{}, ft string) error {
iface, ok := (*v).(*interface{})
if ok {
*iface = res
return nil
}
m, ok := res.(map[string]interface{})
if !ok {
err := fmt.Errorf("expecting a map for a non interface{} value")
sendError(w, err.Error(), http.StatusInternalServerError)
return err
}
e := reflect.ValueOf(*v).Elem()
t := e.Type()
n := t.NumField()
for i := 0; i < n; i++ {
field := t.Field(i)
fn := field.Tag.Get(ft)
if len(fn) == 0 {
fn = field.Name
}
val, ok := m[fn]
if ok {
if e.Field(i).Type() != reflect.TypeOf(val) {
err := fmt.Errorf("unexpected type")
sendError(w, err.Error(), http.StatusInternalServerError)
return err
}
e.Field(i).Set(reflect.ValueOf(val))
}
}
return nil
}
func readQPack(w http.ResponseWriter, r *http.Request, v *interface{}) error {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
return err
}
res, err := qpack.Unpack(b, qpack.QpFlagStringKeysOnly)
if err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
return err
}
return resToPlan(w, res, v, "qp")
}
func readCSV(w http.ResponseWriter, r *http.Request, v *interface{}) error {
res, err := parseCsv(r.Body)
if err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
return err
}
return resToPlan(w, res, v, "csv")
}
func handlerInsert(w http.ResponseWriter, r *http.Request) {
if conn := getConnByHTTP(w, r); conn != nil {
var insert interface{}
if err := readBody(w, r, &insert); err != nil {
return // error is send by the readBody function
}
res, err := conn.client.Insert(insert, base.insertTimeout)
if err != nil {
sendError(w, err.Error(), http.StatusInternalServerError)
return
}
sendData(w, r, res)
}
}