-
Notifications
You must be signed in to change notification settings - Fork 0
/
webui.go
289 lines (250 loc) · 9.03 KB
/
webui.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
package webui
import (
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"strconv"
"sync"
"time"
jwtmiddleware "github.com/auth0/go-jwt-middleware"
"github.com/dgrijalva/jwt-go"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/libesz/poolmanager/pkg/configstore"
"github.com/libesz/poolmanager/pkg/controller"
"github.com/libesz/poolmanager/pkg/io"
"github.com/libesz/poolmanager/pkg/webui/content"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/urfave/negroni"
)
var parsedTemplates *template.Template
func New(listenOn, password string, configStore *configstore.ConfigStore, inputs []io.Input, outputs []io.Output) WebUI {
r := mux.NewRouter()
signingKey := []byte(uuid.New().String())
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return signingKey, nil
},
// When set, the middleware verifies that tokens are signed with the specific signing algorithm
// If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
// Important to avoid security issues described here: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
SigningMethod: jwt.SigningMethodHS256,
})
r.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
fmt.Println("login attempted")
loginPostHandler(signingKey, password, w, r)
}).Methods("POST")
r.Handle("/api/config", negroni.New(
negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
negroni.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
configPostHandler(configStore, w, r)
})),
)).Methods("POST")
r.Handle("/api/config", negroni.New(
negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
negroni.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
configGetHandler(configStore, w, r)
})),
)).Methods("GET")
r.Handle("/api/ping", negroni.New(
negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
negroni.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { myHandler(w, r) })),
))
r.Handle("/api/status", negroni.New(
negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
negroni.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
apiStatusHandler(configStore, inputs, outputs, w, r)
})),
)).Methods("GET")
r.Handle("/metrics", promhttp.Handler())
r.PathPrefix("/").Handler(http.FileServer(content.Content))
server := &http.Server{
Handler: r,
Addr: listenOn,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
return WebUI{server: server}
}
var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user")
fmt.Fprintf(w, "This is an authenticated request")
fmt.Fprintf(w, "Claim content:\n")
for k, v := range user.(*jwt.Token).Claims.(jwt.MapClaims) {
fmt.Fprintf(w, "%s :\t%#v\n", k, v)
}
})
func (w *WebUI) Run(stopChan chan struct{}) {
var wg sync.WaitGroup
wg.Add(1)
go func() {
err := w.server.ListenAndServe()
log.Printf("Webui: %s\n", err.Error())
wg.Done()
}()
<-stopChan
w.server.Close()
wg.Wait()
}
type ApiStatusResponse struct {
Inputs map[string]string `json:"inputs"`
Outputs map[string]bool `json:"outputs"`
}
func apiStatusHandler(configStore *configstore.ConfigStore, inputs []io.Input, outputs []io.Output, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
data := ApiStatusResponse{
Inputs: make(map[string]string),
Outputs: make(map[string]bool),
}
for _, item := range inputs {
if item.Value() == io.InputError {
data.Inputs[item.Name()] = "N/A"
} else {
data.Inputs[item.Name()] = fmt.Sprintf("%.2f %s", item.Value(), item.Degree())
}
}
for _, item := range outputs {
data.Outputs[item.Name()] = item.Get()
}
log.Printf("Webui: rendering apiStatusHandler page with data: %+v\n", data)
_ = json.NewEncoder(w).Encode(data)
}
type ConfigChangeRequest struct {
Controller string `json:"controller"`
Type string `json:"type"`
Key string `json:"key"`
Value string `json:"value"`
}
type ConfigChangeResponse struct {
Error string `json:"error"`
OrigValue interface{} `json:"origValue"`
}
type ConfigData struct {
ConfigProperties map[string]controller.ConfigProperties `json:"schema"`
ConfigValues map[string]controller.Config `json:"values"`
}
func configGetHandler(configStore *configstore.ConfigStore, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
data := ConfigData{
ConfigProperties: make(map[string]controller.ConfigProperties),
ConfigValues: make(map[string]controller.Config),
}
controllers := configStore.GetControllerNames()
for _, controllerName := range controllers {
data.ConfigProperties[controllerName] = configStore.GetProperties(controllerName)
data.ConfigValues[controllerName] = configStore.Get(controllerName)
}
log.Printf("Webui: config properties response rendered with data: %+v\n", data)
json.NewEncoder(w).Encode(&data)
}
func configPostHandler(configStore *configstore.ConfigStore, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
decoder := json.NewDecoder(r.Body)
var data ConfigChangeRequest
err := decoder.Decode(&data)
if err != nil {
log.Printf("Webui: decode error on request: %s\n", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Printf("Webui: requested config change: %+v\n", data)
config := configStore.Get(data.Controller)
origValueString := ""
switch data.Type {
case "range":
log.Printf("Webui: identified numeric config\n")
convertedValue, err := strconv.ParseFloat(data.Value, 64)
if err != nil {
log.Printf("Webui: Failed to parse requested numeric config change for controller %s key %s value %s: %s\n", data.Controller, data.Key, data.Value, err.Error())
respondError(w, origValueString, err)
return
}
origValue, ok := config.Ranges[data.Key]
if !ok {
log.Printf("Webui: Non-existing numeric config key for controller %s key %s value %s\n", data.Controller, data.Key, data.Value)
respondError(w, origValueString, fmt.Errorf("Non-existing config key"))
return
}
origValueString = strconv.FormatFloat(origValue, 'E', -1, 64)
config.Ranges[data.Key] = convertedValue
case "toggle":
log.Printf("Webui: identified boolean config\n")
convertedValue, err := strconv.ParseBool(data.Value)
if err != nil {
log.Printf("Webui: Failed to parse requested boolean config change for controller %s key %s value %s: %s\n", data.Controller, data.Key, data.Value, err.Error())
respondError(w, origValueString, err)
return
}
origValue, ok := config.Toggles[data.Key]
if !ok {
log.Printf("Webui: Non-existing boolean config key for controller %s key %s value %s\n", data.Controller, data.Key, data.Value)
respondError(w, origValueString, fmt.Errorf("Non-existing config key"))
return
}
origValueString = strconv.FormatBool(origValue)
config.Toggles[data.Key] = convertedValue
default:
log.Printf("Webui: unknown type: %s\n", data.Type)
}
err = configStore.Set(data.Controller, config, true)
if err != nil {
log.Printf("Webui: Failed to update config for controller %s: %s\n", data.Controller, err.Error())
respondError(w, origValueString, err)
return
}
w.WriteHeader(http.StatusOK)
u := ConfigChangeResponse{Error: ""}
_ = json.NewEncoder(w).Encode(u)
}
func respondError(w http.ResponseWriter, origValue interface{}, err error) {
w.WriteHeader(http.StatusConflict)
u := ConfigChangeResponse{Error: err.Error(), OrigValue: origValue}
_ = json.NewEncoder(w).Encode(u)
}
type LoginRequest struct {
Password string `json:"password"`
}
type LoginResponse struct {
Error string `json:"error"`
Token string `json:"token"`
}
func generateJWT(signingKey []byte) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"uuid": uuid.New(),
})
tokenString, err := token.SignedString(signingKey)
if err != nil {
return "", err
}
return tokenString, nil
}
func loginPostHandler(signingKey []byte, password string, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
log.Printf("Webui: requested login\n")
decoder := json.NewDecoder(r.Body)
var data LoginRequest
err := decoder.Decode(&data)
if err != nil {
log.Printf("Webui: decode error on login request: %s\n", err.Error())
w.WriteHeader(http.StatusInternalServerError)
u := ConfigChangeResponse{Error: err.Error(), OrigValue: nil}
_ = json.NewEncoder(w).Encode(u)
return
}
if data.Password != password {
log.Printf("Webui: user unauthorized\n")
w.WriteHeader(http.StatusUnauthorized)
u := LoginResponse{Error: "Unauthorized"}
_ = json.NewEncoder(w).Encode(u)
return
}
log.Printf("Webui: user authorized\n")
tokenString, _ := generateJWT(signingKey)
w.WriteHeader(http.StatusAccepted)
u := LoginResponse{Token: tokenString}
_ = json.NewEncoder(w).Encode(u)
}