forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd_api_read.go
246 lines (221 loc) · 5.55 KB
/
d_api_read.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
package uadmin
import (
"database/sql"
"encoding/json"
"net/http"
"reflect"
"strings"
)
func dAPIReadHandler(w http.ResponseWriter, r *http.Request, s *Session) {
var err error
var rowsCount int64
urlParts := strings.Split(r.URL.Path, "/")
modelName := urlParts[0]
model, _ := NewModel(modelName, false)
params := getURLArgs(r)
schema, _ := getSchema(modelName)
// Check permission
allow := false
if disableReader, ok := model.Interface().(APIDisabledReader); ok {
allow = disableReader.APIDisabledRead(r)
// This is a "Disable" method
allow = !allow
if !allow {
w.WriteHeader(401)
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "Permission denied",
})
return
}
}
if publicReader, ok := model.Interface().(APIPublicReader); ok {
allow = publicReader.APIPublicRead(r)
}
if !allow && s != nil {
allow = s.User.GetAccess(modelName).Read
}
if !allow {
w.WriteHeader(401)
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "Permission denied",
})
return
}
// Check if log is required
log := APILogRead
if logReader, ok := model.Interface().(APILogReader); ok {
log = logReader.APILogRead(r)
}
// Run prequery handler
if preQueryReader, ok := model.Interface().(APIPreQueryReader); ok {
if !preQueryReader.APIPreQueryRead(w, r) {
return
}
}
if len(urlParts) == 2 {
// Read Multiple
var m interface{}
SQL := "SELECT {FIELDS} FROM {TABLE_NAME}"
if val, ok := params["$distinct"]; ok && val == "1" {
SQL = "SELECT DISTINCT {FIELDS} FROM {TABLE_NAME}"
}
tableName := schema.TableName
SQL = strings.Replace(SQL, "{TABLE_NAME}", tableName, -1)
f, customSchema := getQueryFields(r, params, tableName)
if f != "" {
SQL = strings.Replace(SQL, "{FIELDS}", f, -1)
} else {
SQL = strings.Replace(SQL, "{FIELDS}", "*", -1)
}
join := getQueryJoin(r, params, tableName)
if join != "" {
SQL += " " + join
}
q, args := getFilters(r, params, tableName, &schema)
if q != "" {
SQL += " WHERE " + q
}
groupBy := getQueryGroupBy(r, params)
if groupBy != "" {
SQL += " GROUP BY " + groupBy
}
order := getQueryOrder(r, params)
if order != "" {
SQL += " ORDER BY " + order
}
limit := getQueryLimit(r, params)
if limit != "" {
SQL += " LIMIT " + limit
}
offset := getQueryOffset(r, params)
if offset != "" {
SQL += " OFFSET " + offset
}
if DebugDB {
Trail(DEBUG, SQL)
Trail(DEBUG, "%#v", args)
}
var rows *sql.Rows
if !customSchema {
mArray, _ := NewModelArray(modelName, true)
m = mArray.Interface()
} else {
m = []map[string]interface{}{}
}
if Database.Type == "mysql" {
db := GetDB()
if !customSchema {
db.Raw(SQL, args...).Scan(m)
} else {
rows, err = db.Raw(SQL, args...).Rows()
if err != nil {
w.WriteHeader(500)
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "Unable to execute SQL. " + err.Error(),
})
Trail(ERROR, "SQL: %v\nARGS: %v", SQL, args)
return
}
m = parseCustomDBSchema(rows)
}
if a, ok := m.([]map[string]interface{}); ok {
rowsCount = int64(len(a))
} else {
rowsCount = int64(reflect.ValueOf(m).Elem().Len())
}
} else if Database.Type == "sqlite" {
db := GetDB().Begin()
db.Exec("PRAGMA case_sensitive_like=ON;")
if !customSchema {
db.Raw(SQL, args...).Scan(m)
} else {
rows, err = db.Raw(SQL, args...).Rows()
if err != nil {
w.WriteHeader(500)
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "Unable to execute SQL. " + err.Error(),
})
Trail(ERROR, "SQL: %v\nARGS: %v", SQL, args)
return
}
m = parseCustomDBSchema(rows)
}
db.Exec("PRAGMA case_sensitive_like=OFF;")
db.Commit()
if a, ok := m.([]map[string]interface{}); ok {
rowsCount = int64(len(a))
} else {
rowsCount = int64(reflect.ValueOf(m).Elem().Len())
}
}
// Preload
if params["$preload"] == "1" {
mList := reflect.ValueOf(m)
for i := 0; i < mList.Elem().Len(); i++ {
Preload(mList.Elem().Index(i).Addr().Interface())
}
}
// Process M2M
getQueryM2M(params, m, customSchema, modelName)
returnDAPIJSON(w, r, map[string]interface{}{
"status": "ok",
"result": m,
}, params, "read", model.Interface())
go func() {
if log {
createAPIReadLog(modelName, 0, rowsCount, params, &s.User, r)
}
}()
return
} else if len(urlParts) == 3 {
// Read One
m, _ := NewModel(modelName, true)
Get(m.Interface(), "id = ?", urlParts[2])
rowsCount = 0
var i interface{}
if int(GetID(m)) != 0 {
i = m.Interface()
rowsCount = 1
}
if params["$preload"] == "1" {
Preload(m.Interface())
}
returnDAPIJSON(w, r, map[string]interface{}{
"status": "ok",
"result": i,
}, params, "read", model.Interface())
go func() {
if log {
createAPIReadLog(modelName, int(GetID(m)), rowsCount, map[string]string{"id": urlParts[2]}, &s.User, r)
}
}()
} else {
// Error: Unknown format
w.WriteHeader(404)
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "invalid format (" + r.URL.Path + ")",
})
return
}
}
func createAPIReadLog(modelName string, ID int, rowsCount int64, params map[string]string, user *User, r *http.Request) {
vals := map[string]interface{}{
"params": params,
"rows_count": rowsCount,
"_IP": r.RemoteAddr,
}
output, _ := json.Marshal(vals)
log := Log{
Username: user.Username,
Action: Action(0).Read(),
TableName: modelName,
TableID: ID,
Activity: string(output),
}
log.Save()
}