/
endpoints-requests.go
389 lines (288 loc) · 10.2 KB
/
endpoints-requests.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
381
382
383
384
385
386
387
388
389
package main
import (
"fmt"
"sort"
"time"
"net/http"
"github.com/caTUstrophy/backend/db"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator"
"github.com/leebenson/conform"
"github.com/nferruzzi/gormGIS"
"github.com/satori/go.uuid"
)
// Structs.
type CreateRequestPayload struct {
Name string `conform:"trim" validate:"required"`
Location struct {
Longitude float64 `json:"lng" conform:"trim"`
Latitude float64 `json:"lat" conform:"trim"`
} `validate:"dive,required"`
Radius float64 `validate:"required"`
Tags []string `conform:"trim" validate:"dive,excludesall=!@#$%^&*()_+-=:;?/0x2C0x7C"`
Description string `conform:"trim"`
ValidityPeriod string `conform:"trim" validate:"required"`
}
type UpdateRequestPayload struct {
Name string `conform:"trim"`
Location struct {
Longitude float64 `json:"lng" conform:"trim"`
Latitude float64 `json:"lat" conform:"trim"`
} `validate:"dive"`
Radius float64
Tags []string `conform:"trim" validate:"dive,excludesall=!@#$%^&*()_+-=:;?/0x2C0x7C"`
Description string `conform:"trim"`
ValidityPeriod string `conform:"trim"`
Matched bool `conform:"trim"`
}
// Functions
func (app *App) CreateRequest(c *gin.Context) {
// Check authorization for this function.
ok, User, message := app.Authorize(c.Request)
if !ok {
// Signal client an error and expect authorization.
c.Header("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"CaTUstrophy\", error=\"invalid_token\", error_description=\"%s\"", message))
c.Status(http.StatusUnauthorized)
return
}
var Payload CreateRequestPayload
// Expect request struct fields for creation in JSON request body.
err := c.BindJSON(&Payload)
if err != nil {
// Check if error was caused by failed unmarshalling string -> []string.
if err.Error() == "json: cannot unmarshal string into Go value of type []string" {
c.JSON(http.StatusBadRequest, gin.H{
"Tags": "Provide an array, not a string",
})
return
}
c.JSON(http.StatusBadRequest, gin.H{
"Error": "Supplied values in JSON body could not be parsed",
})
return
}
// Validate sent request creation data.
conform.Strings(&Payload)
errs := app.Validator.Struct(&Payload)
if errs != nil {
errResp := make(map[string]string)
// Iterate over all validation errors.
for _, err := range errs.(validator.ValidationErrors) {
if err.Tag == "required" {
errResp[err.Field] = "Is required"
} else if err.Tag == "excludesall" {
errResp[err.Field] = "Contains unallowed characters"
}
}
// Send prepared error message to client.
c.JSON(http.StatusBadRequest, errResp)
return
}
var Request db.Request
// Set insert struct to values from payload.
Request.ID = fmt.Sprintf("%s", uuid.NewV4())
Request.Name = Payload.Name
Request.User = *User
Request.UserID = User.ID
Request.Location = gormGIS.GeoPoint{Lng: Payload.Location.Longitude, Lat: Payload.Location.Latitude}
Request.Description = Payload.Description
Request.Radius = Payload.Radius
Request.Tags = make([]db.Tag, 0)
// If tags were supplied, check if they exist in our system.
if len(Payload.Tags) > 0 {
// Retrieve all currently available tags from database.
var Tags []db.Tag
app.DB.Find(&Tags)
// Make tags list searchable in fast time.
sort.Sort(db.TagsByName(Tags))
allTagsExist := true
for _, tag := range Payload.Tags {
// Find tag in sorted tags list.
i := sort.Search(len(Tags), func(i int) bool {
return Tags[i].Name >= tag
})
if i < len(Tags) && Tags[i].Name == tag {
// We found the supplied tag, add it to tags list.
Request.Tags = append(Request.Tags, Tags[i])
} else {
// Set flag to false, if one tag was not found.
allTagsExist = false
}
}
// If at least one of the tags does not exist - return error.
if !allTagsExist {
c.JSON(http.StatusBadRequest, gin.H{
"Tags": "One or multiple tags do not exist",
})
return
}
} else {
Request.Tags = nil
}
// Check if supplied date is a RFC3339 compliant date.
PayloadTime, err := time.Parse(time.RFC3339, Payload.ValidityPeriod)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"ValidityPeriod": "Request has to be a RFC3339 compliant date",
})
return
}
// Check if validity period is yet to come.
if PayloadTime.Unix() <= time.Now().Unix() {
c.JSON(http.StatusBadRequest, gin.H{
"ValidityPeriod": "Request has to be valid until a date in the future",
})
return
} else {
Request.ValidityPeriod = PayloadTime
Request.Expired = false
}
// Try to map the provided location to all containing regions.
app.MapLocationToRegions(Request)
// Save request to database.
app.DB.Create(&Request)
// Load all regions to which we just mapped the request's location.
app.DB.Preload("Regions").First(&Request)
// Calculate the matching score of this request with all possible offers.
go app.CalcMatchScoreForRequest(Request)
model := CopyNestedModel(Request, fieldsRequestWithUser)
c.JSON(http.StatusCreated, model)
}
func (app *App) GetRequest(c *gin.Context) {
// Check authorization for this function.
ok, User, message := app.Authorize(c.Request)
if !ok {
// Signal client an error and expect authorization.
c.Header("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"CaTUstrophy\", error=\"invalid_token\", error_description=\"%s\"", message))
c.Status(http.StatusUnauthorized)
return
}
// Parse requestID from HTTP request.
requestID := app.getUUID(c, "requestID")
if requestID == "" {
c.JSON(http.StatusBadRequest, gin.H{
"Error": "requestID is no valid UUID",
})
return
}
// Load request from database.
var request db.Request
app.DB.Preload("Regions").Preload("Tags").First(&request, "id = ?", requestID)
app.DB.Model(&request).Related(&request.User)
// Validity check:
// User accessing this request has to be either an admin in any region
if ok := ((request.UserID == User.ID) || app.CheckScopes(User, request.Regions, "admin")); !ok {
// Signal client that the provided authorization was not sufficient.
c.Header("WWW-Authenticate", "Bearer realm=\"CaTUstrophy\", error=\"authentication_failed\", error_description=\"Could not authenticate the request\"")
c.Status(http.StatusUnauthorized)
return
}
// He or she can have it, if he or she wants it so badly! :)
model := CopyNestedModel(request, fieldsRequestWithUser)
c.JSON(http.StatusOK, model)
}
func (app *App) UpdateRequest(c *gin.Context) {
// Check authorization for this function.
ok, User, message := app.Authorize(c.Request)
if !ok {
// Signal client an error and expect authorization.
c.Header("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"CaTUstrophy\", error=\"invalid_token\", error_description=\"%s\"", message))
c.Status(http.StatusUnauthorized)
return
}
// Parse requestID from HTTP request.
requestID := app.getUUID(c, "requestID")
if requestID == "" {
c.JSON(http.StatusBadRequest, gin.H{
"Error": "requestID is no valid UUID",
})
return
}
// Load request from database.
var Request db.Request
app.DB.Preload("Regions").Preload("Tags").First(&Request, "\"id\" = ?", requestID)
app.DB.Model(&Request).Related(&Request.User)
// Check scope for user / admin on request.
if ok := ((Request.UserID == User.ID) || app.CheckScopes(User, Request.Regions, "admin")); !ok {
// Signal client that the provided authorization was not sufficient.
c.Header("WWW-Authenticate", "Bearer realm=\"CaTUstrophy\", error=\"authentication_failed\", error_description=\"Could not authenticate the request\"")
c.Status(http.StatusUnauthorized)
return
}
// Bind payload.
var Payload UpdateRequestPayload
if ok := app.ValidatePayloadShort(c, &Payload); !ok {
return
}
Request.Name = Payload.Name
Request.Location = gormGIS.GeoPoint{Lng: Payload.Location.Longitude, Lat: Payload.Location.Latitude}
Request.Radius = Payload.Radius
Request.Description = Payload.Description
// If tags were supplied, check if they exist in our system.
if len(Payload.Tags) > 0 {
// Delete all tags associated with request.
for _, Tag := range Request.Tags {
app.DB.Exec("DELETE FROM \"request_tags\" WHERE \"request_id\" = ? AND \"tag_name\" = ?", Request.ID, Tag.Name)
}
Request.Tags = make([]db.Tag, 0)
allTagsExist := true
for _, tag := range Payload.Tags {
var Tag db.Tag
// Count number of results for query of name of tags.
app.DB.First(&Tag, "\"name\" = ?", tag)
// Set flag to false, if one tag was not found.
if Tag.Name == "" {
allTagsExist = false
} else {
Request.Tags = append(Request.Tags, Tag)
}
}
// If at least one of the tags does not exist - return error.
if !allTagsExist {
c.JSON(http.StatusBadRequest, gin.H{
"Tags": "One or multiple tags do not exist",
})
return
}
} else {
Request.Tags = nil
}
if Payload.ValidityPeriod != "" {
// Check if supplied date is a RFC3339 compliant date.
PayloadTime, err := time.Parse(time.RFC3339, Payload.ValidityPeriod)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"ValidityPeriod": "Request has to be a RFC3339 compliant date",
})
return
}
// Check if validity period is yet to come.
if PayloadTime.Unix() <= time.Now().Unix() {
c.JSON(http.StatusBadRequest, gin.H{
"ValidityPeriod": "Request has to be valid until a date in the future",
})
return
} else {
Request.ValidityPeriod = PayloadTime
Request.Expired = false
}
}
// With this check we discriminate the one position on earth
// where latitude = 0 and longitude = 0 as an update. I am really
// sorry for this, but that is the only reasonable check here.
if Payload.Location.Latitude != 0.0 || Payload.Location.Longitude != 0.0 {
// Delete all regions associated with request.
app.DB.Exec("DELETE FROM \"region_requests\" WHERE \"request_id\" = ?", Request.ID)
Request.Regions = []db.Region{}
// Try to map the provided location to all containing regions.
app.MapLocationToRegions(Request)
}
// Update request in database.
app.DB.Model(&Request).Updates(Request)
// Load all regions to which we just mapped the request's location.
app.DB.Preload("Regions").First(&Request)
// Calculate the matching score of this request with all possible offers.
go app.CalcMatchScoreForRequest(Request)
model := CopyNestedModel(Request, fieldsRequestWithUser)
c.JSON(http.StatusOK, model)
}