-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.go
251 lines (213 loc) · 6.08 KB
/
update.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
package api
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/DeviaVir/instio/pkg/system/admin/upload"
"github.com/DeviaVir/instio/pkg/system/db"
"github.com/DeviaVir/instio/pkg/system/item"
"github.com/gorilla/schema"
)
// Updateable accepts or rejects update POST requests to endpoints such as:
// /api/content/update?type=Review&id=1
type Updateable interface {
// Update enabled external clients to update content of a specific type.
Update(http.ResponseWriter, *http.Request) error
}
func updateContentHandler(res http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
res.WriteHeader(http.StatusMethodNotAllowed)
return
}
err := req.ParseMultipartForm(1024 * 1024 * 4) // maxMemory 4MB.
if err != nil {
log.Println("[Update] error:", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
t := req.URL.Query().Get("type")
if t == "" {
res.WriteHeader(http.StatusBadRequest)
return
}
p, found := item.Types[t]
if !found {
log.Println("[Update] attempt to update content unknown type:", t, "from:", req.RemoteAddr)
res.WriteHeader(http.StatusNotFound)
return
}
id := req.URL.Query().Get("id")
if !db.IsValidID(id) {
log.Println("[Update] attempt to update content with missing or invalid id from:", req.RemoteAddr)
res.WriteHeader(http.StatusBadRequest)
return
}
post := p()
j, err := db.Content(t + ":" + id)
if err != nil {
log.Println("[Update] error getting content for type:", t, err)
res.WriteHeader(http.StatusInternalServerError)
return
}
err = json.Unmarshal(j, post)
if err != nil {
log.Println("[Update] error populating data in type:", t, err)
res.WriteHeader(http.StatusInternalServerError)
return
}
ext, ok := post.(Updateable)
if !ok {
log.Println("[Update] rejected non-updateable type:", t, "from:", req.RemoteAddr)
res.WriteHeader(http.StatusBadRequest)
return
}
ts := fmt.Sprintf("%d", int64(time.Nanosecond)*time.Now().UnixNano()/int64(time.Millisecond))
req.PostForm.Set("timestamp", ts)
req.PostForm.Set("updated", ts)
urlPaths, err := upload.StoreFiles(req)
if err != nil {
log.Println(err)
res.WriteHeader(http.StatusInternalServerError)
return
}
for name, urlPath := range urlPaths {
req.PostForm.Set(name, urlPath)
}
// Check for any multi-value fields (ex. checkbox fields)
// and correctly format for db storage. Essentially, we need
// fieldX.0: value1, fieldX.1: value2 => fieldX: []string{value1, value2}.
fieldOrderValue := make(map[string]map[string][]string)
for k, v := range req.PostForm {
if strings.Contains(k, ".") {
fo := strings.Split(k, ".")
// Put the order and the field value into map.
field := string(fo[0])
order := string(fo[1])
if len(fieldOrderValue[field]) == 0 {
fieldOrderValue[field] = make(map[string][]string)
}
orderValue := fieldOrderValue[field] // orderValue is 0:[?type=Thing&id=1]
orderValue[order] = v
fieldOrderValue[field] = orderValue
// Discard the post form value with name.
req.PostForm.Del(k)
}
}
// Add/Set the key & value to the post form in order.
for f, ov := range fieldOrderValue {
for i := 0; i < len(ov); i++ {
position := fmt.Sprintf("%d", i)
fieldValue := ov[position]
if req.PostForm.Get(f) == "" {
for i, fv := range fieldValue {
if i == 0 {
req.PostForm.Set(f, fv)
} else {
req.PostForm.Add(f, fv)
}
}
} else {
for _, fv := range fieldValue {
req.PostForm.Add(f, fv)
}
}
}
}
hook, ok := post.(item.Hookable)
if !ok {
log.Println("[Update] error: Type", t, "does not implement item.Hookable or embed item.Item.")
res.WriteHeader(http.StatusBadRequest)
return
}
// Let's be nice and make a proper item for the Hookable methods.
dec := schema.NewDecoder()
dec.IgnoreUnknownKeys(true)
dec.SetAliasTag("json")
err = dec.Decode(post, req.PostForm)
if err != nil {
log.Println("Error decoding post form for edit handler:", t, err)
res.WriteHeader(http.StatusInternalServerError)
return
}
err = hook.BeforeAPIUpdate(res, req)
if err != nil {
log.Println("[Update] error calling BeforeAPIUpdate:", err)
if err == ErrNoAuth {
// BeforeAPIUpdate can check user.IsValid(req) for auth.
res.WriteHeader(http.StatusUnauthorized)
}
return
}
err = ext.Update(res, req)
if err != nil {
log.Println("[Update] error calling Update:", err)
if err == ErrNoAuth {
// Update can check user.IsValid(req) or other forms of validation for auth.
res.WriteHeader(http.StatusUnauthorized)
}
return
}
err = hook.BeforeSave(res, req)
if err != nil {
log.Println("[Update] error calling BeforeSave:", err)
return
}
// Set specifier for db bucket in case content is/isn't Trustable.
var spec string
_, err = db.UpdateContent(t+spec+":"+id, req.PostForm)
if err != nil {
log.Println("[Update] error calling UpdateContent:", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
// Set the target in the context so user can get saved value from db in hook.
ctx := context.WithValue(req.Context(), "target", fmt.Sprintf("%s:%s", t, id))
req = req.WithContext(ctx)
err = hook.AfterSave(res, req)
if err != nil {
log.Println("[Update] error calling AfterSave:", err)
return
}
err = hook.AfterAPIUpdate(res, req)
if err != nil {
log.Println("[Update] error calling AfterAPIUpdate:", err)
return
}
// Create JSON response to send data back to client.
var data map[string]interface{}
if spec != "" {
spec = strings.TrimPrefix(spec, "__")
data = map[string]interface{}{
"status": spec,
"type": t,
}
} else {
spec = "public"
data = map[string]interface{}{
"id": id,
"status": spec,
"type": t,
}
}
resp := map[string]interface{}{
"data": []map[string]interface{}{
data,
},
}
j, err = json.Marshal(resp)
if err != nil {
log.Println("[Update] error marshalling response to JSON:", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
res.Header().Set("Content-Type", "application/json")
_, err = res.Write(j)
if err != nil {
log.Println("[Update] error writing response:", err)
return
}
}