-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_get_struct_item.go
309 lines (261 loc) · 7.64 KB
/
http_get_struct_item.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
package crudui
import (
"bytes"
"embed"
"fmt"
"log"
"text/template"
validator "github.com/go-phings/struct-validator"
"net/http"
"reflect"
"strconv"
"strings"
)
type structItemTplObj struct {
Name string
URI string
FieldsHTML string
MsgHTML string
OnlyMsg bool
ID string
ReadOnly bool
}
func (c *Controller) tryGetStructItem(w http.ResponseWriter, r *http.Request, uri string) bool {
structName, id := c.getStructAndIDFromURI("x/struct_item/", c.getRealURI(uri, r.RequestURI))
if structName == "" {
return false
}
// Check if struct exists
_, ok := c.uriStructNameFunc[uri][structName]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return true
}
// check access
readOnly := false
if id != "" {
if !c.isStructOperationAllowed(r, structName, OpsRead) {
w.WriteHeader(http.StatusForbidden)
return true
}
if !c.isStructOperationAllowed(r, structName, OpsUpdate) {
readOnly = true
}
} else {
if !c.isStructOperationAllowed(r, structName, OpsCreate) {
w.WriteHeader(http.StatusForbidden)
return true
}
}
// Render the page
c.renderStructItem(w, r, uri, c.uriStructNameFunc[uri][structName], id, map[string]string{}, 0, "", readOnly)
return true
}
func (c *Controller) tryStructItem(w http.ResponseWriter, r *http.Request, uri string) bool {
structName, id := c.getStructAndIDFromURI("x/struct_item/", c.getRealURI(uri, r.RequestURI))
if structName == "" {
return false
}
// Check if struct exists
_, ok := c.uriStructNameFunc[uri][structName]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return true
}
if r.Method != http.MethodPut && r.Method != http.MethodPost && r.Method != http.MethodDelete {
return false
}
if r.Method == http.MethodDelete && id == "" {
w.WriteHeader(http.StatusBadRequest)
return true
}
// check access for delete
if r.Method == http.MethodDelete {
if !c.isStructOperationAllowed(r, structName, OpsDelete) {
w.WriteHeader(http.StatusForbidden)
return true
}
}
// check access for either create or update
if id != "" {
if !c.isStructOperationAllowed(r, structName, OpsUpdate) {
w.WriteHeader(http.StatusForbidden)
return true
}
} else {
if !c.isStructOperationAllowed(r, structName, OpsCreate) {
w.WriteHeader(http.StatusForbidden)
return true
}
}
obj := c.uriStructNameFunc[uri][structName]()
// Set ID if present in the URI
if id != "" {
val := reflect.ValueOf(obj).Elem()
valField := val.FieldByName("ID")
if !valField.CanSet() {
w.WriteHeader(http.StatusInternalServerError)
return true
}
i, _ := strconv.ParseInt(id, 10, 64)
valField.SetInt(i)
// Load values because we might not overwrite all of them (eg. passwords might stay untouched)
err := c.orm.Load(obj, id)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return true
}
}
// Handle delete here
if r.Method == http.MethodDelete {
err2 := c.orm.Delete(obj)
if err2 != nil {
w.WriteHeader(http.StatusInternalServerError)
return true
}
c.renderMsg(w, r, MsgSuccess, fmt.Sprintf("%s item has been successfully deleted.", structName))
return true
}
// Get form data
r.ParseForm()
// Create object, set value and validate it
invalidFormFields := map[string]bool{}
// Value for each form key is actually an array of strings. We're taking the first one here only
// TODO: Tweak it
v := reflect.ValueOf(obj)
s := v.Elem()
indir := reflect.Indirect(v)
typ := indir.Type()
postValues := map[string]string{}
for fk, fv := range r.Form {
postValues[fk] = fv[0]
if fv[0] == "" {
continue
}
f := s.FieldByName(fk)
if f.IsValid() && f.CanSet() {
// We can set password fields only when they are not empty
field, _ := typ.FieldByName(fk)
gotPassField := c.isFieldHasTag(field, "password")
if gotPassField {
if fv[0] == "" {
continue
}
if c.passFunc != nil {
passVal := c.passFunc(fv[0])
if passVal == "" {
w.WriteHeader(http.StatusInternalServerError)
return true
}
f.SetString(passVal)
continue
}
}
if f.Kind() == reflect.String {
f.SetString(fv[0])
}
if c.isFieldInt(field) {
var iSum int64
for _, fvv := range fv {
i, err := strconv.ParseInt(fvv, 10, 64)
if err != nil {
invalidFormFields[fk] = true
continue
}
if iSum&i == 0 {
iSum += i
}
}
if !invalidFormFields[fk] {
f.SetInt(iSum)
}
}
}
}
valid, failedFields := validator.Validate(obj, &validator.ValidationOptions{
OverwriteTagName: "ui",
})
if len(invalidFormFields) > 0 {
for k := range invalidFormFields {
failedFields[k] = failedFields[k] | validator.FailRegexp
}
}
// TODO: quick hack - if any '___repeat' exist then it should have the same value as field without it
for fk, fv := range postValues {
if strings.HasSuffix(fk, "___repeat") && fv != postValues[strings.Replace(fk, "___repeat", "", 1)] {
valid = false
failedFields[fk] = validator.Required
}
}
if !valid || len(failedFields) > 0 {
invVals := []string{}
for k := range failedFields {
invVals = append(invVals, k)
}
c.renderStructItem(w, r, uri, c.uriStructNameFunc[uri][structName], id, postValues, MsgFailure, fmt.Sprintf("The following fields have invalid values: %s", strings.Join(invVals, ",")), false)
return true
}
err2 := c.orm.Save(obj)
if err2 != nil {
c.renderStructItem(w, r, uri, c.uriStructNameFunc[uri][structName], id, postValues, MsgFailure, fmt.Sprintf("Problem with saving: %s", err2.Error()), false)
return true
}
// Update
if id != "" {
c.renderStructItem(w, r, uri, c.uriStructNameFunc[uri][structName], id, postValues, MsgSuccess, fmt.Sprintf("%s item has been successfully updated.", structName), false)
return true
}
// Create
c.renderMsg(w, r, MsgSuccess, fmt.Sprintf("%s item has been successfully added.", structName))
return true
}
func (c *Controller) renderStructItem(w http.ResponseWriter, r *http.Request, uri string, objFunc func() interface{}, id string, postValues map[string]string, msgType int, msg string, readOnly bool) {
tpl, err := c.getStructItemHTML(uri, objFunc, id, postValues, msgType, msg, readOnly)
if err != nil {
log.Print(err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("error"))
return
}
w.Write([]byte(tpl))
}
func (c *Controller) getStructItemHTML(uri string, objFunc func() interface{}, id string, postValues map[string]string, msgType int, msg string, readOnly bool) (string, error) {
structItemTpl, err := embed.FS.ReadFile(htmlDir, "html/struct_item.html")
if err != nil {
return "", fmt.Errorf("error reading struct item template from embed: %w", err)
}
tplObj, err := c.getStructItemTplObj(uri, objFunc, id, postValues, msgType, msg, readOnly)
if err != nil {
return "", fmt.Errorf("error getting struct item for html: %w", err)
}
buf := &bytes.Buffer{}
t := template.Must(template.New("structItem").Parse(string(structItemTpl)))
err = t.Execute(buf, &tplObj)
if err != nil {
return "", fmt.Errorf("error processing struct item template: %w", err)
}
return buf.String(), nil
}
func (c *Controller) getStructItemTplObj(uri string, objFunc func() interface{}, id string, postValues map[string]string, msgType int, msg string, readOnly bool) (*structItemTplObj, error) {
o := objFunc()
if id != "" {
err := c.orm.Load(o, id)
if err != nil {
return nil, err
}
}
onlyMsg := false
if msgType == MsgSuccess && id == "" {
onlyMsg = true
}
a := &structItemTplObj{
URI: uri,
Name: getStructName(o),
FieldsHTML: c.getStructItemFieldsHTML(o, postValues),
MsgHTML: c.getMsgHTML(msgType, msg),
OnlyMsg: onlyMsg,
ID: id,
ReadOnly: readOnly,
}
return a, nil
}