-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
702 lines (625 loc) · 17.4 KB
/
handler.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
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/go-chi/chi"
"github.com/Decentr-net/cerberus/internal/service"
"github.com/Decentr-net/cerberus/pkg/schema"
"github.com/Decentr-net/go-api"
logging "github.com/Decentr-net/logrus/context"
)
// SavePDVResponse ...
// swagger:model SavePDVResponse
type SavePDVResponse struct {
ID uint64 `json:"id"`
}
// SaveImageResponse ...
// swagger:model SaveImageResponse
type SaveImageResponse struct {
HD string `json:"hd"`
Thumb string `json:"thumb"`
}
// PDVRewardsPool ...
// swagger:model PDVRewardsPool
type PDVRewardsPool struct {
Size sdk.Dec `json:"size"`
TotalDelta sdk.Dec `json:"total_delta"`
NextDistributionDate time.Time `json:"next_distribution_date"`
}
// PDVRewardDelta ...
// swagger:model PDVRewardDelta
type PDVRewardDelta struct {
Delta sdk.Dec `json:"delta"`
Pool *PDVRewardsPool `json:"pool"`
}
// saveImageHandler resizes and saves the given message into storage.
func (s *server) saveImageHandler(w http.ResponseWriter, r *http.Request) {
// swagger:operation POST /images Image Save
//
// Resizes (1920x1080, 480x270) and saves images
// ---
// security:
// - public_key: []
// signature: []
// produces:
// - application/json
// consumes:
// - multipart/form-data
// responses:
// '200':
// description: image successfully resized and saved as HD (1920x1080) and thumbnail (480x270)
// schema:
// "$ref": "#/definitions/SaveImageResponse"
// '500':
// description: internal server error
// schema:
// "$ref": "#/definitions/Error"
if err := api.Verify(r); err != nil {
api.WriteVerifyError(r.Context(), w, err)
return
}
owner, err := api.GetAddressFromPubKey(r.Header.Get(api.PublicKeyHeader))
if err != nil {
api.WriteError(w, http.StatusBadRequest, fmt.Sprintf("failed to decode owner address: %s", err.Error()))
return
}
hdPath, thumbPath, err := s.s.SaveImage(r.Context(), r.Body, owner.String())
if err != nil {
if errors.Is(err, service.ErrImageInvalidFormat) {
api.WriteError(w, http.StatusBadRequest, "request body is not an image")
return
}
if errors.Is(err, service.ErrUploadTimeout) {
api.WriteInternalError(r.Context(), w, "upload image timeout")
return
}
api.WriteInternalErrorf(r.Context(), w, "failed to save image: %s", err.Error())
return
}
api.WriteOK(w, http.StatusOK, SaveImageResponse{
HD: hdPath,
Thumb: thumbPath,
})
}
// savePDVHandler encrypts and puts PDV data into storage.
func (s *server) savePDVHandler(w http.ResponseWriter, r *http.Request) {
// swagger:operation POST /pdv PDV Save
//
// Encrypts and saves PDV
//
// ---
// security:
// - public_key: []
// signature: []
// produces:
// - application/json
// consumes:
// - application/json
// parameters:
// - name: request
// description: batch of pdv
// in: body
// required: true
// schema:
// "$ref": "#/definitions/PDV"
// responses:
// '201':
// description: pdv was put into storage
// schema:
// "$ref": "#/definitions/SavePDVResponse"
// '401':
// description: signature wasn't verified
// schema:
// "$ref": "#/definitions/Error"
// '400':
// description: bad request
// schema:
// "$ref": "#/definitions/Error"
// '403':
// description: profile is banned or fraud detected
// schema:
// "$ref": "#/definitions/Error"
// '500':
// description: internal server error
// schema:
// "$ref": "#/definitions/Error"
if err := api.Verify(r); err != nil {
api.WriteVerifyError(r.Context(), w, err)
return
}
data, err := ioutil.ReadAll(r.Body)
if err != nil {
api.WriteError(w, http.StatusBadRequest, fmt.Sprintf("failed to read body: %s", err.Error()))
return
}
r.Body.Close() // nolint:errcheck,gosec
var p schema.PDVWrapper
if err := json.Unmarshal(data, &p); err != nil {
logging.GetLogger(r.Context()).WithField("body", string(data)).Debug("failed to decode pdv")
api.WriteError(w, http.StatusBadRequest, fmt.Sprintf("request is invalid: %s", err.Error()))
return
}
if !p.Validate() {
logging.GetLogger(r.Context()).WithField("body", string(data)).Debug("failed to validate pdv")
api.WriteError(w, http.StatusBadRequest, "pdv data is invalid")
return
}
if l := uint16(len(p.Data())); l < s.minPDVCount || l > s.maxPDVCount {
if l != 1 || p.Data()[0].Type() != schema.PDVProfileType {
api.WriteError(w, http.StatusBadRequest, "forbidden pdv count")
return
}
}
owner, err := api.GetAddressFromPubKey(r.Header.Get(api.PublicKeyHeader))
if err != nil {
api.WriteError(w, http.StatusBadRequest, fmt.Sprintf("failed to decode owner address: %s", err.Error()))
return
}
if s.savePDVThrottler.Throttle(owner.String()) {
api.WriteError(w, http.StatusTooManyRequests,
fmt.Sprintf("too many requests for %s", owner.String()))
return
}
id, _, err := s.s.SavePDV(r.Context(), p, owner)
if err != nil {
if errors.Is(err, service.ErrPDVFraud) {
logging.GetLogger(r.Context()).WithField("owner", owner.String()).Warn("pdv fraud detected")
api.WriteError(w, http.StatusForbidden, "pdv fraud detected")
return
}
if errors.Is(err, service.ErrProfileBanned) {
logging.GetLogger(r.Context()).WithField("owner", owner.String()).Warn("profile banned")
api.WriteError(w, http.StatusForbidden, "profile banned")
return
}
api.WriteInternalErrorf(r.Context(), w, "failed to save pdv: %s", err.Error())
return
}
s.savePDVThrottler.Reset(owner.String())
api.WriteOK(w, http.StatusCreated, SavePDVResponse{ID: id})
}
// validatePDVHandler validates pdv and returns indexes of invalid.
func (s *server) validatePDVHandler(w http.ResponseWriter, r *http.Request) {
// swagger:operation POST /pdv/validate PDV Validate
//
// Encrypts and saves PDV
//
// ---
// produces:
// - application/json
// consumes:
// - application/json
// parameters:
// - name: request
// description: batch of pdv
// in: body
// required: true
// schema:
// "$ref": "#/definitions/PDV"
// responses:
// '200':
// description: all pdv are valid
// schema:
// "$ref": "#/definitions/ValidatePDVResponse"
// '400':
// description: bad request
// schema:
// "$ref": "#/definitions/Error"
// '500':
// description: internal server error
// schema:
// "$ref": "#/definitions/Error"
data, err := ioutil.ReadAll(r.Body)
if err != nil {
api.WriteError(w, http.StatusBadRequest, fmt.Sprintf("failed to read body: %s", err.Error()))
return
}
r.Body.Close() // nolint:errcheck,gosec
invalidPDV, err := schema.GetInvalidPDV(data)
if err != nil {
api.WriteError(w, http.StatusBadRequest, fmt.Sprintf("failed to validate pdv: %s", err.Error()))
return
}
api.WriteOK(w, http.StatusOK, ValidatePDVResponse{Valid: len(invalidPDV) == 0, InvalidPDV: invalidPDV})
}
// listPDVHandler lists pdv from storage.
func (s *server) listPDVHandler(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /pdv/{owner} PDV List
//
// Lists PDV
//
// ---
// produces:
// - application/json
// parameters:
// - name: owner
// description: PDV's address
// in: path
// required: true
// example: decentr1u9slwz3sje8j94ccpwlslflg0506yc8y2ylmtz
// type: string
// - name: from
// description: id of PDV to start from
// in: query
// type: integer
// format: uint64
// - name: limit
// description: how many pdv will be returned
// in: query
// type: integer
// format: uint16
// maximum: 1000
// responses:
// '200':
// description: List of PDV
// schema:
// type: array
// items:
// type: integer
// format: uint64
// '400':
// description: bad request
// schema:
// "$ref": "#/definitions/Error"
// '500':
// description: internal server error
// schema:
// "$ref": "#/definitions/Error"
owner := chi.URLParam(r, "owner")
if !isOwnerValid(owner) {
api.WriteError(w, http.StatusBadRequest, "invalid owner")
return
}
var err error
var from uint64
if s := r.URL.Query().Get("from"); s != "" {
if from, err = strconv.ParseUint(s, 10, 64); err != nil {
api.WriteError(w, http.StatusBadRequest, "invalid from")
return
}
}
limit := defaultLimit
if s := r.URL.Query().Get("limit"); s != "" {
if limit, err = strconv.ParseUint(s, 10, 16); err != nil || limit > 1000 {
api.WriteError(w, http.StatusBadRequest, "invalid limit")
return
}
}
list, err := s.s.ListPDV(r.Context(), owner, from, uint16(limit))
if err != nil {
api.WriteInternalErrorf(r.Context(), w, "failed to list pdv: %s", err.Error())
return
}
data, err := json.Marshal(list)
if err != nil {
api.WriteInternalErrorf(r.Context(), w, "failed to marshal list of pdv: %s", err.Error())
return
}
w.Write(data) // nolint
}
// getPDVHandler gets pdv from storage and decrypts it.
func (s *server) getPDVHandler(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /pdv/{owner}/{id} PDV Get
//
// Returns plain PDV
//
// ---
// produces:
// - application/json
// security:
// - public_key: []
// signature: []
// parameters:
// - name: address
// description: PDV's address
// in: path
// required: true
// type: string
// responses:
// '200':
// description: PDV
// schema:
// "$ref": "#/definitions/PDV"
// '401':
// description: signature wasn't verified
// schema:
// "$ref": "#/definitions/Error"
// '403':
// description: access to file is denied
// schema:
// "$ref": "#/definitions/Error"
// '400':
// description: bad request
// schema:
// "$ref": "#/definitions/Error"
// '500':
// description: internal server error
// schema:
// "$ref": "#/definitions/Error"
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 64)
if err != nil {
api.WriteError(w, http.StatusBadRequest, "invalid id")
return
}
if !isOwnerValid(chi.URLParam(r, "owner")) {
api.WriteError(w, http.StatusBadRequest, "invalid owner")
return
}
if err := api.Verify(r); err != nil {
api.WriteVerifyError(r.Context(), w, err)
return
}
owner, err := api.GetAddressFromPubKey(r.Header.Get(api.PublicKeyHeader))
if err != nil {
api.WriteError(w, http.StatusBadRequest, "failed to generate address")
return
}
if chi.URLParam(r, "owner") != owner.String() {
api.WriteError(w, http.StatusForbidden, "access denied")
return
}
data, err := s.s.ReceivePDV(r.Context(), owner.String(), id)
if err != nil {
if errors.Is(err, service.ErrNotFound) {
api.WriteErrorf(w, http.StatusNotFound, fmt.Sprintf("PDV '%d' not found", id))
} else {
api.WriteInternalErrorf(r.Context(), w, "failed to receive pdv: %s", err.Error())
}
return
}
w.Write(data) // nolint
}
// getPDVMetaHandler returns PDVs meta by address.
func (s *server) getPDVMetaHandler(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /pdv/{owner}/{id}/meta PDV GetMeta
//
// Get meta
//
// Returns metadata of PDV
//
// ---
// parameters:
// - name: address
// description: PDV's address
// in: path
// required: true
// type: string
// responses:
// '200':
// description: metadata of pdv
// schema:
// "$ref": "#/definitions/PDVMeta"
// '404':
// description: PDV doesn't exist
// schema:
// "$ref": "#/definitions/Error"
// '400':
// description: bad request
// schema:
// "$ref": "#/definitions/Error"
// '500':
// description: internal server error
// schema:
// "$ref": "#/definitions/Error"
owner := chi.URLParam(r, "owner")
if !isOwnerValid(owner) {
api.WriteError(w, http.StatusBadRequest, "invalid address")
return
}
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 64)
if err != nil {
api.WriteError(w, http.StatusBadRequest, "invalid id")
return
}
m, err := s.s.GetPDVMeta(r.Context(), owner, id)
if err != nil {
if errors.Is(err, service.ErrNotFound) {
api.WriteErrorf(w, http.StatusNotFound, fmt.Sprintf("PDV '%d' not found", id))
return
}
api.WriteInternalErrorf(r.Context(), w, "failed to get meta: %s", err.Error())
return
}
api.WriteOK(w, http.StatusOK, m)
}
// getProfilesHandler returns profiles.
func (s *server) getProfilesHandler(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /profiles Profile GetProfiles
//
// Get profiles
//
// Returns profiles by addresses
//
// ---
// parameters:
// - name: address
// description: profile address
// in: query
// required: true
// example: decentr1u9slwz3sje8j94ccpwlslflg0506yc8y2ylmtz,decentr1u9slwz3sje8j94ccpwlslflg0506yc8y2ylmtz
// schema:
// type: array
// items:
// type: string
// responses:
// '200':
// description: metadata of pdv
// schema:
// type: array
// items:
// "$ref": "#/definitions/APIProfile"
// '500':
// description: internal server error
// schema:
// "$ref": "#/definitions/Error"
address := strings.Split(r.URL.Query().Get("address"), ",")
var requestedBy string
if r.Header.Get(api.PublicKeyHeader) != "" {
if err := api.Verify(r); err != nil {
api.WriteVerifyError(r.Context(), w, err)
return
}
owner, err := api.GetAddressFromPubKey(r.Header.Get(api.PublicKeyHeader))
if err != nil {
api.WriteError(w, http.StatusBadRequest, fmt.Sprintf("failed to decode owner address: %s", err.Error()))
return
}
requestedBy = owner.String()
}
for _, v := range address {
if !isOwnerValid(v) {
api.WriteError(w, http.StatusBadRequest, "invalid address")
return
}
}
pp, err := s.s.GetProfiles(r.Context(), address)
if err != nil {
api.WriteInternalError(r.Context(), w, fmt.Sprintf("failed to get profiles: %s", err.Error()))
return
}
out := make([]Profile, len(pp))
for i, v := range pp {
p := Profile{
Address: v.Address,
FirstName: v.FirstName,
LastName: v.LastName,
Bio: v.Bio,
Gender: v.Gender,
Avatar: v.Avatar,
Banned: v.Banned,
CreatedAt: v.CreatedAt.Unix(),
}
if v.Birthday != nil {
p.Birthday = v.Birthday.Format(dateFormat)
}
if requestedBy == p.Address {
p.Emails = v.Emails
}
out[i] = p
}
api.WriteOK(w, http.StatusOK, out)
}
// getRewardsConfigHandler returns rewards config.
func (s *server) getRewardsConfigHandler(w http.ResponseWriter, _ *http.Request) {
// swagger:operation GET /configs/rewards Configs GetRewardsConfig
//
// Get rewards config
//
// Returns rewards config.
//
// ---
// responses:
// '200':
// description: rewards config
// schema:
// "$ref": "#/definitions/ObjectTypes"
// '500':
// description: internal server error
// schema:
// "$ref": "#/definitions/Error"
api.WriteOK(w, http.StatusOK, s.s.GetRewardsMap())
}
// getBlacklistHandler returns blacklist.
func (s *server) getBlacklistHandler(w http.ResponseWriter, _ *http.Request) {
// swagger:operation GET /configs/blacklist Configs GetBlacklistConfig
//
// Get blacklist
//
// Returns blacklist.
//
// ---
// responses:
// '200':
// description: blacklist
// schema:
// "$ref": "#/definitions/Blacklist"
// '500':
// description: internal server error
// schema:
// "$ref": "#/definitions/Error"
api.WriteOK(w, http.StatusOK, s.s.GetBlacklist())
}
func (s *server) getPDVRewardsPool(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /pdv-rewards/pool PDVRewards PDVRewardsPool
//
// Get PDV rewards pool
//
// Returns rewards pool.
//
// ---
// produces:
// - application/json
// responses:
// '200':
// description: pool
// schema:
// "$ref": "#/definitions/PDVRewardsPool"
api.WriteOK(w, http.StatusOK, s.rewardsPool)
}
func (s *server) getAccountPDVDelta(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /accounts/{owner}/pdv-delta PDVRewards PDVRewardDelta
//
// Get PDV reward delta of the given account
//
// Returns PDV reward delta with reward pool
//
// ---
// produces:
// - application/json
// parameters:
// - name: owner
// description: account address
// in: path
// required: true
// type: string
// responses:
// '200':
// description: pool
// schema:
// "$ref": "#/definitions/PDVRewardDelta"
// '404':
// description: PDV doesn't exist
// schema:
// "$ref": "#/definitions/Error"
// '500':
// description: internal server error
// schema:
// "$ref": "#/definitions/Error"
owner := chi.URLParam(r, "owner")
if !isOwnerValid(owner) {
api.WriteError(w, http.StatusBadRequest, "invalid owner")
return
}
delta, err := s.s.GetPDVDelta(r.Context(), owner)
if err != nil {
api.WriteInternalError(r.Context(), w, fmt.Sprintf("failed to get PDV delta: %s", err.Error()))
return
}
api.WriteOK(w, http.StatusOK, PDVRewardDelta{
Delta: delta,
Pool: s.rewardsPool,
})
}
func (s *server) preparePDVRewardsPool(ctx context.Context) (*PDVRewardsPool, error) {
total, err := s.s.GetPDVTotalDelta(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get PDV delta total: %w", err)
}
date, err := s.s.GetPDVRewardsNextDistributionDate(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get next distribution date: %w", err)
}
return &PDVRewardsPool{
Size: s.pdvRewardsPoolSize,
TotalDelta: total,
NextDistributionDate: date,
}, nil
}