/
router.go
1484 lines (1280 loc) · 44 KB
/
router.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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package v1
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/InVisionApp/go-health/v2"
"github.com/InVisionApp/go-health/v2/handlers"
"github.com/dghubble/gologin/v2"
"github.com/dghubble/gologin/v2/github"
oauth2login "github.com/dghubble/gologin/v2/oauth2"
"github.com/go-playground/validator/v10"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
_ "github.com/lib/pq"
"github.com/microcosm-cc/bluemonday"
"github.com/rs/zerolog"
uuid "github.com/satori/go.uuid"
"golang.org/x/oauth2"
"gorm.io/gorm"
"github.com/cosmos/atlas/config"
"github.com/cosmos/atlas/server/httputil"
"github.com/cosmos/atlas/server/middleware"
"github.com/cosmos/atlas/server/models"
)
const (
sessionName = "atlas_session"
sessionGithubID = "github_id"
sessionUserID = "user_Id"
sessionRedirectURI = "redirect_uri"
V1APIPathPrefix = "/api/v1"
)
var (
// MaxTokens defines the maximum number of API tokens a user can create.
MaxTokens int64 = 100
paginationParams = []string{
"page", "{page:[0-9]+}",
"limit", "{limit:[0-9]+}",
}
)
// Router implements a versioned HTTP router responsible for handling all v1 API
// requests
type Router struct {
logger zerolog.Logger
cfg config.Config
db *gorm.DB
cookieCfg gologin.CookieConfig
sessionStore *sessions.CookieStore
oauth2Cfg *oauth2.Config
healthChecker *health.Health
validate *validator.Validate
sanitizer Sanitizer
ghClientCreator func(string) GitHubClientI
}
func NewRouter(
logger zerolog.Logger,
cfg config.Config,
db *gorm.DB,
cookieCfg gologin.CookieConfig,
sStore *sessions.CookieStore,
oauth2Cfg *oauth2.Config,
ghClientCreator func(string) GitHubClientI,
) (*Router, error) {
sqlDB, _ := db.DB()
healthChecker, err := httputil.CreateHealthChecker(sqlDB, true)
if err != nil {
return nil, err
}
return &Router{
logger: logger,
cfg: cfg,
db: db,
cookieCfg: cookieCfg,
sessionStore: sStore,
oauth2Cfg: oauth2Cfg,
healthChecker: healthChecker,
validate: validator.New(),
sanitizer: newSanitizer(),
ghClientCreator: ghClientCreator,
}, nil
}
// Register registers all v1 HTTP handlers with the provided mux router and
// prefix path. All registered HTTP handlers come bundled with the appropriate
// middleware.
func (r *Router) Register(rtr *mux.Router, prefix string) {
v1Router := rtr.PathPrefix(prefix).Subrouter()
// handle all preflight request
v1Router.Methods("OPTIONS").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.WriteHeader(http.StatusOK)
})
// build middleware chain
mChain := middleware.Build(r.logger, r.cfg)
// define and register the health endpoint
v1Router.Handle(
"/health",
mChain.Then(handlers.NewJSONHandlerFunc(r.healthChecker, nil)),
).Methods(httputil.MethodGET)
// ======================
// unauthenticated routes
// ======================
v1Router.Handle(
"/modules/search",
mChain.ThenFunc(r.SearchModules()),
).Queries(append(paginationParams, "q", "{q}")...).Methods(httputil.MethodGET)
v1Router.Handle(
"/modules",
mChain.ThenFunc(r.GetAllModules()),
).Queries(paginationParams...).Methods(httputil.MethodGET)
v1Router.Handle(
"/modules/{id:[0-9]+}",
mChain.ThenFunc(r.GetModuleByID()),
).Methods(httputil.MethodGET)
v1Router.Handle(
"/modules/{id:[0-9]+}/versions",
mChain.ThenFunc(r.GetModuleVersions()),
).Methods(httputil.MethodGET)
v1Router.Handle(
"/modules/{id:[0-9]+}/authors",
mChain.ThenFunc(r.GetModuleAuthors()),
).Methods(httputil.MethodGET)
v1Router.Handle(
"/modules/{id:[0-9]+}/keywords",
mChain.ThenFunc(r.GetModuleKeywords()),
).Methods(httputil.MethodGET)
v1Router.Handle(
"/users/{name}",
mChain.ThenFunc(r.GetUserByName()),
).Methods(httputil.MethodGET)
v1Router.Handle(
"/users/{name}/modules",
mChain.ThenFunc(r.GetUserModules()),
).Methods(httputil.MethodGET)
v1Router.Handle(
"/users",
mChain.ThenFunc(r.GetAllUsers()),
).Queries(paginationParams...).Methods(httputil.MethodGET)
v1Router.Handle(
"/keywords",
mChain.ThenFunc(r.GetAllKeywords()),
).Queries(paginationParams...).Methods(httputil.MethodGET)
v1Router.Handle(
"/nodes/search",
mChain.ThenFunc(r.SearchNodes()),
).Queries(append(paginationParams, "q", "{q}")...).Methods(httputil.MethodGET)
// allow a missing 'q' query param which defaults to returning all nodes
v1Router.Handle(
"/nodes/search",
mChain.ThenFunc(r.SearchNodes()),
).Queries(paginationParams...).Methods(httputil.MethodGET)
// ====================
// authenticated routes
// ====================
v1Router.Handle(
"/modules",
mChain.ThenFunc(r.UpsertModule()),
).Methods(httputil.MethodPUT)
v1Router.Handle(
"/modules/{id:[0-9]+}/star",
mChain.ThenFunc(r.StarModule()),
).Methods(httputil.MethodPUT)
v1Router.Handle(
"/modules/{id:[0-9]+}/unstar",
mChain.ThenFunc(r.UnStarModule()),
).Methods(httputil.MethodPUT)
v1Router.Handle(
"/me",
mChain.ThenFunc(r.GetUser()),
).Methods(httputil.MethodGET)
v1Router.Handle(
"/me",
mChain.ThenFunc(r.UpdateUser()),
).Methods(httputil.MethodPUT)
v1Router.Handle(
"/me/confirm/{emailToken}",
mChain.ThenFunc(r.ConfirmEmail()),
).Methods(httputil.MethodPUT)
v1Router.Handle(
"/me/invite",
mChain.ThenFunc(r.InviteOwner()),
).Methods(httputil.MethodPUT)
v1Router.Handle(
"/me/invite/accept/{inviteToken}",
mChain.ThenFunc(r.AcceptOwnerInvite()),
).Methods(httputil.MethodPUT)
v1Router.Handle(
"/me/tokens",
mChain.ThenFunc(r.CreateUserToken()),
).Methods(httputil.MethodPUT)
v1Router.Handle(
"/me/tokens",
mChain.ThenFunc(r.GetUserTokens()),
).Methods(httputil.MethodGET)
v1Router.Handle(
"/me/tokens/{id:[0-9]+}",
mChain.ThenFunc(r.RevokeUserToken()),
).Methods(httputil.MethodDELETE)
// ==============
// session routes
// ==============
v1Router.Handle(
"/session/start",
mChain.Then(r.StartSession()),
).Methods(httputil.MethodGET)
v1Router.Handle(
"/session/authorize",
mChain.Then(r.AuthorizeSession()),
).Methods(httputil.MethodGET)
v1Router.Handle(
"/session/logout",
mChain.ThenFunc(r.LogoutSession()),
).Methods(httputil.MethodPOST)
}
// UpsertModule implements a request handler to publish a Cosmos SDK module.
// The authorized user is considered to be the publisher. The publisher must be
// an owner of the module and a contributor to the GitHub repository. If the
// module does not exist, the publisher is considered to be the first and only
// owner and subsequent owners may be invited by the publisher. An error is
// returned if the request body is invalid, the user is not authorized or if any
// database transaction fails.
//
// @Summary Publish a Cosmos SDK module
// @Tags modules
// @Accept json
// @Produce json
// @Param manifest body Manifest true "module manifest"
// @Success 200 {object} models.ModuleJSON
// @Failure 400 {object} httputil.ErrResponse
// @Failure 401 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Security APIKeyAuth
// @Router /modules [put]
func (r *Router) UpsertModule() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
authUser, ok, err := r.authorize(req)
if err != nil || !ok {
httputil.RespondWithError(w, http.StatusUnauthorized, err)
return
}
var request Manifest
if err := json.NewDecoder(req.Body).Decode(&request); err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("failed to read request: %w", err))
return
}
if err := r.validate.Struct(request); err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("invalid request: %w", httputil.TransformValidationError(err)))
return
}
module := ModuleFromManifest(request, r.sanitizer)
ghClient := r.ghClientCreator(authUser.GithubAccessToken.String)
repo, err := ghClient.GetRepository(module.Version.Repo)
if err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, err)
return
}
// set the module's team as the GitHub repository owner
module.Team = repo.Owner
// set the module's version publisher
module.Version.PublishedBy = authUser.ID
// verify the publisher is a contributor to the repository
var isContributor bool
for user := range repo.Contributors {
if authUser.Name == user {
isContributor = true
break
}
}
if !isContributor {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("publisher '%s' is not a contributor of this module", authUser.Name))
return
}
// set the avatar URL for each author
for i, author := range module.Authors {
contributor, ok := repo.Contributors[author.Name]
if ok {
author.AvatarURL = contributor.GetAvatarURL()
module.Authors[i] = author
}
}
// The publisher must already be an existing owner or must have accepted an
// invitation by an existing owner.
record, err := models.QueryModule(r.db, map[string]interface{}{"name": module.Name, "team": module.Team})
if err == nil {
// the module already exists so we check if the publisher is an owner
var isOwner bool
for i := 0; i < len(record.Owners) && !isOwner; i++ {
if record.Owners[i].ID == authUser.ID {
isOwner = true
}
}
if !isOwner {
httputil.RespondWithError(w, http.StatusBadRequest, errors.New("publisher must be an owner of the module"))
return
}
module.Owners = record.Owners
} else {
// Otherwise, the module is new and we automatically assign the publisher
// as the first and only owner.
module.Owners = []models.User{authUser}
}
module, err = module.Upsert(r.db)
if err != nil {
httputil.RespondWithError(w, http.StatusInternalServerError, err)
return
}
httputil.RespondWithJSON(w, http.StatusOK, module)
}
}
// GetModuleByID implements a request handler to retrieve a module by ID.
//
// @Summary Get a Cosmos SDK module by ID
// @Tags modules
// @Accept json
// @Produce json
// @Param id path int true "module ID"
// @Success 200 {object} models.ModuleJSON
// @Failure 400 {object} httputil.ErrResponse
// @Failure 404 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Router /modules/{id} [get]
func (r *Router) GetModuleByID() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
idStr := params["id"]
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("invalid module ID: %w", err))
return
}
module, err := models.GetModuleByID(r.db, uint(id))
if err != nil {
code := http.StatusInternalServerError
if errors.Is(err, gorm.ErrRecordNotFound) {
code = http.StatusNotFound
}
httputil.RespondWithError(w, code, err)
return
}
httputil.RespondWithJSON(w, http.StatusOK, module)
}
}
// SearchModules implements a request handler to retrieve a set of module objects
// by search criteria.
//
// @Summary Search for Cosmos SDK modules by name, team, description and keywords
// @Tags modules
// @Accept json
// @Produce json
// @Param page query int true "pagination page" default(1)
// @Param limit query int true "pagination limit" default(100)
// @Param reverse query string false "pagination reverse" default(false)
// @Param order query string false "pagination order by" default(id)
// @Param q query string true "search criteria"
// @Success 200 {object} httputil.PaginationResponse
// @Failure 400 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Router /modules/search [get]
func (r *Router) SearchModules() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
pQuery, err := httputil.ParsePaginationQueryParams(req)
if err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, err)
return
}
query := req.URL.Query().Get("q")
modules, paginator, err := models.SearchModules(r.db, query, pQuery)
if err != nil {
httputil.RespondWithError(w, http.StatusInternalServerError, err)
return
}
paginated := httputil.NewPaginationResponse(
pQuery,
paginator.PrevPage,
paginator.NextPage,
paginator.Total,
modules,
)
httputil.RespondWithJSON(w, http.StatusOK, paginated)
}
}
// GetAllModules implements a request handler returning a paginated set of
// modules.
//
// @Summary Return a paginated set of all Cosmos SDK modules
// @Tags modules
// @Accept json
// @Produce json
// @Param page query int true "pagination page" default(1)
// @Param limit query int true "pagination limit" default(100)
// @Param reverse query string false "pagination reverse" default(false)
// @Param order query string false "pagination order by" default(id)
// @Success 200 {object} httputil.PaginationResponse
// @Failure 400 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Router /modules [get]
func (r *Router) GetAllModules() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
pQuery, err := httputil.ParsePaginationQueryParams(req)
if err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, err)
return
}
modules, paginator, err := models.GetAllModules(r.db, pQuery)
if err != nil {
httputil.RespondWithError(w, http.StatusInternalServerError, err)
return
}
paginated := httputil.NewPaginationResponse(pQuery, paginator.PrevPage, paginator.NextPage, paginator.Total, modules)
httputil.RespondWithJSON(w, http.StatusOK, paginated)
}
}
// GetModuleVersions implements a request handler to retrieve a module's set of
// versions by ID.
//
// @Summary Get all versions for a Cosmos SDK module by ID
// @Tags modules
// @Accept json
// @Produce json
// @Param id path int true "module ID"
// @Success 200 {array} models.ModuleVersionJSON
// @Failure 400 {object} httputil.ErrResponse
// @Failure 404 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Router /modules/{id}/versions [get]
func (r *Router) GetModuleVersions() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
idStr := params["id"]
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("invalid module ID: %w", err))
return
}
module, err := models.GetModuleByID(r.db, uint(id))
if err != nil {
code := http.StatusInternalServerError
if errors.Is(err, gorm.ErrRecordNotFound) {
code = http.StatusNotFound
}
httputil.RespondWithError(w, code, err)
return
}
httputil.RespondWithJSON(w, http.StatusOK, module.Versions)
}
}
// GetModuleAuthors implements a request handler to retrieve a module's set of
// authors by ID.
//
// @Summary Get all authors for a Cosmos SDK module by ID
// @Tags modules
// @Accept json
// @Produce json
// @Param id path int true "module ID"
// @Success 200 {array} models.UserJSON
// @Failure 400 {object} httputil.ErrResponse
// @Failure 404 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Router /modules/{id}/authors [get]
func (r *Router) GetModuleAuthors() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
idStr := params["id"]
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("invalid module ID: %w", err))
return
}
module, err := models.GetModuleByID(r.db, uint(id))
if err != nil {
code := http.StatusInternalServerError
if errors.Is(err, gorm.ErrRecordNotFound) {
code = http.StatusNotFound
}
httputil.RespondWithError(w, code, err)
return
}
httputil.RespondWithJSON(w, http.StatusOK, module.Authors)
}
}
// GetModuleKeywords implements a request handler to retrieve a module's set of
// keywords by ID.
//
// @Summary Get all keywords for a Cosmos SDK module by ID
// @Tags modules
// @Accept json
// @Produce json
// @Param id path int true "module ID"
// @Success 200 {array} models.KeywordJSON
// @Failure 400 {object} httputil.ErrResponse
// @Failure 404 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Router /modules/{id}/keywords [get]
func (r *Router) GetModuleKeywords() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
idStr := params["id"]
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("invalid module ID: %w", err))
return
}
module, err := models.GetModuleByID(r.db, uint(id))
if err != nil {
code := http.StatusInternalServerError
if errors.Is(err, gorm.ErrRecordNotFound) {
code = http.StatusNotFound
}
httputil.RespondWithError(w, code, err)
return
}
httputil.RespondWithJSON(w, http.StatusOK, module.Keywords)
}
}
// GetUserByID implements a request handler to retrieve a user by name.
//
// @Summary Get a user by name
// @Tags users
// @Accept json
// @Produce json
// @Param name path string true "user name"
// @Success 200 {object} models.UserJSON
// @Failure 404 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Router /users/{name} [get]
func (r *Router) GetUserByName() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
user, err := models.QueryUser(r.db, map[string]interface{}{"name": params["name"]})
if err != nil {
code := http.StatusInternalServerError
if errors.Is(err, gorm.ErrRecordNotFound) {
code = http.StatusNotFound
}
httputil.RespondWithError(w, code, err)
return
}
httputil.RespondWithJSON(w, http.StatusOK, user)
}
}
// GetAllUsers implements a request handler returning a paginated set of
// users.
//
// @Summary Return a paginated set of all users
// @Tags users
// @Accept json
// @Produce json
// @Param page query int true "pagination page" default(1)
// @Param limit query int true "pagination limit" default(100)
// @Param reverse query string false "pagination reverse" default(false)
// @Param order query string false "pagination order by" default(id)
// @Success 200 {object} httputil.PaginationResponse
// @Failure 400 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Router /users [get]
func (r *Router) GetAllUsers() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
pQuery, err := httputil.ParsePaginationQueryParams(req)
if err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, err)
return
}
users, paginator, err := models.GetAllUsers(r.db, pQuery)
if err != nil {
httputil.RespondWithError(w, http.StatusInternalServerError, err)
return
}
paginated := httputil.NewPaginationResponse(pQuery, paginator.PrevPage, paginator.NextPage, paginator.Total, users)
httputil.RespondWithJSON(w, http.StatusOK, paginated)
}
}
// GetUserModules implements a request handler to retrieve a set of modules
// authored by a given user by name.
//
// @Summary Return a set of all Cosmos SDK modules published by a given user
// @Tags users
// @Accept json
// @Produce json
// @Param name path string true "user name"
// @Success 200 {array} models.ModuleJSON
// @Failure 404 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Router /users/{name}/modules [get]
func (r *Router) GetUserModules() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
modules, err := models.GetUserModules(r.db, params["name"])
if err != nil {
code := http.StatusInternalServerError
if errors.Is(err, gorm.ErrRecordNotFound) {
code = http.StatusNotFound
}
httputil.RespondWithError(w, code, err)
return
}
httputil.RespondWithJSON(w, http.StatusOK, modules)
}
}
// InviteOwner implements a request handler to invite a user to be an owner of a
// module.
//
// @Summary Invite a user to be an owner of a module
// @Tags users
// @Produce json
// @Accept json
// @Param invite body ModuleInvite true "invitation"
// @Success 200 {object} boolean
// @Failure 400 {object} httputil.ErrResponse
// @Failure 401 {object} httputil.ErrResponse
// @Failure 404 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Security APIKeyAuth
// @Router /me/invite [put]
func (r *Router) InviteOwner() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
authUser, ok, err := r.authorize(req)
if err != nil || !ok {
httputil.RespondWithError(w, http.StatusUnauthorized, err)
return
}
var requestBody ModuleInvite
if err := json.NewDecoder(req.Body).Decode(&requestBody); err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("failed to read request: %w", err))
return
}
if err := r.validate.Struct(requestBody); err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("invalid request: %w", httputil.TransformValidationError(err)))
return
}
module, err := models.GetModuleByID(r.db, requestBody.ModuleID)
if err != nil {
code := http.StatusInternalServerError
if errors.Is(err, gorm.ErrRecordNotFound) {
code = http.StatusNotFound
}
httputil.RespondWithError(w, code, err)
return
}
// ensure invitee is not already an owner
for _, o := range module.Owners {
if o.Name == requestBody.User {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("'%s' is already an owner", requestBody.User))
return
}
}
invitee, err := models.QueryUser(r.db, map[string]interface{}{"name": requestBody.User})
if err != nil {
code := http.StatusInternalServerError
if errors.Is(err, gorm.ErrRecordNotFound) {
code = http.StatusNotFound
}
httputil.RespondWithError(w, code, err)
return
}
// ensure invitee has a verified email
if !invitee.EmailConfirmed {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("'%s' must confirm their email address", requestBody.User))
return
}
// upsert invite record
moi, err := models.ModuleOwnerInvite{ModuleID: module.ID, InvitedByUserID: authUser.ID, InvitedUserID: invitee.ID}.Upsert(r.db)
if err != nil {
httputil.RespondWithError(w, http.StatusInternalServerError, err)
return
}
// send invite
acceptURL := fmt.Sprintf("%s/accept/%s", r.cfg.String(config.DomainName), moi.Token)
if err := r.sendOwnerInvitation(acceptURL, authUser.Name, invitee, module); err != nil {
httputil.RespondWithError(w, http.StatusInternalServerError, err)
return
}
httputil.RespondWithJSON(w, http.StatusOK, true)
}
}
// AcceptOwnerInvite implements a request handler for accepting a module owner
// invitation.
//
// @Summary Accept a module owner invitation
// @Tags users
// @Produce json
// @Param inviteToken path string true "invite token"
// @Success 200 {object} models.ModuleJSON
// @Failure 400 {object} httputil.ErrResponse
// @Failure 401 {object} httputil.ErrResponse
// @Failure 404 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Security APIKeyAuth
// @Router /me/invite/accept/{inviteToken} [put]
func (r *Router) AcceptOwnerInvite() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
authUser, ok, err := r.authorize(req)
if err != nil || !ok {
httputil.RespondWithError(w, http.StatusUnauthorized, err)
return
}
inviteToken := mux.Vars(req)["inviteToken"]
moi, err := models.QueryModuleOwnerInvite(r.db, map[string]interface{}{"invited_user_id": authUser.ID, "token": inviteToken})
if err != nil {
httputil.RespondWithError(w, http.StatusNotFound, err)
return
}
// prevent stale invites from being accepted
if time.Since(moi.UpdatedAt) > 24*time.Hour {
httputil.RespondWithError(w, http.StatusBadRequest, errors.New("expired module owner invitation"))
return
}
module, err := models.GetModuleByID(r.db, moi.ModuleID)
if err != nil {
code := http.StatusInternalServerError
if errors.Is(err, gorm.ErrRecordNotFound) {
code = http.StatusNotFound
}
httputil.RespondWithError(w, code, err)
return
}
module, err = module.AddOwner(r.db, authUser)
if err != nil {
httputil.RespondWithError(w, http.StatusInternalServerError, err)
return
}
httputil.RespondWithJSON(w, http.StatusOK, module)
}
}
// CreateUserToken implements a request handler that creates a new API token for
// the authenticated user.
//
// @Summary Create a user API token
// @Tags users
// @Produce json
// @Param token body Token true "token name"
// @Success 200 {object} models.UserTokenJSON
// @Failure 400 {object} httputil.ErrResponse
// @Failure 401 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Security APIKeyAuth
// @Router /me/tokens [put]
func (r *Router) CreateUserToken() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
authUser, ok, err := r.authorize(req)
if err != nil || !ok {
httputil.RespondWithError(w, http.StatusUnauthorized, err)
return
}
var request Token
if err := json.NewDecoder(req.Body).Decode(&request); err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("failed to read request: %w", err))
return
}
if err := r.validate.Struct(request); err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("invalid request: %w", httputil.TransformValidationError(err)))
return
}
numTokens := authUser.CountTokens(r.db)
if numTokens >= MaxTokens {
httputil.RespondWithError(w, http.StatusBadRequest, errors.New("maximum number of user API tokens reached"))
return
}
token, err := authUser.CreateToken(r.db, request.Name)
if err != nil {
httputil.RespondWithError(w, http.StatusInternalServerError, err)
return
}
httputil.RespondWithJSON(w, http.StatusOK, token)
}
}
// GetUserTokens implements a request handler returning all of an authenticated
// user's tokens.
//
// @Summary Get all API tokens by user ID
// @Tags users
// @Produce json
// @Success 200 {array} models.UserTokenJSON
// @Failure 401 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Security APIKeyAuth
// @Router /me/tokens [get]
func (r *Router) GetUserTokens() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
authUser, ok, err := r.authorize(req)
if err != nil || !ok {
httputil.RespondWithError(w, http.StatusUnauthorized, err)
return
}
tokens, err := authUser.GetTokens(r.db)
if err != nil {
httputil.RespondWithError(w, http.StatusInternalServerError, err)
return
}
httputil.RespondWithJSON(w, http.StatusOK, tokens)
}
}
// RevokeUserToken implements a request handler revoking a specific token from
// the authorized user.
//
// @Summary Revoke a user API token by ID
// @Tags users
// @Produce json
// @Param id path int true "token ID"
// @Success 200 {object} models.UserTokenJSON
// @Failure 400 {object} httputil.ErrResponse
// @Failure 401 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Security APIKeyAuth
// @Router /me/tokens/{id} [delete]
func (r *Router) RevokeUserToken() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
authUser, ok, err := r.authorize(req)
if err != nil || !ok {
httputil.RespondWithError(w, http.StatusUnauthorized, err)
return
}
params := mux.Vars(req)
idStr := params["id"]
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
httputil.RespondWithError(w, http.StatusBadRequest, fmt.Errorf("invalid user ID: %w", err))
return
}
token, err := models.QueryUserToken(r.db, map[string]interface{}{"id": id, "user_id": authUser.ID, "revoked": false})
if err != nil {
code := http.StatusInternalServerError
if errors.Is(err, gorm.ErrRecordNotFound) {
code = http.StatusNotFound
}
httputil.RespondWithError(w, code, err)
return
}
token, err = token.Revoke(r.db)
if err != nil {
httputil.RespondWithError(w, http.StatusInternalServerError, err)
return
}
httputil.RespondWithJSON(w, http.StatusOK, token)
}
}
// StarModule implements a request handler for adding a favorite by a user to a
// given module.
//
// @Summary Add a favorite for a module
// @Tags modules
// @Produce json
// @Param id path int true "module ID"
// @Success 200 {object} ModuleStars
// @Failure 400 {object} httputil.ErrResponse
// @Failure 401 {object} httputil.ErrResponse
// @Failure 404 {object} httputil.ErrResponse
// @Failure 500 {object} httputil.ErrResponse
// @Security APIKeyAuth
// @Router /modules/{id}/star [put]
func (r *Router) StarModule() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
authUser, ok, err := r.authorize(req)
if err != nil || !ok {
httputil.RespondWithError(w, http.StatusUnauthorized, err)
return
}
params := mux.Vars(req)
idStr := params["id"]
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {