-
Notifications
You must be signed in to change notification settings - Fork 60
/
d_api_add.go
380 lines (344 loc) · 8.78 KB
/
d_api_add.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
package uadmin
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"time"
)
func dAPIAddHandler(w http.ResponseWriter, r *http.Request, s *Session) {
var rowsCount int64
urlParts := strings.Split(r.URL.Path, "/")
modelName := urlParts[0]
model, _ := NewModel(modelName, false)
schema, _ := getSchema(modelName)
tableName := schema.TableName
// Check CSRF
if CheckCSRF(r) {
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "Failed CSRF protection.",
})
return
}
// Check permission
allow := false
if disableAdder, ok := model.Interface().(APIDisabledAdder); ok {
allow = disableAdder.APIDisabledAdd(r)
// This is a "Disable" method
allow = !allow
if !allow {
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "Permission denied",
})
return
}
}
if publicAdder, ok := model.Interface().(APIPublicAdder); ok {
allow = publicAdder.APIPublicAdd(r)
}
if !allow && s != nil {
allow = s.User.GetAccess(modelName).Add
}
if !allow {
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "Permission denied",
})
return
}
// Check if log is required
log := APILogAdd
if logAdder, ok := model.Interface().(APILogAdder); ok {
log = logAdder.APILogAdd(r)
}
// Get parameters
params := getURLArgs(r)
params = customParamsAdd(params, model, s)
createdIDs := []int{}
// Process Upload files
fileList, err := dAPIUpload(w, r, &schema)
if err != nil {
Trail(ERROR, "dAPI Add Upload error processing. %s", err)
}
for k, v := range fileList {
params["_"+k] = v
}
if len(urlParts) == 2 {
// Add One/Many
q, args, m2mFields := getAddFilters(params, &schema)
if DebugDB {
Trail(DEBUG, "q: %s, v: %#v", q, args)
}
db := GetDB().Begin()
for i := range q {
// Build args place holder
argsPlaceHolder := []string{}
for range args[i] {
argsPlaceHolder = append(argsPlaceHolder, "?")
}
db = db.Exec("INSERT INTO "+tableName+" ("+q[i]+") VALUES ("+strings.Join(argsPlaceHolder, ",")+")", args[i]...)
rowsCount += db.RowsAffected
}
id := []int{}
if Database.Type == "sqlite" {
db = db.Raw("SELECT last_insert_rowid() AS lastid")
} else if Database.Type == "mysql" {
db = db.Raw("SELECT LAST_INSERT_ID() AS lastid")
} else if Database.Type == "postgres" {
db = db.Raw("SELECT lastval() AS lastid")
}
db.Table(tableName).Pluck("lastid", &id)
db.Commit()
if db.Error != nil {
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "Error in add. " + db.Error.Error(),
})
return
}
intRowsCount := int(rowsCount)
for i := 1; i <= intRowsCount; i++ {
createdIDs = append(createdIDs, id[0]-(intRowsCount-i))
}
// Add M2M records
// No need to delete existing m2m records because it
// is a new model
// Insert records
db = GetDB().Begin()
for i := range m2mFields {
table1 := schema.ModelName
for m2mModelName := range m2mFields[i] {
t2Schema, _ := getSchema(m2mModelName)
table2 := t2Schema.ModelName
for _, id := range strings.Split(m2mFields[i][m2mModelName], ",") {
if m2mFields[i][m2mModelName] == "" {
continue
}
sql := sqlDialect[Database.Type]["insertM2M"]
sql = strings.Replace(sql, "{TABLE1}", table1, -1)
sql = strings.Replace(sql, "{TABLE2}", table2, -1)
db = db.Exec(sql, createdIDs[i], id)
}
}
}
db.Commit()
returnDAPIJSON(w, r, map[string]interface{}{
"status": "ok",
"rows_count": rowsCount,
"id": createdIDs,
}, params, "add", model.Interface())
if log {
for i := range createdIDs {
createAPIAddLog(q, args, GetDB().Config.NamingStrategy.ColumnName("", model.Type().Name()), createdIDs[i], s, r)
}
}
} else {
// Error: Unknown format
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "invalid format (" + r.URL.Path + ")",
})
return
}
}
func customParamsAdd(params map[string]string, m reflect.Value, s *Session) map[string]string {
if m.FieldByName("CreatedAt").Kind() != reflect.Invalid {
params["_created_at"] = time.Now().Format("2006-01-02 15:04:05")
}
if m.FieldByName("CreatedBy").Kind() != reflect.Invalid && s != nil {
if m.FieldByName("CreatedBy").Kind() == reflect.String {
params["_created_by"] = s.User.Username
}
if m.FieldByName("CreatedByID").Kind() == reflect.Uint {
params["_created_by_id"] = fmt.Sprint(s.UserID)
}
}
return params
}
func getAddFilters(params map[string]string, schema *ModelSchema) (query []string, args [][]interface{}, m2m []map[string]string) {
query = []string{}
args = [][]interface{}{}
m2m = []map[string]string{}
// Check if we have to add one or multiple
addOne := true
for k := range params {
if k[0] != '_' {
continue
}
if strings.Contains(k[1:], "__") {
addOne = false
break
}
}
if addOne {
// Add one
itemArgs := []interface{}{}
itemQ := []string{}
itemM2M := map[string]string{}
for k, v := range params {
if k[0] != '_' {
continue
}
// Process M2M
fDBName := getWriteQueryFields(k)
fDBName = fDBName[1 : len(fDBName)-1]
isM2M := false
for _, f := range schema.Fields {
if f.ColumnName == fDBName && f.Type == cM2M {
itemM2M[strings.ToLower(f.TypeName)] = v
isM2M = true
break
}
}
if isM2M {
continue
}
itemQ = append(itemQ, getWriteQueryFields(k))
itemArgs = append(itemArgs, getAddQueryArg(v))
}
query = append(query, strings.Join(itemQ, ", "))
args = append(args, itemArgs)
m2m = append(m2m, itemM2M)
} else {
// Add Multiple
index := 0
var indexExists bool
var itemArgs []interface{}
var itemQ []string
var itemM2M map[string]string
for {
indexExists = false
itemArgs = []interface{}{}
itemQ = []string{}
itemM2M = map[string]string{}
// Check if index exists
for k := range params {
if k[0] != '_' {
continue
}
if strings.Contains(k[1:], fmt.Sprintf("__%d", index)) {
indexExists = true
break
}
}
if !indexExists {
break
}
// build query and args
for k, v := range params {
if k[0] != '_' {
continue
}
queryParts := strings.Split(k[1:], "__")
paramIndex := 0
if len(queryParts) == 2 {
tmp, _ := strconv.ParseInt(queryParts[1], 10, 64)
paramIndex = int(tmp)
}
// if strings.Contains(k[1:], fmt.Sprintf("__%d", index)) {
if paramIndex == index {
// Add it
k = strings.TrimSuffix(k, fmt.Sprintf("__%d", index))
// Process M2M
fDBName := getWriteQueryFields(k)
fDBName = fDBName[1 : len(fDBName)-1]
isM2M := false
for _, f := range schema.Fields {
if f.ColumnName == fDBName && f.Type == cM2M {
itemM2M[strings.ToLower(f.TypeName)] = v
isM2M = true
break
}
}
if isM2M {
continue
}
itemQ = append(itemQ, getWriteQueryFields(k))
itemArgs = append(itemArgs, getAddQueryArg(v))
} else if !strings.Contains(k[1:], "__") {
// Add it
// Process M2M
fDBName := getWriteQueryFields(k)
fDBName = fDBName[1 : len(fDBName)-1]
isM2M := false
for _, f := range schema.Fields {
if f.ColumnName == fDBName && f.Type == cM2M {
itemM2M[strings.ToLower(f.TypeName)] = v
isM2M = true
break
}
}
if isM2M {
continue
}
itemQ = append(itemQ, getWriteQueryFields(k))
itemArgs = append(itemArgs, getAddQueryArg(v))
}
}
query = append(query, strings.Join(itemQ, ", "))
args = append(args, itemArgs)
m2m = append(m2m, itemM2M)
index++
}
}
return query, args, m2m
}
func getAddQueryArg(v string) interface{} {
var err error
v, err = url.QueryUnescape(v)
if err != nil {
Trail(WARNING, "getAddQueryArg url.QueryUnescape unable to unescape value. %s", err)
return []interface{}{v}
}
return v
}
func createAPIAddLog(q []string, args [][]interface{}, tableName string, ID int, session *Session, r *http.Request) {
// TODO: Fix mismatch field name and value assignment
// in JSON object for Activity field in Logs
nameMap := map[string]string{}
for _, f := range Schema[tableName].Fields {
nameMap[f.ColumnName] = f.Name
}
for counter := range q {
q1 := q[counter]
args1 := args[counter]
qParts := strings.Split(q1, ", ")
vals := map[string]interface{}{
"_IP": GetRemoteIP(r),
}
index := 0
for k, v := range nameMap {
exists := false
for i := range qParts {
if qParts[i] == k {
exists = true
break
}
}
if exists {
vals[v] = args1[index]
index++
} else {
vals[v] = ""
}
}
b, _ := json.Marshal(vals)
username := ""
if session != nil {
username = session.User.Username
}
log := Log{
Username: username,
Action: Action(0).Added(),
TableName: tableName,
TableID: ID,
Activity: string(b),
}
log.Save()
}
}