forked from aquasecurity/postee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
92 lines (77 loc) · 2.18 KB
/
config.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
package uiserver
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
hookDbService "github.com/tzurielweisberg/postee/v2/dbservice"
"github.com/tzurielweisberg/postee/v2/router"
)
func (srv *uiServer) getConfig(w http.ResponseWriter, r *http.Request) {
log.Printf("configured config path %s", srv.cfgPath)
_, err := router.Parsev2cfg(srv.cfgPath)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("Invalid config file format: %s", err.Error())))
return
}
d, err := ioutil.ReadFile(srv.cfgPath)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "text/yaml")
w.WriteHeader(http.StatusOK)
w.Write(d)
}
func (srv *uiServer) updateConfig(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
inputYaml, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Can't read JSON string", http.StatusBadRequest)
return
}
if err := os.Rename(srv.cfgPath, srv.cfgPath+".copy"); err != nil {
log.Printf("rename file error %v", err)
http.Error(w, "Can't remove data from the config file for overwrite", http.StatusBadRequest)
return
}
f, err := os.Create(srv.cfgPath)
if err != nil {
log.Printf("create file error %v", err)
http.Error(w, "Can't open the config file for overwrite", http.StatusBadRequest)
return
}
defer f.Close()
_, err = f.Write(inputYaml)
if err != nil {
log.Printf("write file error %v", err)
http.Error(w, "Can't write to the config file for overwrite", http.StatusBadRequest)
return
}
os.RemoveAll(srv.cfgPath + ".copy")
apikey, err := hookDbService.GetApiKey()
if err != nil {
log.Printf("Can not load api key from bolt %v", err)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
err = reloadWebhookCfg(srv.webhookUrl, apikey)
if err != nil {
log.Printf("Unable to reach Postee backend %v", err)
http.Error(w, "Unable to reach Postee backend", http.StatusBadRequest)
return
}
}
func reloadWebhookCfg(url string, key string) error {
u := fmt.Sprintf("%s/reload?key=%s", url, key)
resp, err := http.Get(u)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}