forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
d_api.go
288 lines (257 loc) · 8.96 KB
/
d_api.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
package uadmin
import (
"context"
"net/http"
"strconv"
"strings"
)
const dAPIHelp = `
Data Access API Help (dAPI)
===========================
Command:
========
URL Command
======================================================================================================
/modelname/read/ Read Multiple
/modelname/read/1/ Read One
/modelname/add/?f__0=0&f__1=1 Add Multiple
/modelname/add/ Add One
/modelname/edit/?f=1&_f=0 Edit Multiple
/modelname/edit/1/ Edit One
/modelname/delete/?f=1 Delete Multiple
/modelname/delete/1/ Delete One
/modelname/method/METHOD_NAME/1/ Run method on model where id=1
/modelname/schema/ Schema
/$allmodels/ All Models
Field Filtering:
================
Filter Description
======================================================================================================
__gt Greater Than
__gte Greater Than or Equal To
__lt Less Than
__lte Less Than or Equal To
__in Find a value matching any of these values
__is Stands for IS NULL
__contains Search for string values that contains
__between Selects values within a given range
__startswith Search for string values that starts with a given substring
__endswith Search for string values that ends with a given substring
__re Regex
__icontains Similar to __contains except it is case insensitive
__istartswith Similar to __startswith except it is case insensitive
__iendswith Similar to __endswith except it is case insensitive
!{FIELD}__{OP} Negates the operator e.g. !id__in means: id NOT IN (?)
$or=f=0|f=1 OR operator (f=0 OR f=1)
$or=f1=0+f2=0|f=1 OR operator with a nested AND ((f1=0 AND f2=0) OR f=1)
URL Symbols:
============
Symbol Description Example
=======================================================================================================
- Descending Order $order=-fieldname
_ Writing Data (Add/Edit) $_f=f1
Special Parameters:
===================
Query Description
======================================================================================================
$limit=1 Number of records that you want to return
$offset=1 Starting point to read in the list of records
$order=f1,-f Used to sort the results. Use "-" for descending order and comma for
more field
$f=f1,f2 Selecting Fields
$groupby=f Groups rows that have the same values into summary rows
$deleted=1 Returns results including deleted records
$join=[inner__]m[__f] Joins results from another model based on a foreign key
$m2m={0,1,fill,id} Returns results from M2M fields where:
0 : Don't return
[1,fill]: Return all fields
id : Only return IDs
$m2m=f__{id,fill} Returns results from a specific M2M field
$q=abc Searches all string based fields for read, edit, and delete requests
$preload={0,1} Fills the data from foreign keys into structs
0 : Don't return
1 : Return preloaded data
$next=/ Used in read method that redirects the user to the specified path
after processing the request
$back: Send the user back
$stat=1 Returns the query execution time in milliseconds
Aggregation Operators:
======================
Operator Description
======================================================================================================
__sum Used in $f that returns the total sum of a numeric field
__avg Used in $f that returns the average value of a numeric field
__min Used in $f that returns the smallest value of the selected column
__max Used in $f that returns the largest value of the selected column
__count Used in $f that returns the number of rows that matches a specified criteria
__date Used in $f that returns DATE() of the field
__year Used in $f that returns YEAR() of the field
__month Used in $f that returns MONTH() of the field
__day Used in $f that returns DAY() of the field
For full documentation: https://uadmin-docs.readthedocs.io/en
/latest/dapi.html
`
// CKey is the standard key used in uAdmin for context keys
type CKey string
func dAPIHandler(w http.ResponseWriter, r *http.Request, s *Session) {
// Parse the Form
err := r.ParseMultipartForm(2 << 10)
if err != nil {
r.ParseForm()
}
// Add Custom headers
for k, v := range CustomDAPIHeaders {
w.Header().Add(k, v)
}
r.URL.Path = strings.TrimPrefix(r.URL.Path, RootURL+"api/d")
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/")
r.URL.Path = strings.TrimSuffix(r.URL.Path, "/")
urlParts := strings.Split(r.URL.Path, "/")
ctx := context.WithValue(r.Context(), CKey("dAPI"), true)
r = r.WithContext(ctx)
// auth dAPI
if urlParts[0] == "auth" {
dAPIAuthHandler(w, r, s)
return
}
if urlParts[0] == "$allmodels" {
if !s.User.Admin {
w.WriteHeader(http.StatusForbidden)
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "access denied",
})
}
dAPIAllModelsHandler(w, r, s)
return
}
// Check if there is no command and show help
if r.URL.Path == "" || r.URL.Path == "help" {
if s == nil {
w.WriteHeader(http.StatusForbidden)
ReturnJSON(w, r, map[string]interface{}{
"status": "error",
"err_msg": "access denied",
})
return
}
w.Write([]byte(dAPIHelp))
return
}
// sanity check
// check model name
modelExists := false
var model interface{}
for k, v := range models {
if urlParts[0] == k {
modelExists = true
model = v
// add model to context
ctx := context.WithValue(r.Context(), CKey("modelName"), urlParts[0])
r = r.WithContext(ctx)
// trim model name from URL
r.URL.Path = strings.TrimPrefix(r.URL.Path, urlParts[0])
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/")
break
}
}
if !modelExists {
w.WriteHeader(404)
ReturnJSON(w, r, map[string]string{
"status": "error",
"err_msg": "Model name not found (" + urlParts[0] + ")",
})
return
}
//check command
commandExists := false
command := ""
secondPartIsANumber := false
if len(urlParts) > 1 {
if _, err := strconv.Atoi(urlParts[1]); err == nil {
secondPartIsANumber = true
}
}
if len(urlParts) > 1 && !secondPartIsANumber {
for _, i := range []string{"read", "add", "edit", "delete", "schema", "method"} {
if urlParts[1] == i {
commandExists = true
command = i
// trim command from URL
r.URL.Path = strings.TrimPrefix(r.URL.Path, urlParts[1])
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/")
break
}
}
} else {
commandExists = true
switch r.Method {
case http.MethodGet:
command = "read"
case http.MethodPost:
command = "add"
case http.MethodPut:
command = "edit"
case http.MethodDelete:
command = "delete"
}
}
if !commandExists {
w.WriteHeader(404)
ReturnJSON(w, r, map[string]string{
"status": "error",
"err_msg": "Invalid command (" + command + ")",
})
return
}
// Route the request to the correct handler based on the command
if command == "read" {
// check if there is a prequery
if preQuery, ok := model.(APIPreQueryReader); ok && !preQuery.APIPreQueryRead(w, r) {
} else {
dAPIReadHandler(w, r, s)
}
return
}
if command == "add" {
if preQuery, ok := model.(APIPreQueryAdder); ok && !preQuery.APIPreQueryAdd(w, r) {
} else {
dAPIAddHandler(w, r, s)
}
return
}
if command == "edit" {
// check if there is a prequery
if preQuery, ok := model.(APIPreQueryEditor); ok && !preQuery.APIPreQueryEdit(w, r) {
} else {
dAPIEditHandler(w, r, s)
}
return
}
if command == "delete" {
// check if there is a prequery
if preQuery, ok := model.(APIPreQueryDeleter); ok && !preQuery.APIPreQueryDelete(w, r) {
} else {
dAPIDeleteHandler(w, r, s)
}
return
}
if command == "schema" {
// check if there is a prequery
if preQuery, ok := model.(APIPreQuerySchemer); ok && !preQuery.APIPreQuerySchema(w, r) {
} else {
dAPISchemaHandler(w, r, s)
}
return
}
if command == "method" {
dAPIMethodHandler(w, r, s)
if r.URL.Query().Get("$next") != "" {
if strings.HasPrefix(r.URL.Query().Get("$next"), "$back") && r.Header.Get("Referer") != "" {
http.Redirect(w, r, r.Header.Get("Referer")+strings.TrimPrefix(r.URL.Query().Get("$next"), "$back"), http.StatusSeeOther)
} else {
http.Redirect(w, r, r.URL.Query().Get("$next"), http.StatusSeeOther)
}
}
}
}