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
|
package sparkles
import (
"net/http"
"github.com/xlgmokha/x/pkg/log"
"github.com/xlgmokha/x/pkg/mapper"
"github.com/xlgmokha/x/pkg/serde"
"github.com/xlgmokha/x/pkg/x"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/domain"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/middleware"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/authz"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls"
)
type Controller struct {
db domain.Repository[*domain.Sparkle]
check authz.CheckPermissionService
}
func New(db domain.Repository[*domain.Sparkle], check authz.CheckPermissionService) *Controller {
return &Controller{
check: check,
db: db,
}
}
func (c *Controller) MountTo(mux *http.ServeMux) {
mux.HandleFunc("GET /sparkles", c.Index)
mux.Handle("POST /sparkles", x.Middleware[http.Handler](
http.HandlerFunc(c.Create),
middleware.RequireUser(),
// middleware.RequirePermission("create", c.check),
))
// This is a temporary endpoint to restore a backup
mux.HandleFunc("POST /sparkles/restore", c.Restore)
}
func (c *Controller) Index(w http.ResponseWriter, r *http.Request) {
if err := serde.ToHTTP(w, r, c.db.All(r.Context())); err != nil {
pls.LogError(r.Context(), err)
w.WriteHeader(http.StatusInternalServerError)
}
}
func (c *Controller) Create(w http.ResponseWriter, r *http.Request) {
sparkle := mapper.MapFrom[*http.Request, *domain.Sparkle](r)
if x.IsZero(sparkle) {
w.WriteHeader(http.StatusBadRequest)
return
}
if err := c.db.Save(r.Context(), sparkle); err != nil {
pls.LogError(r.Context(), err)
w.WriteHeader(http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusCreated)
if err := serde.ToHTTP(w, r, sparkle); err != nil {
pls.LogError(r.Context(), err)
return
}
}
// This is a temporary endpoint to restore a backup
// of sparkles and can be deleted once we have an actual database
func (c *Controller) Restore(w http.ResponseWriter, r *http.Request) {
sparkles, _ := serde.FromHTTP[[]*domain.Sparkle](r)
log.WithFields(r.Context(), log.Fields{"sparkles": sparkles})
x.Each(sparkles, func(sparkle *domain.Sparkle) {
if err := c.db.Save(r.Context(), sparkle); err != nil {
pls.LogError(r.Context(), err)
}
})
}
|